xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 7c478bd95313f5f23a4c958a745db2134aa03244)
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 (mctl_present && io->ipsec_out_attach_if) {
6631 		/* ip_grab_attach_ill returns a held ill */
6632 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
6633 		    io->ipsec_out_ill_index, B_FALSE);
6634 
6635 		/* Failure case frees things for us. */
6636 		if (attach_ill == NULL)
6637 			return;
6638 
6639 		/*
6640 		 * Check if we need an ire that will not be
6641 		 * looked up by anybody else i.e. HIDDEN.
6642 		 */
6643 		if (ill_is_probeonly(attach_ill))
6644 			ire_marks = IRE_MARK_HIDDEN;
6645 	}
6646 	/*
6647 	 * If this IRE is created for forwarding or it is not for
6648 	 * traffic for congestion controlled protocols, mark it as temporary.
6649 	 */
6650 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
6651 		ire_marks |= IRE_MARK_TEMPORARY;
6652 
6653 	/*
6654 	 * Get what we can from ire_ftable_lookup which will follow an IRE
6655 	 * chain until it gets the most specific information available.
6656 	 * For example, we know that there is no IRE_CACHE for this dest,
6657 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
6658 	 * ire_ftable_lookup will look up the gateway, etc.
6659 	 * Check if in_ill != NULL. If it is true, the packet must be
6660 	 * from an incoming interface where RTA_SRCIFP is set.
6661 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
6662 	 * to the destination, of equal netmask length in the forward table,
6663 	 * will be recursively explored. If no information is available
6664 	 * for the final gateway of that route, we force the returned ire
6665 	 * to be equal to sire using MATCH_IRE_PARENT.
6666 	 * At least, in this case we have a starting point (in the buckets)
6667 	 * to look for other routes to the destination in the forward table.
6668 	 * This is actually used only for multirouting, where a list
6669 	 * of routes has to be processed in sequence.
6670 	 */
6671 	if (in_ill != NULL) {
6672 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
6673 		    in_ill, MATCH_IRE_TYPE);
6674 	} else if (attach_ill == NULL) {
6675 		ire = ire_ftable_lookup(dst, 0, 0, 0,
6676 		    NULL, &sire, zoneid, 0,
6677 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
6678 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT);
6679 	} else {
6680 		/*
6681 		 * attach_ill is set only for communicating with
6682 		 * on-link hosts. So, don't look for DEFAULT.
6683 		 */
6684 		ipif_t	*attach_ipif;
6685 
6686 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
6687 		if (attach_ipif == NULL) {
6688 			ill_refrele(attach_ill);
6689 			goto icmp_err_ret;
6690 		}
6691 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
6692 		    &sire, zoneid, 0,
6693 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL);
6694 		ipif_refrele(attach_ipif);
6695 	}
6696 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
6697 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
6698 
6699 	/*
6700 	 * This loop is run only once in most cases.
6701 	 * We loop to resolve further routes only when the destination
6702 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
6703 	 */
6704 	do {
6705 		/* Clear the previous iteration's values */
6706 		if (src_ipif != NULL) {
6707 			ipif_refrele(src_ipif);
6708 			src_ipif = NULL;
6709 		}
6710 		if (dst_ill != NULL) {
6711 			ill_refrele(dst_ill);
6712 			dst_ill = NULL;
6713 		}
6714 
6715 		multirt_resolve_next = B_FALSE;
6716 		/*
6717 		 * We check if packets have to be multirouted.
6718 		 * In this case, given the current <ire, sire> couple,
6719 		 * we look for the next suitable <ire, sire>.
6720 		 * This check is done in ire_multirt_lookup(),
6721 		 * which applies various criteria to find the next route
6722 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
6723 		 * unchanged if it detects it has not been tried yet.
6724 		 */
6725 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
6726 			ip3dbg(("ip_newroute: starting next_resolution "
6727 			    "with first_mp %p, tag %d\n",
6728 			    (void *)first_mp,
6729 			    MULTIRT_DEBUG_TAGGED(first_mp)));
6730 
6731 			ASSERT(sire != NULL);
6732 			multirt_is_resolvable =
6733 			    ire_multirt_lookup(&ire, &sire, multirt_flags);
6734 
6735 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
6736 			    "ire %p, sire %p\n",
6737 			    multirt_is_resolvable,
6738 			    (void *)ire, (void *)sire));
6739 
6740 			if (!multirt_is_resolvable) {
6741 				/*
6742 				 * No more multirt route to resolve; give up
6743 				 * (all routes resolved or no more
6744 				 * resolvable routes).
6745 				 */
6746 				if (ire != NULL) {
6747 					ire_refrele(ire);
6748 					ire = NULL;
6749 				}
6750 			} else {
6751 				ASSERT(sire != NULL);
6752 				ASSERT(ire != NULL);
6753 				/*
6754 				 * We simply use first_sire as a flag that
6755 				 * indicates if a resolvable multirt route
6756 				 * has already been found.
6757 				 * If it is not the case, we may have to send
6758 				 * an ICMP error to report that the
6759 				 * destination is unreachable.
6760 				 * We do not IRE_REFHOLD first_sire.
6761 				 */
6762 				if (first_sire == NULL) {
6763 					first_sire = sire;
6764 				}
6765 			}
6766 		}
6767 		if (ire == NULL) {
6768 			if (ip_debug > 3) {
6769 				/* ip2dbg */
6770 				pr_addr_dbg("ip_newroute: "
6771 				    "can't resolve %s\n", AF_INET, &dst);
6772 			}
6773 			ip3dbg(("ip_newroute: "
6774 			    "ire %p, sire %p, first_sire %p\n",
6775 			    (void *)ire, (void *)sire, (void *)first_sire));
6776 
6777 			if (sire != NULL) {
6778 				ire_refrele(sire);
6779 				sire = NULL;
6780 			}
6781 
6782 			if (first_sire != NULL) {
6783 				/*
6784 				 * At least one multirt route has been found
6785 				 * in the same call to ip_newroute();
6786 				 * there is no need to report an ICMP error.
6787 				 * first_sire was not IRE_REFHOLDed.
6788 				 */
6789 				MULTIRT_DEBUG_UNTAG(first_mp);
6790 				freemsg(first_mp);
6791 				return;
6792 			}
6793 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
6794 			    RTA_DST);
6795 			if (attach_ill != NULL)
6796 				ill_refrele(attach_ill);
6797 			goto icmp_err_ret;
6798 		}
6799 
6800 		/*
6801 		 * When RTA_SRCIFP is used to add a route, then an interface
6802 		 * route is added in the source interface's routing table.
6803 		 * If the outgoing interface of this route is of type
6804 		 * IRE_IF_RESOLVER, then upon creation of the ire,
6805 		 * ire_dlureq_mp is set to NULL. Later, when this route is
6806 		 * first used for forwarding packet, ip_newroute() is called
6807 		 * to resolve the hardware address of the outgoing ipif.
6808 		 * We do not come here for IRE_IF_NORESOLVER entries in the
6809 		 * source interface based table. We only come here if the
6810 		 * outgoing interface is a resolver interface and we don't
6811 		 * have the ire_dlureq_mp information yet.
6812 		 * If in_ill is not null that means it is called from
6813 		 * ip_rput.
6814 		 */
6815 
6816 		ASSERT(ire->ire_in_ill == NULL ||
6817 		    (ire->ire_type == IRE_IF_RESOLVER &&
6818 		    ire->ire_dlureq_mp == NULL));
6819 
6820 		/*
6821 		 * Verify that the returned IRE does not have either
6822 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
6823 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
6824 		 */
6825 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
6826 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
6827 			if (attach_ill != NULL)
6828 				ill_refrele(attach_ill);
6829 			goto icmp_err_ret;
6830 		}
6831 		/*
6832 		 * Increment the ire_ob_pkt_count field for ire if it is an
6833 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
6834 		 * increment the same for the parent IRE, sire, if it is some
6835 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
6836 		 * and HOST_REDIRECT).
6837 		 */
6838 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
6839 			UPDATE_OB_PKT_COUNT(ire);
6840 			ire->ire_last_used_time = lbolt;
6841 		}
6842 
6843 		if (sire != NULL) {
6844 			gw = sire->ire_gateway_addr;
6845 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
6846 			    IRE_INTERFACE)) == 0);
6847 			UPDATE_OB_PKT_COUNT(sire);
6848 			sire->ire_last_used_time = lbolt;
6849 		}
6850 		/*
6851 		 * We have a route to reach the destination.
6852 		 *
6853 		 * 1) If the interface is part of ill group, try to get a new
6854 		 *    ill taking load spreading into account.
6855 		 *
6856 		 * 2) After selecting the ill, get a source address that
6857 		 *    might create good inbound load spreading.
6858 		 *    ipif_select_source does this for us.
6859 		 *
6860 		 * If the application specified the ill (ifindex), we still
6861 		 * load spread. Only if the packets needs to go out
6862 		 * specifically on a given ill e.g. binding to
6863 		 * IPIF_NOFAILOVER address, then we don't try to use a
6864 		 * different ill for load spreading.
6865 		 */
6866 		if (attach_ill == NULL) {
6867 			/*
6868 			 * Don't perform outbound load spreading in the
6869 			 * case of an RTF_MULTIRT route, as we actually
6870 			 * typically want to replicate outgoing packets
6871 			 * through particular interfaces.
6872 			 */
6873 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
6874 				dst_ill = ire->ire_ipif->ipif_ill;
6875 				/* for uniformity */
6876 				ill_refhold(dst_ill);
6877 			} else {
6878 				/*
6879 				 * If we are here trying to create an IRE_CACHE
6880 				 * for an offlink destination and have the
6881 				 * IRE_CACHE for the next hop and the latter is
6882 				 * using virtual IP source address selection i.e
6883 				 * it's ire->ire_ipif is pointing to a virtual
6884 				 * network interface (vni) then
6885 				 * ip_newroute_get_dst_ll() will return the vni
6886 				 * interface as the dst_ill. Since the vni is
6887 				 * virtual i.e not associated with any physical
6888 				 * interface, it cannot be the dst_ill, hence
6889 				 * in such a case call ip_newroute_get_dst_ll()
6890 				 * with the stq_ill instead of the ire_ipif ILL.
6891 				 * The function returns a refheld ill.
6892 				 */
6893 				if ((ire->ire_type == IRE_CACHE) &&
6894 				    IS_VNI(ire->ire_ipif->ipif_ill))
6895 					dst_ill = ip_newroute_get_dst_ill(
6896 						ire->ire_stq->q_ptr);
6897 				else
6898 					dst_ill = ip_newroute_get_dst_ill(
6899 						ire->ire_ipif->ipif_ill);
6900 			}
6901 			if (dst_ill == NULL) {
6902 				if (ip_debug > 2) {
6903 					pr_addr_dbg("ip_newroute: "
6904 					    "no dst ill for dst"
6905 					    " %s\n", AF_INET, &dst);
6906 				}
6907 				goto icmp_err_ret;
6908 			}
6909 		} else {
6910 			dst_ill = ire->ire_ipif->ipif_ill;
6911 			/* for uniformity */
6912 			ill_refhold(dst_ill);
6913 			/*
6914 			 * We should have found a route matching ill as we
6915 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
6916 			 * Rather than asserting, when there is a mismatch,
6917 			 * we just drop the packet.
6918 			 */
6919 			if (dst_ill != attach_ill) {
6920 				ip0dbg(("ip_newroute: Packet dropped as "
6921 				    "IPIF_NOFAILOVER ill is %s, "
6922 				    "ire->ire_ipif->ipif_ill is %s\n",
6923 				    attach_ill->ill_name,
6924 				    dst_ill->ill_name));
6925 				ill_refrele(attach_ill);
6926 				goto icmp_err_ret;
6927 			}
6928 		}
6929 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
6930 		if (attach_ill != NULL) {
6931 			ill_refrele(attach_ill);
6932 			attach_ill = NULL;
6933 			do_attach_ill = B_TRUE;
6934 		}
6935 		ASSERT(dst_ill != NULL);
6936 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
6937 
6938 		/*
6939 		 * Pick the best source address from dst_ill.
6940 		 *
6941 		 * 1) If it is part of a multipathing group, we would
6942 		 *    like to spread the inbound packets across different
6943 		 *    interfaces. ipif_select_source picks a random source
6944 		 *    across the different ills in the group.
6945 		 *
6946 		 * 2) If it is not part of a multipathing group, we try
6947 		 *    to pick the source address from the destination
6948 		 *    route. Clustering assumes that when we have multiple
6949 		 *    prefixes hosted on an interface, the prefix of the
6950 		 *    source address matches the prefix of the destination
6951 		 *    route. We do this only if the address is not
6952 		 *    DEPRECATED.
6953 		 *
6954 		 * 3) If the conn is in a different zone than the ire, we
6955 		 *    need to pick a source address from the right zone.
6956 		 *
6957 		 * NOTE : If we hit case (1) above, the prefix of the source
6958 		 *	  address picked may not match the prefix of the
6959 		 *	  destination routes prefix as ipif_select_source
6960 		 *	  does not look at "dst" while picking a source
6961 		 *	  address.
6962 		 *	  If we want the same behavior as (2), we will need
6963 		 *	  to change the behavior of ipif_select_source.
6964 		 */
6965 		ASSERT(src_ipif == NULL);
6966 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
6967 			/*
6968 			 * The RTF_SETSRC flag is set in the parent ire (sire).
6969 			 * Check that the ipif matching the requested source
6970 			 * address still exists.
6971 			 */
6972 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
6973 			    zoneid, NULL, NULL, NULL, NULL);
6974 		}
6975 		if (src_ipif == NULL) {
6976 			ire_marks |= IRE_MARK_USESRC_CHECK;
6977 			if ((dst_ill->ill_group != NULL) ||
6978 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
6979 			    (connp != NULL && ire->ire_zoneid != zoneid) ||
6980 			    (dst_ill->ill_usesrc_ifindex != 0)) {
6981 				src_ipif = ipif_select_source(dst_ill, dst,
6982 				    zoneid);
6983 				if (src_ipif == NULL) {
6984 					if (ip_debug > 2) {
6985 						pr_addr_dbg("ip_newroute: "
6986 						    "no src for dst %s ",
6987 						    AF_INET, &dst);
6988 						printf("through interface %s\n",
6989 						    dst_ill->ill_name);
6990 					}
6991 					goto icmp_err_ret;
6992 				}
6993 			} else {
6994 				src_ipif = ire->ire_ipif;
6995 				ASSERT(src_ipif != NULL);
6996 				/* hold src_ipif for uniformity */
6997 				ipif_refhold(src_ipif);
6998 			}
6999 		}
7000 
7001 		/*
7002 		 * Assign a source address while we have the conn.
7003 		 * We can't have ip_wput_ire pick a source address when the
7004 		 * packet returns from arp since we need to look at
7005 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
7006 		 * going through arp.
7007 		 *
7008 		 * NOTE : ip_newroute_v6 does not have this piece of code as
7009 		 *	  it uses ip6i to store this information.
7010 		 */
7011 		if (ipha->ipha_src == INADDR_ANY &&
7012 		    (connp == NULL || !connp->conn_unspec_src)) {
7013 			ipha->ipha_src = src_ipif->ipif_src_addr;
7014 		}
7015 		if (ip_debug > 3) {
7016 			/* ip2dbg */
7017 			pr_addr_dbg("ip_newroute: first hop %s\n",
7018 			    AF_INET, &gw);
7019 		}
7020 		ip2dbg(("\tire type %s (%d)\n",
7021 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
7022 
7023 		/*
7024 		 * The TTL of multirouted packets is bounded by the
7025 		 * ip_multirt_ttl ndd variable.
7026 		 */
7027 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7028 			/* Force TTL of multirouted packets */
7029 			if ((ip_multirt_ttl > 0) &&
7030 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
7031 				ip2dbg(("ip_newroute: forcing multirt TTL "
7032 				    "to %d (was %d), dst 0x%08x\n",
7033 				    ip_multirt_ttl, ipha->ipha_ttl,
7034 				    ntohl(sire->ire_addr)));
7035 				ipha->ipha_ttl = ip_multirt_ttl;
7036 			}
7037 		}
7038 		/*
7039 		 * At this point in ip_newroute(), ire is either the
7040 		 * IRE_CACHE of the next-hop gateway for an off-subnet
7041 		 * destination or an IRE_INTERFACE type that should be used
7042 		 * to resolve an on-subnet destination or an on-subnet
7043 		 * next-hop gateway.
7044 		 *
7045 		 * In the IRE_CACHE case, we have the following :
7046 		 *
7047 		 * 1) src_ipif - used for getting a source address.
7048 		 *
7049 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
7050 		 *    means packets using this IRE_CACHE will go out on
7051 		 *    dst_ill.
7052 		 *
7053 		 * 3) The IRE sire will point to the prefix that is the
7054 		 *    longest  matching route for the destination. These
7055 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST,
7056 		 *    and IRE_HOST_REDIRECT.
7057 		 *
7058 		 *    The newly created IRE_CACHE entry for the off-subnet
7059 		 *    destination is tied to both the prefix route and the
7060 		 *    interface route used to resolve the next-hop gateway
7061 		 *    via the ire_phandle and ire_ihandle fields,
7062 		 *    respectively.
7063 		 *
7064 		 * In the IRE_INTERFACE case, we have the following :
7065 		 *
7066 		 * 1) src_ipif - used for getting a source address.
7067 		 *
7068 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
7069 		 *    means packets using the IRE_CACHE that we will build
7070 		 *    here will go out on dst_ill.
7071 		 *
7072 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
7073 		 *    to be created will only be tied to the IRE_INTERFACE
7074 		 *    that was derived from the ire_ihandle field.
7075 		 *
7076 		 *    If sire is non-NULL, it means the destination is
7077 		 *    off-link and we will first create the IRE_CACHE for the
7078 		 *    gateway. Next time through ip_newroute, we will create
7079 		 *    the IRE_CACHE for the final destination as described
7080 		 *    above.
7081 		 *
7082 		 * In both cases, after the current resolution has been
7083 		 * completed (or possibly initialised, in the IRE_INTERFACE
7084 		 * case), the loop may be re-entered to attempt the resolution
7085 		 * of another RTF_MULTIRT route.
7086 		 *
7087 		 * When an IRE_CACHE entry for the off-subnet destination is
7088 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
7089 		 * for further processing in emission loops.
7090 		 */
7091 		save_ire = ire;
7092 		switch (ire->ire_type) {
7093 		case IRE_CACHE: {
7094 			ire_t	*ipif_ire;
7095 			mblk_t	*ire_fp_mp;
7096 
7097 			ASSERT(sire != NULL);
7098 			if (gw == 0)
7099 				gw = ire->ire_gateway_addr;
7100 			/*
7101 			 * We need 3 ire's to create a new cache ire for an
7102 			 * off-link destination from the cache ire of the
7103 			 * gateway.
7104 			 *
7105 			 *	1. The prefix ire 'sire'
7106 			 *	2. The cache ire of the gateway 'ire'
7107 			 *	3. The interface ire 'ipif_ire'
7108 			 *
7109 			 * We have (1) and (2). We lookup (3) below.
7110 			 *
7111 			 * If there is no interface route to the gateway,
7112 			 * it is a race condition, where we found the cache
7113 			 * but the inteface route has been deleted.
7114 			 */
7115 			ipif_ire = ire_ihandle_lookup_offlink(ire, sire);
7116 			if (ipif_ire == NULL) {
7117 				ip1dbg(("ip_newroute: "
7118 				    "ire_ihandle_lookup_offlink failed\n"));
7119 				goto icmp_err_ret;
7120 			}
7121 			/*
7122 			 * XXX We are using the same dlureq_mp
7123 			 * (DL_UNITDATA_REQ) though the save_ire is not
7124 			 * pointing at the same ill.
7125 			 * This is incorrect. We need to send it up to the
7126 			 * resolver to get the right dlureq_mp. For ethernets
7127 			 * this may be okay (ill_type == DL_ETHER).
7128 			 */
7129 			dlureq_mp = save_ire->ire_dlureq_mp;
7130 			ire_fp_mp = NULL;
7131 			/*
7132 			 * save_ire's ire_fp_mp can't change since it is
7133 			 * not an IRE_MIPRTUN or IRE_BROADCAST
7134 			 * LOCK_IRE_FP_MP does not do any useful work in
7135 			 * the case of IRE_CACHE. So we don't use it below.
7136 			 */
7137 			if (save_ire->ire_stq == dst_ill->ill_wq)
7138 				ire_fp_mp = save_ire->ire_fp_mp;
7139 
7140 			ire = ire_create(
7141 			    (uchar_t *)&dst,		/* dest address */
7142 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7143 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7144 			    (uchar_t *)&gw,		/* gateway address */
7145 			    NULL,
7146 			    &save_ire->ire_max_frag,
7147 			    ire_fp_mp,			/* Fast Path header */
7148 			    dst_ill->ill_rq,		/* recv-from queue */
7149 			    dst_ill->ill_wq,		/* send-to queue */
7150 			    IRE_CACHE,			/* IRE type */
7151 			    save_ire->ire_dlureq_mp,
7152 			    src_ipif,
7153 			    in_ill,			/* incoming ill */
7154 			    sire->ire_mask,		/* Parent mask */
7155 			    sire->ire_phandle,		/* Parent handle */
7156 			    ipif_ire->ire_ihandle,	/* Interface handle */
7157 			    sire->ire_flags &
7158 				(RTF_SETSRC | RTF_MULTIRT), /* flags if any */
7159 			    &(sire->ire_uinfo));
7160 
7161 			if (ire == NULL) {
7162 				ire_refrele(ipif_ire);
7163 				ire_refrele(save_ire);
7164 				break;
7165 			}
7166 
7167 			ire->ire_marks |= ire_marks;
7168 
7169 			/*
7170 			 * Prevent sire and ipif_ire from getting deleted.
7171 			 * The newly created ire is tied to both of them via
7172 			 * the phandle and ihandle respectively.
7173 			 */
7174 			IRB_REFHOLD(sire->ire_bucket);
7175 			/* Has it been removed already ? */
7176 			if (sire->ire_marks & IRE_MARK_CONDEMNED) {
7177 				IRB_REFRELE(sire->ire_bucket);
7178 				ire_refrele(ipif_ire);
7179 				ire_refrele(save_ire);
7180 				break;
7181 			}
7182 
7183 			IRB_REFHOLD(ipif_ire->ire_bucket);
7184 			/* Has it been removed already ? */
7185 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
7186 				IRB_REFRELE(ipif_ire->ire_bucket);
7187 				IRB_REFRELE(sire->ire_bucket);
7188 				ire_refrele(ipif_ire);
7189 				ire_refrele(save_ire);
7190 				break;
7191 			}
7192 
7193 			xmit_mp = first_mp;
7194 			/*
7195 			 * In the case of multirouting, a copy
7196 			 * of the packet is done before its sending.
7197 			 * The copy is used to attempt another
7198 			 * route resolution, in a next loop.
7199 			 */
7200 			if (ire->ire_flags & RTF_MULTIRT) {
7201 				copy_mp = copymsg(first_mp);
7202 				if (copy_mp != NULL) {
7203 					xmit_mp = copy_mp;
7204 					MULTIRT_DEBUG_TAG(first_mp);
7205 				}
7206 			}
7207 			ire_add_then_send(q, ire, xmit_mp);
7208 			ire_refrele(save_ire);
7209 
7210 			/* Assert that sire is not deleted yet. */
7211 			ASSERT(sire->ire_ptpn != NULL);
7212 			IRB_REFRELE(sire->ire_bucket);
7213 
7214 			/* Assert that ipif_ire is not deleted yet. */
7215 			ASSERT(ipif_ire->ire_ptpn != NULL);
7216 			IRB_REFRELE(ipif_ire->ire_bucket);
7217 			ire_refrele(ipif_ire);
7218 
7219 			/*
7220 			 * If copy_mp is not NULL, multirouting was
7221 			 * requested. We loop to initiate a next
7222 			 * route resolution attempt, starting from sire.
7223 			 */
7224 			if (copy_mp != NULL) {
7225 				/*
7226 				 * Search for the next unresolved
7227 				 * multirt route.
7228 				 */
7229 				copy_mp = NULL;
7230 				ipif_ire = NULL;
7231 				ire = NULL;
7232 				multirt_resolve_next = B_TRUE;
7233 				continue;
7234 			}
7235 
7236 			ire_refrele(sire);
7237 			ipif_refrele(src_ipif);
7238 			ill_refrele(dst_ill);
7239 			return;
7240 		}
7241 		case IRE_IF_NORESOLVER: {
7242 			/*
7243 			 * We have what we need to build an IRE_CACHE.
7244 			 *
7245 			 * Create a new dlureq_mp with the IP gateway address
7246 			 * in destination address in the DLPI hdr if the
7247 			 * physical length is exactly 4 bytes.
7248 			 */
7249 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
7250 				uchar_t *addr;
7251 
7252 				if (gw)
7253 					addr = (uchar_t *)&gw;
7254 				else
7255 					addr = (uchar_t *)&dst;
7256 
7257 				dlureq_mp = ill_dlur_gen(addr,
7258 				    dst_ill->ill_phys_addr_length,
7259 				    dst_ill->ill_sap,
7260 				    dst_ill->ill_sap_length);
7261 			} else {
7262 				dlureq_mp = ire->ire_dlureq_mp;
7263 			}
7264 
7265 			if (dlureq_mp == NULL) {
7266 				ip1dbg(("ip_newroute: dlureq_mp NULL\n"));
7267 				break;
7268 			}
7269 
7270 			ire = ire_create(
7271 			    (uchar_t *)&dst,		/* dest address */
7272 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7273 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7274 			    (uchar_t *)&gw,		/* gateway address */
7275 			    NULL,
7276 			    &save_ire->ire_max_frag,
7277 			    NULL,			/* Fast Path header */
7278 			    dst_ill->ill_rq,		/* recv-from queue */
7279 			    dst_ill->ill_wq,		/* send-to queue */
7280 			    IRE_CACHE,
7281 			    dlureq_mp,
7282 			    src_ipif,
7283 			    in_ill,			/* Incoming ill */
7284 			    save_ire->ire_mask,		/* Parent mask */
7285 			    (sire != NULL) ?		/* Parent handle */
7286 				sire->ire_phandle : 0,
7287 			    save_ire->ire_ihandle,	/* Interface handle */
7288 			    (sire != NULL) ? sire->ire_flags &
7289 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
7290 			    &(save_ire->ire_uinfo));
7291 
7292 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
7293 				freeb(dlureq_mp);
7294 
7295 			if (ire == NULL) {
7296 				ire_refrele(save_ire);
7297 				break;
7298 			}
7299 
7300 			ire->ire_marks |= ire_marks;
7301 
7302 			/* Prevent save_ire from getting deleted */
7303 			IRB_REFHOLD(save_ire->ire_bucket);
7304 			/* Has it been removed already ? */
7305 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
7306 				IRB_REFRELE(save_ire->ire_bucket);
7307 				ire_refrele(save_ire);
7308 				break;
7309 			}
7310 
7311 			/*
7312 			 * In the case of multirouting, a copy
7313 			 * of the packet is made before it is sent.
7314 			 * The copy is used in the next
7315 			 * loop to attempt another resolution.
7316 			 */
7317 			xmit_mp = first_mp;
7318 			if ((sire != NULL) &&
7319 			    (sire->ire_flags & RTF_MULTIRT)) {
7320 				copy_mp = copymsg(first_mp);
7321 				if (copy_mp != NULL) {
7322 					xmit_mp = copy_mp;
7323 					MULTIRT_DEBUG_TAG(first_mp);
7324 				}
7325 			}
7326 			ire_add_then_send(q, ire, xmit_mp);
7327 
7328 			/* Assert that it is not deleted yet. */
7329 			ASSERT(save_ire->ire_ptpn != NULL);
7330 			IRB_REFRELE(save_ire->ire_bucket);
7331 			ire_refrele(save_ire);
7332 
7333 			if (copy_mp != NULL) {
7334 				/*
7335 				 * If we found a (no)resolver, we ignore any
7336 				 * trailing top priority IRE_CACHE in further
7337 				 * loops. This ensures that we do not omit any
7338 				 * (no)resolver.
7339 				 * This IRE_CACHE, if any, will be processed
7340 				 * by another thread entering ip_newroute().
7341 				 * IRE_CACHE entries, if any, will be processed
7342 				 * by another thread entering ip_newroute(),
7343 				 * (upon resolver response, for instance).
7344 				 * This aims to force parallel multirt
7345 				 * resolutions as soon as a packet must be sent.
7346 				 * In the best case, after the tx of only one
7347 				 * packet, all reachable routes are resolved.
7348 				 * Otherwise, the resolution of all RTF_MULTIRT
7349 				 * routes would require several emissions.
7350 				 */
7351 				multirt_flags &= ~MULTIRT_CACHEGW;
7352 
7353 				/*
7354 				 * Search for the next unresolved multirt
7355 				 * route.
7356 				 */
7357 				copy_mp = NULL;
7358 				save_ire = NULL;
7359 				ire = NULL;
7360 				multirt_resolve_next = B_TRUE;
7361 				continue;
7362 			}
7363 
7364 			/*
7365 			 * Don't need sire anymore
7366 			 */
7367 			if (sire != NULL)
7368 				ire_refrele(sire);
7369 
7370 			ipif_refrele(src_ipif);
7371 			ill_refrele(dst_ill);
7372 			return;
7373 		}
7374 		case IRE_IF_RESOLVER:
7375 			/*
7376 			 * We can't build an IRE_CACHE yet, but at least we
7377 			 * found a resolver that can help.
7378 			 */
7379 			res_mp = dst_ill->ill_resolver_mp;
7380 			if (!OK_RESOLVER_MP(res_mp))
7381 				break;
7382 			/*
7383 			 * To be at this point in the code with a non-zero gw
7384 			 * means that dst is reachable through a gateway that
7385 			 * we have never resolved.  By changing dst to the gw
7386 			 * addr we resolve the gateway first.
7387 			 * When ire_add_then_send() tries to put the IP dg
7388 			 * to dst, it will reenter ip_newroute() at which
7389 			 * time we will find the IRE_CACHE for the gw and
7390 			 * create another IRE_CACHE in case IRE_CACHE above.
7391 			 */
7392 			if (gw != INADDR_ANY) {
7393 				/*
7394 				 * The source ipif that was determined above was
7395 				 * relative to the destination address, not the
7396 				 * gateway's. If src_ipif was not taken out of
7397 				 * the IRE_IF_RESOLVER entry, we'll need to call
7398 				 * ipif_select_source() again.
7399 				 */
7400 				if (src_ipif != ire->ire_ipif) {
7401 					ipif_refrele(src_ipif);
7402 					src_ipif = ipif_select_source(dst_ill,
7403 					    gw, zoneid);
7404 					if (src_ipif == NULL) {
7405 						if (ip_debug > 2) {
7406 							pr_addr_dbg(
7407 							    "ip_newroute: no "
7408 							    "src for gw %s ",
7409 							    AF_INET, &gw);
7410 							printf("through "
7411 							    "interface %s\n",
7412 							    dst_ill->ill_name);
7413 						}
7414 						goto icmp_err_ret;
7415 					}
7416 				}
7417 				save_dst = dst;
7418 				dst = gw;
7419 				gw = INADDR_ANY;
7420 			}
7421 			/*
7422 			 * We obtain a partial IRE_CACHE which we will pass
7423 			 * along with the resolver query.  When the response
7424 			 * comes back it will be there ready for us to add.
7425 			 * The ire_max_frag is atomically set under the
7426 			 * irebucket lock in ire_add_v[46].
7427 			 */
7428 			ire = ire_create_mp(
7429 			    (uchar_t *)&dst,		/* dest address */
7430 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7431 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7432 			    (uchar_t *)&gw,		/* gateway address */
7433 			    NULL,			/* no in_src_addr */
7434 			    NULL,			/* ire_max_frag */
7435 			    NULL,			/* Fast Path header */
7436 			    dst_ill->ill_rq,		/* recv-from queue */
7437 			    dst_ill->ill_wq,		/* send-to queue */
7438 			    IRE_CACHE,
7439 			    res_mp,
7440 			    src_ipif,			/* Interface ipif */
7441 			    in_ill,			/* Incoming ILL */
7442 			    save_ire->ire_mask,		/* Parent mask */
7443 			    0,
7444 			    save_ire->ire_ihandle,	/* Interface handle */
7445 			    0,				/* flags if any */
7446 			    &(save_ire->ire_uinfo));
7447 
7448 			if (ire == NULL) {
7449 				ire_refrele(save_ire);
7450 				break;
7451 			}
7452 
7453 			if ((sire != NULL) &&
7454 			    (sire->ire_flags & RTF_MULTIRT)) {
7455 				copy_mp = copymsg(first_mp);
7456 				if (copy_mp != NULL)
7457 					MULTIRT_DEBUG_TAG(copy_mp);
7458 			}
7459 
7460 			ire->ire_marks |= ire_marks;
7461 
7462 			/*
7463 			 * Construct message chain for the resolver
7464 			 * of the form:
7465 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
7466 			 * Packet could contain a IPSEC_OUT mp.
7467 			 *
7468 			 * NOTE : ire will be added later when the response
7469 			 * comes back from ARP. If the response does not
7470 			 * come back, ARP frees the packet. For this reason,
7471 			 * we can't REFHOLD the bucket of save_ire to prevent
7472 			 * deletions. We may not be able to REFRELE the bucket
7473 			 * if the response never comes back. Thus, before
7474 			 * adding the ire, ire_add_v4 will make sure that the
7475 			 * interface route does not get deleted. This is the
7476 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
7477 			 * where we can always prevent deletions because of
7478 			 * the synchronous nature of adding IRES i.e
7479 			 * ire_add_then_send is called after creating the IRE.
7480 			 */
7481 			ASSERT(ire->ire_mp != NULL);
7482 			ire->ire_mp->b_cont = first_mp;
7483 			/* Have saved_mp handy, for cleanup if canput fails */
7484 			saved_mp = mp;
7485 			mp = ire->ire_dlureq_mp;
7486 			ASSERT(mp != NULL);
7487 			ire->ire_dlureq_mp = NULL;
7488 			linkb(mp, ire->ire_mp);
7489 
7490 
7491 			/*
7492 			 * Fill in the source and dest addrs for the resolver.
7493 			 * NOTE: this depends on memory layouts imposed by
7494 			 * ill_init().
7495 			 */
7496 			areq = (areq_t *)mp->b_rptr;
7497 			addrp = (ipaddr_t *)((char *)areq +
7498 			    areq->areq_sender_addr_offset);
7499 			if (do_attach_ill) {
7500 				/*
7501 				 * This is bind to no failover case.
7502 				 * arp packet also must go out on attach_ill.
7503 				 */
7504 				ASSERT(ipha->ipha_src != NULL);
7505 				*addrp = ipha->ipha_src;
7506 			} else {
7507 				*addrp = save_ire->ire_src_addr;
7508 			}
7509 
7510 			ire_refrele(save_ire);
7511 			addrp = (ipaddr_t *)((char *)areq +
7512 			    areq->areq_target_addr_offset);
7513 			*addrp = dst;
7514 			/* Up to the resolver. */
7515 			if (canputnext(dst_ill->ill_rq)) {
7516 				putnext(dst_ill->ill_rq, mp);
7517 				ire = NULL;
7518 				if (copy_mp != NULL) {
7519 					/*
7520 					 * If we found a resolver, we ignore
7521 					 * any trailing top priority IRE_CACHE
7522 					 * in the further loops. This ensures
7523 					 * that we do not omit any resolver.
7524 					 * IRE_CACHE entries, if any, will be
7525 					 * processed next time we enter
7526 					 * ip_newroute().
7527 					 */
7528 					multirt_flags &= ~MULTIRT_CACHEGW;
7529 					/*
7530 					 * Search for the next unresolved
7531 					 * multirt route.
7532 					 */
7533 					first_mp = copy_mp;
7534 					copy_mp = NULL;
7535 					/* Prepare the next resolution loop. */
7536 					mp = first_mp;
7537 					EXTRACT_PKT_MP(mp, first_mp,
7538 					    mctl_present);
7539 					if (mctl_present)
7540 						io = (ipsec_out_t *)
7541 						    first_mp->b_rptr;
7542 					ipha = (ipha_t *)mp->b_rptr;
7543 
7544 					ASSERT(sire != NULL);
7545 
7546 					dst = save_dst;
7547 					multirt_resolve_next = B_TRUE;
7548 					continue;
7549 				}
7550 
7551 				if (sire != NULL)
7552 					ire_refrele(sire);
7553 
7554 				/*
7555 				 * The response will come back in ip_wput
7556 				 * with db_type IRE_DB_TYPE.
7557 				 */
7558 				ipif_refrele(src_ipif);
7559 				ill_refrele(dst_ill);
7560 				return;
7561 			} else {
7562 				/* Prepare for cleanup */
7563 				ire->ire_dlureq_mp = mp;
7564 				mp->b_cont = NULL;
7565 				ire_delete(ire);
7566 				mp = saved_mp;
7567 				ire = NULL;
7568 				if (copy_mp != NULL) {
7569 					MULTIRT_DEBUG_UNTAG(copy_mp);
7570 					freemsg(copy_mp);
7571 					copy_mp = NULL;
7572 				}
7573 				break;
7574 			}
7575 		default:
7576 			break;
7577 		}
7578 	} while (multirt_resolve_next);
7579 
7580 	ip1dbg(("ip_newroute: dropped\n"));
7581 	/* Did this packet originate externally? */
7582 	if (mp->b_prev) {
7583 		mp->b_next = NULL;
7584 		mp->b_prev = NULL;
7585 		BUMP_MIB(&ip_mib, ipInDiscards);
7586 	} else {
7587 		BUMP_MIB(&ip_mib, ipOutDiscards);
7588 	}
7589 	ASSERT(copy_mp == NULL);
7590 	MULTIRT_DEBUG_UNTAG(first_mp);
7591 	freemsg(first_mp);
7592 	if (ire != NULL)
7593 		ire_refrele(ire);
7594 	if (sire != NULL)
7595 		ire_refrele(sire);
7596 	if (src_ipif != NULL)
7597 		ipif_refrele(src_ipif);
7598 	if (dst_ill != NULL)
7599 		ill_refrele(dst_ill);
7600 	return;
7601 
7602 icmp_err_ret:
7603 	ip1dbg(("ip_newroute: no route\n"));
7604 	if (src_ipif != NULL)
7605 		ipif_refrele(src_ipif);
7606 	if (dst_ill != NULL)
7607 		ill_refrele(dst_ill);
7608 	if (sire != NULL)
7609 		ire_refrele(sire);
7610 	/* Did this packet originate externally? */
7611 	if (mp->b_prev) {
7612 		mp->b_next = NULL;
7613 		mp->b_prev = NULL;
7614 		/* XXX ipInNoRoutes */
7615 		q = WR(q);
7616 	} else {
7617 		/*
7618 		 * Since ip_wput() isn't close to finished, we fill
7619 		 * in enough of the header for credible error reporting.
7620 		 */
7621 		if (ip_hdr_complete(ipha, zoneid)) {
7622 			/* Failed */
7623 			MULTIRT_DEBUG_UNTAG(first_mp);
7624 			freemsg(first_mp);
7625 			if (ire != NULL)
7626 				ire_refrele(ire);
7627 			return;
7628 		}
7629 	}
7630 	BUMP_MIB(&ip_mib, ipOutNoRoutes);
7631 
7632 	/*
7633 	 * At this point we will have ire only if RTF_BLACKHOLE
7634 	 * or RTF_REJECT flags are set on the IRE. It will not
7635 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
7636 	 */
7637 	if (ire != NULL) {
7638 		if (ire->ire_flags & RTF_BLACKHOLE) {
7639 			ire_refrele(ire);
7640 			MULTIRT_DEBUG_UNTAG(first_mp);
7641 			freemsg(first_mp);
7642 			return;
7643 		}
7644 		ire_refrele(ire);
7645 	}
7646 	if (ip_source_routed(ipha)) {
7647 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED);
7648 		return;
7649 	}
7650 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE);
7651 }
7652 
7653 /*
7654  * IPv4 -
7655  * ip_newroute_ipif is called by ip_wput_multicast and
7656  * ip_rput_forward_multicast whenever we need to send
7657  * out a packet to a destination address for which we do not have specific
7658  * routing information. It is used when the packet will be sent out
7659  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
7660  * socket option is set or icmp error message wants to go out on a particular
7661  * interface for a unicast packet.
7662  *
7663  * In most cases, the destination address is resolved thanks to the ipif
7664  * intrinsic resolver. However, there are some cases where the call to
7665  * ip_newroute_ipif must take into account the potential presence of
7666  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
7667  * that uses the interface. This is specified through flags,
7668  * which can be a combination of:
7669  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
7670  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
7671  *   and flags. Additionally, the packet source address has to be set to
7672  *   the specified address. The caller is thus expected to set this flag
7673  *   if the packet has no specific source address yet.
7674  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
7675  *   flag, the resulting ire will inherit the flag. All unresolved routes
7676  *   to the destination must be explored in the same call to
7677  *   ip_newroute_ipif().
7678  */
7679 static void
7680 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
7681     conn_t *connp, uint32_t flags)
7682 {
7683 	areq_t	*areq;
7684 	ire_t	*ire = NULL;
7685 	mblk_t	*res_mp;
7686 	ipaddr_t *addrp;
7687 	mblk_t *first_mp;
7688 	ire_t	*save_ire = NULL;
7689 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
7690 	ipif_t	*src_ipif = NULL;
7691 	ushort_t ire_marks = 0;
7692 	ill_t	*dst_ill = NULL;
7693 	boolean_t mctl_present;
7694 	ipsec_out_t *io;
7695 	ipha_t *ipha;
7696 	int	ihandle = 0;
7697 	mblk_t	*saved_mp;
7698 	ire_t   *fire = NULL;
7699 	mblk_t  *copy_mp = NULL;
7700 	boolean_t multirt_resolve_next;
7701 	ipaddr_t ipha_dst;
7702 	zoneid_t zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
7703 
7704 	/*
7705 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
7706 	 * here for uniformity
7707 	 */
7708 	ipif_refhold(ipif);
7709 
7710 	/*
7711 	 * This loop is run only once in most cases.
7712 	 * We loop to resolve further routes only when the destination
7713 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7714 	 */
7715 	do {
7716 		if (dst_ill != NULL) {
7717 			ill_refrele(dst_ill);
7718 			dst_ill = NULL;
7719 		}
7720 		if (src_ipif != NULL) {
7721 			ipif_refrele(src_ipif);
7722 			src_ipif = NULL;
7723 		}
7724 		multirt_resolve_next = B_FALSE;
7725 
7726 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
7727 		    ipif->ipif_ill->ill_name));
7728 
7729 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7730 		if (mctl_present)
7731 			io = (ipsec_out_t *)first_mp->b_rptr;
7732 
7733 		ipha = (ipha_t *)mp->b_rptr;
7734 
7735 		/*
7736 		 * Save the packet destination address, we may need it after
7737 		 * the packet has been consumed.
7738 		 */
7739 		ipha_dst = ipha->ipha_dst;
7740 
7741 		/*
7742 		 * If the interface is a pt-pt interface we look for an
7743 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
7744 		 * local_address and the pt-pt destination address. Otherwise
7745 		 * we just match the local address.
7746 		 * NOTE: dst could be different than ipha->ipha_dst in case
7747 		 * of sending igmp multicast packets over a point-to-point
7748 		 * connection.
7749 		 * Thus we must be careful enough to check ipha_dst to be a
7750 		 * multicast address, otherwise it will take xmit_if path for
7751 		 * multicast packets resulting into kernel stack overflow by
7752 		 * repeated calls to ip_newroute_ipif from ire_send().
7753 		 */
7754 		if (CLASSD(ipha_dst) &&
7755 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
7756 			goto err_ret;
7757 		}
7758 
7759 		/*
7760 		 * We check if an IRE_OFFSUBNET for the addr that goes through
7761 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
7762 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
7763 		 * propagate its flags to the new ire.
7764 		 */
7765 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
7766 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
7767 			ip2dbg(("ip_newroute_ipif: "
7768 			    "ipif_lookup_multi_ire("
7769 			    "ipif %p, dst %08x) = fire %p\n",
7770 			    (void *)ipif, ntohl(dst), (void *)fire));
7771 		}
7772 
7773 		if (mctl_present && io->ipsec_out_attach_if) {
7774 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
7775 			    io->ipsec_out_ill_index, B_FALSE);
7776 
7777 			/* Failure case frees things for us. */
7778 			if (attach_ill == NULL) {
7779 				ipif_refrele(ipif);
7780 				if (fire != NULL)
7781 					ire_refrele(fire);
7782 				return;
7783 			}
7784 
7785 			/*
7786 			 * Check if we need an ire that will not be
7787 			 * looked up by anybody else i.e. HIDDEN.
7788 			 */
7789 			if (ill_is_probeonly(attach_ill)) {
7790 				ire_marks = IRE_MARK_HIDDEN;
7791 			}
7792 			/*
7793 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
7794 			 * case.
7795 			 */
7796 			dst_ill = ipif->ipif_ill;
7797 			/* attach_ill has been refheld by ip_grab_attach_ill */
7798 			ASSERT(dst_ill == attach_ill);
7799 		} else {
7800 			/*
7801 			 * If this is set by IP_XMIT_IF, then make sure that
7802 			 * ipif is pointing to the same ill as the IP_XMIT_IF
7803 			 * specified ill.
7804 			 */
7805 			ASSERT((connp == NULL) ||
7806 			    (connp->conn_xmit_if_ill == NULL) ||
7807 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
7808 			/*
7809 			 * If the interface belongs to an interface group,
7810 			 * make sure the next possible interface in the group
7811 			 * is used.  This encourages load spreading among
7812 			 * peers in an interface group.
7813 			 * Note: load spreading is disabled for RTF_MULTIRT
7814 			 * routes.
7815 			 */
7816 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
7817 			    (fire->ire_flags & RTF_MULTIRT)) {
7818 				/*
7819 				 * Don't perform outbound load spreading
7820 				 * in the case of an RTF_MULTIRT issued route,
7821 				 * we actually typically want to replicate
7822 				 * outgoing packets through particular
7823 				 * interfaces.
7824 				 */
7825 				dst_ill = ipif->ipif_ill;
7826 				ill_refhold(dst_ill);
7827 			} else {
7828 				dst_ill = ip_newroute_get_dst_ill(
7829 				    ipif->ipif_ill);
7830 			}
7831 			if (dst_ill == NULL) {
7832 				if (ip_debug > 2) {
7833 					pr_addr_dbg("ip_newroute_ipif: "
7834 					    "no dst ill for dst %s\n",
7835 					    AF_INET, &dst);
7836 				}
7837 				goto err_ret;
7838 			}
7839 		}
7840 
7841 		/*
7842 		 * Pick a source address preferring non-deprecated ones.
7843 		 * Unlike ip_newroute, we don't do any source address
7844 		 * selection here since for multicast it really does not help
7845 		 * in inbound load spreading as in the unicast case.
7846 		 */
7847 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
7848 		    (fire->ire_flags & RTF_SETSRC)) {
7849 			/*
7850 			 * As requested by flags, an IRE_OFFSUBNET was looked up
7851 			 * on that interface. This ire has RTF_SETSRC flag, so
7852 			 * the source address of the packet must be changed.
7853 			 * Check that the ipif matching the requested source
7854 			 * address still exists.
7855 			 */
7856 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
7857 			    zoneid, NULL, NULL, NULL, NULL);
7858 		}
7859 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
7860 		    (connp != NULL && ipif->ipif_zoneid != zoneid)) &&
7861 		    (src_ipif == NULL)) {
7862 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
7863 			if (src_ipif == NULL) {
7864 				if (ip_debug > 2) {
7865 					/* ip1dbg */
7866 					pr_addr_dbg("ip_newroute_ipif: "
7867 					    "no src for dst %s",
7868 					    AF_INET, &dst);
7869 				}
7870 				ip1dbg((" through interface %s\n",
7871 				    dst_ill->ill_name));
7872 				goto err_ret;
7873 			}
7874 			ipif_refrele(ipif);
7875 			ipif = src_ipif;
7876 			ipif_refhold(ipif);
7877 		}
7878 		if (src_ipif == NULL) {
7879 			src_ipif = ipif;
7880 			ipif_refhold(src_ipif);
7881 		}
7882 
7883 		/*
7884 		 * Assign a source address while we have the conn.
7885 		 * We can't have ip_wput_ire pick a source address when the
7886 		 * packet returns from arp since conn_unspec_src might be set
7887 		 * and we loose the conn when going through arp.
7888 		 */
7889 		if (ipha->ipha_src == INADDR_ANY &&
7890 		    (connp == NULL || !connp->conn_unspec_src)) {
7891 			ipha->ipha_src = src_ipif->ipif_src_addr;
7892 		}
7893 
7894 		/*
7895 		 * In case of IP_XMIT_IF, it is possible that the outgoing
7896 		 * interface does not have an interface ire.
7897 		 * Example: Thousands of mobileip PPP interfaces to mobile
7898 		 * nodes. We don't want to create interface ires because
7899 		 * packets from other mobile nodes must not take the route
7900 		 * via interface ires to the visiting mobile node without
7901 		 * going through the home agent, in absence of mobileip
7902 		 * route optimization.
7903 		 */
7904 		if (CLASSD(ipha_dst) && (connp == NULL ||
7905 		    connp->conn_xmit_if_ill == NULL)) {
7906 			/* ipif_to_ire returns an held ire */
7907 			ire = ipif_to_ire(ipif);
7908 			if (ire == NULL)
7909 				goto err_ret;
7910 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
7911 				goto err_ret;
7912 			/*
7913 			 * ihandle is needed when the ire is added to
7914 			 * cache table.
7915 			 */
7916 			save_ire = ire;
7917 			ihandle = save_ire->ire_ihandle;
7918 
7919 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
7920 			    "flags %04x\n",
7921 			    (void *)ire, (void *)ipif, flags));
7922 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
7923 			    (fire->ire_flags & RTF_MULTIRT)) {
7924 				/*
7925 				 * As requested by flags, an IRE_OFFSUBNET was
7926 				 * looked up on that interface. This ire has
7927 				 * RTF_MULTIRT flag, so the resolution loop will
7928 				 * be re-entered to resolve additional routes on
7929 				 * other interfaces. For that purpose, a copy of
7930 				 * the packet is performed at this point.
7931 				 */
7932 				fire->ire_last_used_time = lbolt;
7933 				copy_mp = copymsg(first_mp);
7934 				if (copy_mp) {
7935 					MULTIRT_DEBUG_TAG(copy_mp);
7936 				}
7937 			}
7938 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
7939 			    (fire->ire_flags & RTF_SETSRC)) {
7940 				/*
7941 				 * As requested by flags, an IRE_OFFSUBET was
7942 				 * looked up on that interface. This ire has
7943 				 * RTF_SETSRC flag, so the source address of the
7944 				 * packet must be changed.
7945 				 */
7946 				ipha->ipha_src = fire->ire_src_addr;
7947 			}
7948 		} else {
7949 			ASSERT((connp == NULL) ||
7950 			    (connp->conn_xmit_if_ill != NULL) ||
7951 			    (connp->conn_dontroute));
7952 			/*
7953 			 * The only ways we can come here are:
7954 			 * 1) IP_XMIT_IF socket option is set
7955 			 * 2) ICMP error message generated from
7956 			 *    ip_mrtun_forward() routine and it needs
7957 			 *    to go through the specified ill.
7958 			 * 3) SO_DONTROUTE socket option is set
7959 			 * In all cases, the new ire will not be added
7960 			 * into cache table.
7961 			 */
7962 			ire_marks |= IRE_MARK_NOADD;
7963 		}
7964 
7965 		switch (ipif->ipif_net_type) {
7966 		case IRE_IF_NORESOLVER: {
7967 			/* We have what we need to build an IRE_CACHE. */
7968 			mblk_t	*dlureq_mp;
7969 
7970 			/*
7971 			 * Create a new dlureq_mp with the
7972 			 * IP gateway address as destination address in the
7973 			 * DLPI hdr if the physical length is exactly 4 bytes.
7974 			 */
7975 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
7976 				dlureq_mp = ill_dlur_gen((uchar_t *)&dst,
7977 				    dst_ill->ill_phys_addr_length,
7978 				    dst_ill->ill_sap,
7979 				    dst_ill->ill_sap_length);
7980 			} else {
7981 				/* use the value set in ip_ll_subnet_defaults */
7982 				dlureq_mp = ill_dlur_gen(NULL,
7983 				    dst_ill->ill_phys_addr_length,
7984 				    dst_ill->ill_sap,
7985 				    dst_ill->ill_sap_length);
7986 			}
7987 
7988 			if (dlureq_mp == NULL)
7989 				break;
7990 			/*
7991 			 * The new ire inherits the IRE_OFFSUBNET flags
7992 			 * and source address, if this was requested.
7993 			 */
7994 			ire = ire_create(
7995 			    (uchar_t *)&dst,		/* dest address */
7996 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7997 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7998 			    NULL,			/* gateway address */
7999 			    NULL,
8000 			    &ipif->ipif_mtu,
8001 			    NULL,			/* Fast Path header */
8002 			    dst_ill->ill_rq,		/* recv-from queue */
8003 			    dst_ill->ill_wq,		/* send-to queue */
8004 			    IRE_CACHE,
8005 			    dlureq_mp,
8006 			    src_ipif,
8007 			    NULL,
8008 			    (save_ire != NULL ? save_ire->ire_mask : 0),
8009 			    (fire != NULL) ?		/* Parent handle */
8010 				fire->ire_phandle : 0,
8011 			    ihandle,			/* Interface handle */
8012 			    (fire != NULL) ?
8013 				(fire->ire_flags &
8014 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
8015 			    (save_ire == NULL ? &ire_uinfo_null :
8016 				&save_ire->ire_uinfo));
8017 
8018 			freeb(dlureq_mp);
8019 
8020 			if (ire == NULL) {
8021 				if (save_ire != NULL)
8022 					ire_refrele(save_ire);
8023 				break;
8024 			}
8025 
8026 			ire->ire_marks |= ire_marks;
8027 
8028 			/* Prevent save_ire from getting deleted */
8029 			if (save_ire != NULL) {
8030 				IRB_REFHOLD(save_ire->ire_bucket);
8031 				/* Has it been removed already ? */
8032 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8033 					IRB_REFRELE(save_ire->ire_bucket);
8034 					ire_refrele(save_ire);
8035 					break;
8036 				}
8037 			}
8038 
8039 			ire_add_then_send(q, ire, first_mp);
8040 
8041 			/* Assert that save_ire is not deleted yet. */
8042 			if (save_ire != NULL) {
8043 				ASSERT(save_ire->ire_ptpn != NULL);
8044 				IRB_REFRELE(save_ire->ire_bucket);
8045 				ire_refrele(save_ire);
8046 				save_ire = NULL;
8047 			}
8048 			if (fire != NULL) {
8049 				ire_refrele(fire);
8050 				fire = NULL;
8051 			}
8052 
8053 			/*
8054 			 * the resolution loop is re-entered if this
8055 			 * was requested through flags and if we
8056 			 * actually are in a multirouting case.
8057 			 */
8058 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
8059 				boolean_t need_resolve =
8060 				    ire_multirt_need_resolve(ipha_dst);
8061 				if (!need_resolve) {
8062 					MULTIRT_DEBUG_UNTAG(copy_mp);
8063 					freemsg(copy_mp);
8064 					copy_mp = NULL;
8065 				} else {
8066 					/*
8067 					 * ipif_lookup_group() calls
8068 					 * ire_lookup_multi() that uses
8069 					 * ire_ftable_lookup() to find
8070 					 * an IRE_INTERFACE for the group.
8071 					 * In the multirt case,
8072 					 * ire_lookup_multi() then invokes
8073 					 * ire_multirt_lookup() to find
8074 					 * the next resolvable ire.
8075 					 * As a result, we obtain an new
8076 					 * interface, derived from the
8077 					 * next ire.
8078 					 */
8079 					ipif_refrele(ipif);
8080 					ipif = ipif_lookup_group(ipha_dst,
8081 					    zoneid);
8082 					ip2dbg(("ip_newroute_ipif: "
8083 					    "multirt dst %08x, ipif %p\n",
8084 					    htonl(dst), (void *)ipif));
8085 					if (ipif != NULL) {
8086 						mp = copy_mp;
8087 						copy_mp = NULL;
8088 						multirt_resolve_next = B_TRUE;
8089 						continue;
8090 					} else {
8091 						freemsg(copy_mp);
8092 					}
8093 				}
8094 			}
8095 			if (ipif != NULL)
8096 				ipif_refrele(ipif);
8097 			ill_refrele(dst_ill);
8098 			ipif_refrele(src_ipif);
8099 			return;
8100 		}
8101 		case IRE_IF_RESOLVER:
8102 			/*
8103 			 * We can't build an IRE_CACHE yet, but at least
8104 			 * we found a resolver that can help.
8105 			 */
8106 			res_mp = dst_ill->ill_resolver_mp;
8107 			if (!OK_RESOLVER_MP(res_mp))
8108 				break;
8109 
8110 			/*
8111 			 * We obtain a partial IRE_CACHE which we will pass
8112 			 * along with the resolver query.  When the response
8113 			 * comes back it will be there ready for us to add.
8114 			 * The new ire inherits the IRE_OFFSUBNET flags
8115 			 * and source address, if this was requested.
8116 			 * The ire_max_frag is atomically set under the
8117 			 * irebucket lock in ire_add_v[46]. Only in the
8118 			 * case of IRE_MARK_NOADD, we set it here itself.
8119 			 */
8120 			ire = ire_create_mp(
8121 			    (uchar_t *)&dst,		/* dest address */
8122 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8123 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8124 			    NULL,			/* gateway address */
8125 			    NULL,			/* no in_src_addr */
8126 			    (ire_marks & IRE_MARK_NOADD) ?
8127 				ipif->ipif_mtu : 0,	/* max_frag */
8128 			    NULL,			/* Fast path header */
8129 			    dst_ill->ill_rq,		/* recv-from queue */
8130 			    dst_ill->ill_wq,		/* send-to queue */
8131 			    IRE_CACHE,
8132 			    res_mp,
8133 			    src_ipif,
8134 			    NULL,
8135 			    (save_ire != NULL ? save_ire->ire_mask : 0),
8136 			    (fire != NULL) ?		/* Parent handle */
8137 				fire->ire_phandle : 0,
8138 			    ihandle,			/* Interface handle */
8139 			    (fire != NULL) ?		/* flags if any */
8140 				(fire->ire_flags &
8141 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
8142 			    (save_ire == NULL ? &ire_uinfo_null :
8143 				&save_ire->ire_uinfo));
8144 
8145 			if (save_ire != NULL) {
8146 				ire_refrele(save_ire);
8147 				save_ire = NULL;
8148 			}
8149 			if (ire == NULL)
8150 				break;
8151 
8152 			ire->ire_marks |= ire_marks;
8153 			/*
8154 			 * Construct message chain for the resolver of the
8155 			 * form:
8156 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8157 			 *
8158 			 * NOTE : ire will be added later when the response
8159 			 * comes back from ARP. If the response does not
8160 			 * come back, ARP frees the packet. For this reason,
8161 			 * we can't REFHOLD the bucket of save_ire to prevent
8162 			 * deletions. We may not be able to REFRELE the
8163 			 * bucket if the response never comes back.
8164 			 * Thus, before adding the ire, ire_add_v4 will make
8165 			 * sure that the interface route does not get deleted.
8166 			 * This is the only case unlike ip_newroute_v6,
8167 			 * ip_newroute_ipif_v6 where we can always prevent
8168 			 * deletions because ire_add_then_send is called after
8169 			 * creating the IRE.
8170 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
8171 			 * does not add this IRE into the IRE CACHE.
8172 			 */
8173 			ASSERT(ire->ire_mp != NULL);
8174 			ire->ire_mp->b_cont = first_mp;
8175 			/* Have saved_mp handy, for cleanup if canput fails */
8176 			saved_mp = mp;
8177 			mp = ire->ire_dlureq_mp;
8178 			ASSERT(mp != NULL);
8179 			ire->ire_dlureq_mp = NULL;
8180 			linkb(mp, ire->ire_mp);
8181 
8182 			/*
8183 			 * Fill in the source and dest addrs for the resolver.
8184 			 * NOTE: this depends on memory layouts imposed by
8185 			 * ill_init().
8186 			 */
8187 			areq = (areq_t *)mp->b_rptr;
8188 			addrp = (ipaddr_t *)((char *)areq +
8189 			    areq->areq_sender_addr_offset);
8190 			*addrp = ire->ire_src_addr;
8191 			addrp = (ipaddr_t *)((char *)areq +
8192 			    areq->areq_target_addr_offset);
8193 			*addrp = dst;
8194 			/* Up to the resolver. */
8195 			if (canputnext(dst_ill->ill_rq)) {
8196 				putnext(dst_ill->ill_rq, mp);
8197 				/*
8198 				 * The response will come back in ip_wput
8199 				 * with db_type IRE_DB_TYPE.
8200 				 */
8201 			} else {
8202 				ire->ire_dlureq_mp = mp;
8203 				mp->b_cont = NULL;
8204 				ire_delete(ire);
8205 				saved_mp->b_next = NULL;
8206 				saved_mp->b_prev = NULL;
8207 				freemsg(first_mp);
8208 				ip2dbg(("ip_newroute_ipif: dropped\n"));
8209 			}
8210 
8211 			if (fire != NULL) {
8212 				ire_refrele(fire);
8213 				fire = NULL;
8214 			}
8215 
8216 
8217 			/*
8218 			 * The resolution loop is re-entered if this was
8219 			 * requested through flags and we actually are
8220 			 * in a multirouting case.
8221 			 */
8222 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
8223 				boolean_t need_resolve =
8224 				    ire_multirt_need_resolve(ipha_dst);
8225 				if (!need_resolve) {
8226 					MULTIRT_DEBUG_UNTAG(copy_mp);
8227 					freemsg(copy_mp);
8228 					copy_mp = NULL;
8229 				} else {
8230 					/*
8231 					 * ipif_lookup_group() calls
8232 					 * ire_lookup_multi() that uses
8233 					 * ire_ftable_lookup() to find
8234 					 * an IRE_INTERFACE for the group.
8235 					 * In the multirt case,
8236 					 * ire_lookup_multi() then invokes
8237 					 * ire_multirt_lookup() to find
8238 					 * the next resolvable ire.
8239 					 * As a result, we obtain an new
8240 					 * interface, derived from the
8241 					 * next ire.
8242 					 */
8243 					ipif_refrele(ipif);
8244 					ipif = ipif_lookup_group(ipha_dst,
8245 					    zoneid);
8246 					if (ipif != NULL) {
8247 						mp = copy_mp;
8248 						copy_mp = NULL;
8249 						multirt_resolve_next = B_TRUE;
8250 						continue;
8251 					} else {
8252 						freemsg(copy_mp);
8253 					}
8254 				}
8255 			}
8256 			if (ipif != NULL)
8257 				ipif_refrele(ipif);
8258 			ill_refrele(dst_ill);
8259 			ipif_refrele(src_ipif);
8260 			return;
8261 		default:
8262 			break;
8263 		}
8264 	} while (multirt_resolve_next);
8265 
8266 err_ret:
8267 	ip2dbg(("ip_newroute_ipif: dropped\n"));
8268 	if (fire != NULL)
8269 		ire_refrele(fire);
8270 	ipif_refrele(ipif);
8271 	/* Did this packet originate externally? */
8272 	if (dst_ill != NULL)
8273 		ill_refrele(dst_ill);
8274 	if (src_ipif != NULL)
8275 		ipif_refrele(src_ipif);
8276 	if (mp->b_prev || mp->b_next) {
8277 		mp->b_next = NULL;
8278 		mp->b_prev = NULL;
8279 	} else {
8280 		/*
8281 		 * Since ip_wput() isn't close to finished, we fill
8282 		 * in enough of the header for credible error reporting.
8283 		 */
8284 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
8285 			/* Failed */
8286 			freemsg(first_mp);
8287 			if (ire != NULL)
8288 				ire_refrele(ire);
8289 			return;
8290 		}
8291 	}
8292 	/*
8293 	 * At this point we will have ire only if RTF_BLACKHOLE
8294 	 * or RTF_REJECT flags are set on the IRE. It will not
8295 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8296 	 */
8297 	if (ire != NULL) {
8298 		if (ire->ire_flags & RTF_BLACKHOLE) {
8299 			ire_refrele(ire);
8300 			freemsg(first_mp);
8301 			return;
8302 		}
8303 		ire_refrele(ire);
8304 	}
8305 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE);
8306 }
8307 
8308 /* Name/Value Table Lookup Routine */
8309 char *
8310 ip_nv_lookup(nv_t *nv, int value)
8311 {
8312 	if (!nv)
8313 		return (NULL);
8314 	for (; nv->nv_name; nv++) {
8315 		if (nv->nv_value == value)
8316 			return (nv->nv_name);
8317 	}
8318 	return ("unknown");
8319 }
8320 
8321 /*
8322  * one day it can be patched to 1 from /etc/system for machines that have few
8323  * fast network interfaces feeding multiple cpus.
8324  */
8325 int ill_stream_putlocks = 0;
8326 
8327 /*
8328  * This is a module open, i.e. this is a control stream for access
8329  * to a DLPI device.  We allocate an ill_t as the instance data in
8330  * this case.
8331  */
8332 int
8333 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
8334 {
8335 	uint32_t mem_cnt;
8336 	uint32_t cpu_cnt;
8337 	uint32_t min_cnt;
8338 	pgcnt_t mem_avail;
8339 	extern uint32_t ip_cache_table_size, ip6_cache_table_size;
8340 	ill_t	*ill;
8341 	int	err;
8342 
8343 	/*
8344 	 * Prevent unprivileged processes from pushing IP so that
8345 	 * they can't send raw IP.
8346 	 */
8347 	if (secpolicy_net_rawaccess(credp) != 0)
8348 		return (EPERM);
8349 
8350 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
8351 	q->q_ptr = WR(q)->q_ptr = ill;
8352 
8353 	/*
8354 	 * ill_init initializes the ill fields and then sends down
8355 	 * down a DL_INFO_REQ after calling qprocson.
8356 	 */
8357 	err = ill_init(q, ill);
8358 	if (err != 0) {
8359 		mi_free(ill);
8360 		q->q_ptr = NULL;
8361 		WR(q)->q_ptr = NULL;
8362 		return (err);
8363 	}
8364 
8365 	/* ill_init initializes the ipsq marking this thread as writer */
8366 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
8367 	/* Wait for the DL_INFO_ACK */
8368 	mutex_enter(&ill->ill_lock);
8369 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
8370 		/*
8371 		 * Return value of 0 indicates a pending signal.
8372 		 */
8373 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
8374 		if (err == 0) {
8375 			mutex_exit(&ill->ill_lock);
8376 			(void) ip_close(q, 0);
8377 			return (EINTR);
8378 		}
8379 	}
8380 	mutex_exit(&ill->ill_lock);
8381 
8382 	/*
8383 	 * ip_rput_other could have set an error  in ill_error on
8384 	 * receipt of M_ERROR.
8385 	 */
8386 
8387 	err = ill->ill_error;
8388 	if (err != 0) {
8389 		(void) ip_close(q, 0);
8390 		return (err);
8391 	}
8392 
8393 	/*
8394 	 * ip_ire_max_bucket_cnt is sized below based on the memory
8395 	 * size and the cpu speed of the machine. This is upper
8396 	 * bounded by the compile time value of ip_ire_max_bucket_cnt
8397 	 * and is lower bounded by the compile time value of
8398 	 * ip_ire_min_bucket_cnt.  Similar logic applies to
8399 	 * ip6_ire_max_bucket_cnt.
8400 	 */
8401 	mem_avail = kmem_avail();
8402 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
8403 	    ip_cache_table_size / sizeof (ire_t);
8404 	cpu_cnt = CPU->cpu_type_info.pi_clock >> ip_ire_cpu_ratio;
8405 
8406 	min_cnt = MIN(cpu_cnt, mem_cnt);
8407 	if (min_cnt < ip_ire_min_bucket_cnt)
8408 		min_cnt = ip_ire_min_bucket_cnt;
8409 	if (ip_ire_max_bucket_cnt > min_cnt) {
8410 		ip_ire_max_bucket_cnt = min_cnt;
8411 	}
8412 
8413 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
8414 	    ip6_cache_table_size / sizeof (ire_t);
8415 	min_cnt = MIN(cpu_cnt, mem_cnt);
8416 	if (min_cnt < ip6_ire_min_bucket_cnt)
8417 		min_cnt = ip6_ire_min_bucket_cnt;
8418 	if (ip6_ire_max_bucket_cnt > min_cnt) {
8419 		ip6_ire_max_bucket_cnt = min_cnt;
8420 	}
8421 
8422 	ill->ill_credp = credp;
8423 	crhold(credp);
8424 
8425 	mutex_enter(&ip_mi_lock);
8426 	err = mi_open_link(&ip_g_head, (IDP)ill, devp, flag, sflag, credp);
8427 	mutex_exit(&ip_mi_lock);
8428 	if (err) {
8429 		(void) ip_close(q, 0);
8430 		return (err);
8431 	}
8432 	return (0);
8433 }
8434 
8435 /* IP open routine. */
8436 int
8437 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
8438 {
8439 	conn_t 		*connp;
8440 	major_t		maj;
8441 
8442 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
8443 
8444 	/* Allow reopen. */
8445 	if (q->q_ptr != NULL)
8446 		return (0);
8447 
8448 	if (sflag & MODOPEN) {
8449 		/* This is a module open */
8450 		return (ip_modopen(q, devp, flag, sflag, credp));
8451 	}
8452 
8453 
8454 	/*
8455 	 * We are opening as a device. This is an IP client stream, and we
8456 	 * allocate an conn_t as the instance data.
8457 	 */
8458 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP);
8459 	connp->conn_upq = q;
8460 	q->q_ptr = WR(q)->q_ptr = connp;
8461 
8462 	/* Minor tells us which /dev entry was opened */
8463 	if (geteminor(*devp) == IPV6_MINOR) {
8464 		connp->conn_flags |= IPCL_ISV6;
8465 		connp->conn_af_isv6 = B_TRUE;
8466 		ip_setqinfo(q, geteminor(*devp), B_FALSE);
8467 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
8468 	} else {
8469 		connp->conn_af_isv6 = B_FALSE;
8470 		connp->conn_pkt_isv6 = B_FALSE;
8471 	}
8472 
8473 
8474 	if ((connp->conn_dev =
8475 	    inet_minor_alloc(ip_minor_arena)) == 0) {
8476 		q->q_ptr = WR(q)->q_ptr = NULL;
8477 		CONN_DEC_REF(connp);
8478 		return (EBUSY);
8479 	}
8480 
8481 	maj = getemajor(*devp);
8482 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
8483 
8484 	/*
8485 	 * connp->conn_cred is crfree()ed in ip_close().
8486 	 */
8487 	connp->conn_cred = credp;
8488 	crhold(connp->conn_cred);
8489 
8490 	connp->conn_zoneid = getzoneid();
8491 
8492 	/*
8493 	 * This should only happen for ndd, netstat, raw socket or other SCTP
8494 	 * administrative ops.  In these cases, we just need a normal conn_t
8495 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
8496 	 * an error will be returned.
8497 	 */
8498 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
8499 		connp->conn_rq = q;
8500 		connp->conn_wq = WR(q);
8501 	} else {
8502 		connp->conn_ulp = IPPROTO_SCTP;
8503 		connp->conn_rq = connp->conn_wq = NULL;
8504 	}
8505 	/* Non-zero default values */
8506 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
8507 
8508 	/*
8509 	 * Make the conn globally visible to walkers
8510 	 */
8511 	mutex_enter(&connp->conn_lock);
8512 	connp->conn_state_flags &= ~CONN_INCIPIENT;
8513 	mutex_exit(&connp->conn_lock);
8514 	ASSERT(connp->conn_ref == 1);
8515 
8516 	qprocson(q);
8517 
8518 	return (0);
8519 }
8520 
8521 /*
8522  * Change q_qinfo based on the value of isv6.
8523  * This can not called on an ill queue.
8524  * Note that there is no race since either q_qinfo works for conn queues - it
8525  * is just an optimization to enter the best wput routine directly.
8526  */
8527 void
8528 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib)
8529 {
8530 	ASSERT(q->q_flag & QREADR);
8531 	ASSERT(WR(q)->q_next == NULL);
8532 	ASSERT(q->q_ptr != NULL);
8533 
8534 	if (minor == IPV6_MINOR)  {
8535 		if (bump_mib)
8536 			BUMP_MIB(&ip6_mib, ipv6OutSwitchIPv4);
8537 		q->q_qinfo = &rinit_ipv6;
8538 		WR(q)->q_qinfo = &winit_ipv6;
8539 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
8540 	} else {
8541 		if (bump_mib)
8542 			BUMP_MIB(&ip_mib, ipOutSwitchIPv6);
8543 		q->q_qinfo = &rinit;
8544 		WR(q)->q_qinfo = &winit;
8545 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
8546 	}
8547 
8548 }
8549 
8550 /*
8551  * See if IPsec needs loading because of the options in mp.
8552  */
8553 static boolean_t
8554 ipsec_opt_present(mblk_t *mp)
8555 {
8556 	uint8_t *optcp, *next_optcp, *opt_endcp;
8557 	struct opthdr *opt;
8558 	struct T_opthdr *topt;
8559 	int opthdr_len;
8560 	t_uscalar_t optname, optlevel;
8561 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
8562 	ipsec_req_t *ipsr;
8563 
8564 	/*
8565 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
8566 	 * return TRUE.
8567 	 */
8568 
8569 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
8570 	opt_endcp = optcp + tor->OPT_length;
8571 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
8572 		opthdr_len = sizeof (struct T_opthdr);
8573 	} else {		/* O_OPTMGMT_REQ */
8574 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
8575 		opthdr_len = sizeof (struct opthdr);
8576 	}
8577 	for (; optcp < opt_endcp; optcp = next_optcp) {
8578 		if (optcp + opthdr_len > opt_endcp)
8579 			return (B_FALSE);	/* Not enough option header. */
8580 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
8581 			topt = (struct T_opthdr *)optcp;
8582 			optlevel = topt->level;
8583 			optname = topt->name;
8584 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
8585 		} else {
8586 			opt = (struct opthdr *)optcp;
8587 			optlevel = opt->level;
8588 			optname = opt->name;
8589 			next_optcp = optcp + opthdr_len +
8590 			    _TPI_ALIGN_OPT(opt->len);
8591 		}
8592 		if ((next_optcp < optcp) || /* wraparound pointer space */
8593 		    ((next_optcp >= opt_endcp) && /* last option bad len */
8594 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
8595 			return (B_FALSE); /* bad option buffer */
8596 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
8597 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
8598 			/*
8599 			 * Check to see if it's an all-bypass or all-zeroes
8600 			 * IPsec request.  Don't bother loading IPsec if
8601 			 * the socket doesn't want to use it.  (A good example
8602 			 * is a bypass request.)
8603 			 *
8604 			 * Basically, if any of the non-NEVER bits are set,
8605 			 * load IPsec.
8606 			 */
8607 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
8608 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
8609 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
8610 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
8611 			    != 0)
8612 				return (B_TRUE);
8613 		}
8614 	}
8615 	return (B_FALSE);
8616 }
8617 
8618 /*
8619  * If conn is is waiting for ipsec to finish loading, kick it.
8620  */
8621 /* ARGSUSED */
8622 static void
8623 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
8624 {
8625 	t_scalar_t	optreq_prim;
8626 	mblk_t		*mp;
8627 	cred_t		*cr;
8628 	int		err = 0;
8629 
8630 	/*
8631 	 * This function is called, after ipsec loading is complete.
8632 	 * Since IP checks exclusively and atomically (i.e it prevents
8633 	 * ipsec load from completing until ip_optcom_req completes)
8634 	 * whether ipsec load is complete, there cannot be a race with IP
8635 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
8636 	 */
8637 	mutex_enter(&connp->conn_lock);
8638 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
8639 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
8640 		mp = connp->conn_ipsec_opt_mp;
8641 		connp->conn_ipsec_opt_mp = NULL;
8642 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
8643 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
8644 		mutex_exit(&connp->conn_lock);
8645 
8646 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
8647 
8648 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
8649 		if (optreq_prim == T_OPTMGMT_REQ) {
8650 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
8651 			    &ip_opt_obj);
8652 		} else {
8653 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
8654 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
8655 			    &ip_opt_obj);
8656 		}
8657 		if (err != EINPROGRESS)
8658 			CONN_OPER_PENDING_DONE(connp);
8659 		return;
8660 	}
8661 	mutex_exit(&connp->conn_lock);
8662 }
8663 
8664 /*
8665  * Called from the ipsec_loader thread, outside any perimeter, to tell
8666  * ip qenable any of the queues waiting for the ipsec loader to
8667  * complete.
8668  *
8669  * Use ip_mi_lock to be safe here: all modifications of the mi lists
8670  * are done with this lock held, so it's guaranteed that none of the
8671  * links will change along the way.
8672  */
8673 void
8674 ip_ipsec_load_complete()
8675 {
8676 	ipcl_walk(conn_restart_ipsec_waiter, NULL);
8677 }
8678 
8679 /*
8680  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
8681  * determines the grp on which it has to become exclusive, queues the mp
8682  * and sq draining restarts the optmgmt
8683  */
8684 static boolean_t
8685 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
8686 {
8687 	conn_t *connp;
8688 
8689 	/*
8690 	 * Take IPsec requests and treat them special.
8691 	 */
8692 	if (ipsec_opt_present(mp)) {
8693 		/* First check if IPsec is loaded. */
8694 		mutex_enter(&ipsec_loader_lock);
8695 		if (ipsec_loader_state != IPSEC_LOADER_WAIT) {
8696 			mutex_exit(&ipsec_loader_lock);
8697 			return (B_FALSE);
8698 		}
8699 		connp = Q_TO_CONN(q);
8700 		mutex_enter(&connp->conn_lock);
8701 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
8702 
8703 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
8704 		connp->conn_ipsec_opt_mp = mp;
8705 		mutex_exit(&connp->conn_lock);
8706 		mutex_exit(&ipsec_loader_lock);
8707 
8708 		ipsec_loader_loadnow();
8709 		return (B_TRUE);
8710 	}
8711 	return (B_FALSE);
8712 }
8713 
8714 /*
8715  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
8716  * all of them are copied to the conn_t. If the req is "zero", the policy is
8717  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
8718  * fields.
8719  * We keep only the latest setting of the policy and thus policy setting
8720  * is not incremental/cumulative.
8721  *
8722  * Requests to set policies with multiple alternative actions will
8723  * go through a different API.
8724  */
8725 int
8726 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
8727 {
8728 	uint_t ah_req = 0;
8729 	uint_t esp_req = 0;
8730 	uint_t se_req = 0;
8731 	ipsec_selkey_t sel;
8732 	ipsec_act_t *actp = NULL;
8733 	uint_t nact;
8734 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
8735 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
8736 	ipsec_policy_root_t *pr;
8737 	ipsec_policy_head_t *ph;
8738 	int fam;
8739 	boolean_t is_pol_reset;
8740 	int error = 0;
8741 
8742 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
8743 
8744 	/*
8745 	 * The IP_SEC_OPT option does not allow variable length parameters,
8746 	 * hence a request cannot be NULL.
8747 	 */
8748 	if (req == NULL)
8749 		return (EINVAL);
8750 
8751 	ah_req = req->ipsr_ah_req;
8752 	esp_req = req->ipsr_esp_req;
8753 	se_req = req->ipsr_self_encap_req;
8754 
8755 	/*
8756 	 * Are we dealing with a request to reset the policy (i.e.
8757 	 * zero requests).
8758 	 */
8759 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
8760 	    (esp_req & REQ_MASK) == 0 &&
8761 	    (se_req & REQ_MASK) == 0);
8762 
8763 	if (!is_pol_reset) {
8764 		/*
8765 		 * If we couldn't load IPsec, fail with "protocol
8766 		 * not supported".
8767 		 * IPsec may not have been loaded for a request with zero
8768 		 * policies, so we don't fail in this case.
8769 		 */
8770 		mutex_enter(&ipsec_loader_lock);
8771 		if (ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
8772 			mutex_exit(&ipsec_loader_lock);
8773 			return (EPROTONOSUPPORT);
8774 		}
8775 		mutex_exit(&ipsec_loader_lock);
8776 
8777 		/*
8778 		 * Test for valid requests. Invalid algorithms
8779 		 * need to be tested by IPSEC code because new
8780 		 * algorithms can be added dynamically.
8781 		 */
8782 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
8783 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
8784 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
8785 			return (EINVAL);
8786 		}
8787 
8788 		/*
8789 		 * Only privileged users can issue these
8790 		 * requests.
8791 		 */
8792 		if (((ah_req & IPSEC_PREF_NEVER) ||
8793 		    (esp_req & IPSEC_PREF_NEVER) ||
8794 		    (se_req & IPSEC_PREF_NEVER)) &&
8795 		    secpolicy_net_config(cr, B_FALSE) != 0) {
8796 			return (EPERM);
8797 		}
8798 
8799 		/*
8800 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
8801 		 * are mutually exclusive.
8802 		 */
8803 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
8804 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
8805 		    ((se_req & REQ_MASK) == REQ_MASK)) {
8806 			/* Both of them are set */
8807 			return (EINVAL);
8808 		}
8809 	}
8810 
8811 	mutex_enter(&connp->conn_lock);
8812 
8813 	/*
8814 	 * If we have already cached policies in ip_bind_connected*(), don't
8815 	 * let them change now. We cache policies for connections
8816 	 * whose src,dst [addr, port] is known.  The exception to this is
8817 	 * tunnels.  Tunnels are allowed to change policies after having
8818 	 * become fully bound.
8819 	 */
8820 	if (connp->conn_policy_cached && !IPCL_IS_IPTUN(connp)) {
8821 		mutex_exit(&connp->conn_lock);
8822 		return (EINVAL);
8823 	}
8824 
8825 	/*
8826 	 * We have a zero policies, reset the connection policy if already
8827 	 * set. This will cause the connection to inherit the
8828 	 * global policy, if any.
8829 	 */
8830 	if (is_pol_reset) {
8831 		if (connp->conn_policy != NULL) {
8832 			IPPH_REFRELE(connp->conn_policy);
8833 			connp->conn_policy = NULL;
8834 		}
8835 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
8836 		connp->conn_in_enforce_policy = B_FALSE;
8837 		connp->conn_out_enforce_policy = B_FALSE;
8838 		mutex_exit(&connp->conn_lock);
8839 		return (0);
8840 	}
8841 
8842 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy);
8843 	if (ph == NULL)
8844 		goto enomem;
8845 
8846 	ipsec_actvec_from_req(req, &actp, &nact);
8847 	if (actp == NULL)
8848 		goto enomem;
8849 
8850 	/*
8851 	 * Always allocate IPv4 policy entries, since they can also
8852 	 * apply to ipv6 sockets being used in ipv4-compat mode.
8853 	 */
8854 	bzero(&sel, sizeof (sel));
8855 	sel.ipsl_valid = IPSL_IPV4;
8856 
8857 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
8858 	if (pin4 == NULL)
8859 		goto enomem;
8860 
8861 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
8862 	if (pout4 == NULL)
8863 		goto enomem;
8864 
8865 	if (connp->conn_pkt_isv6) {
8866 		/*
8867 		 * We're looking at a v6 socket, also allocate the
8868 		 * v6-specific entries...
8869 		 */
8870 		sel.ipsl_valid = IPSL_IPV6;
8871 		pin6 = ipsec_policy_create(&sel, actp, nact,
8872 		    IPSEC_PRIO_SOCKET);
8873 		if (pin6 == NULL)
8874 			goto enomem;
8875 
8876 		pout6 = ipsec_policy_create(&sel, actp, nact,
8877 		    IPSEC_PRIO_SOCKET);
8878 		if (pout6 == NULL)
8879 			goto enomem;
8880 
8881 		/*
8882 		 * .. and file them away in the right place.
8883 		 */
8884 		fam = IPSEC_AF_V6;
8885 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
8886 		pin6->ipsp_links.itl_next = pr->ipr[fam];
8887 		pr->ipr[fam] = pin6;
8888 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
8889 		pout6->ipsp_links.itl_next = pr->ipr[fam];
8890 		pr->ipr[fam] = pout6;
8891 	}
8892 
8893 	ipsec_actvec_free(actp, nact);
8894 
8895 	/*
8896 	 * File the v4 policies.
8897 	 */
8898 	fam = IPSEC_AF_V4;
8899 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
8900 	pin4->ipsp_links.itl_next = pr->ipr[fam];
8901 	pr->ipr[fam] = pin4;
8902 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
8903 	pout4->ipsp_links.itl_next = pr->ipr[fam];
8904 	pr->ipr[fam] = pout4;
8905 
8906 	/*
8907 	 * If the requests need security, set enforce_policy.
8908 	 * If the requests are IPSEC_PREF_NEVER, one should
8909 	 * still set conn_out_enforce_policy so that an ipsec_out
8910 	 * gets attached in ip_wput. This is needed so that
8911 	 * for connections that we don't cache policy in ip_bind,
8912 	 * if global policy matches in ip_wput_attach_policy, we
8913 	 * don't wrongly inherit global policy. Similarly, we need
8914 	 * to set conn_in_enforce_policy also so that we don't verify
8915 	 * policy wrongly.
8916 	 */
8917 	if ((ah_req & REQ_MASK) != 0 ||
8918 	    (esp_req & REQ_MASK) != 0 ||
8919 	    (se_req & REQ_MASK) != 0) {
8920 		connp->conn_in_enforce_policy = B_TRUE;
8921 		connp->conn_out_enforce_policy = B_TRUE;
8922 		connp->conn_flags |= IPCL_CHECK_POLICY;
8923 	}
8924 
8925 	/*
8926 	 * Tunnels are allowed to set policy after having been fully bound.
8927 	 * If that's the case, cache policy here.
8928 	 */
8929 	if (IPCL_IS_IPTUN(connp) && connp->conn_fully_bound)
8930 		error = ipsec_conn_cache_policy(connp, !connp->conn_af_isv6);
8931 
8932 	mutex_exit(&connp->conn_lock);
8933 	return (error);
8934 #undef REQ_MASK
8935 
8936 	/*
8937 	 * Common memory-allocation-failure exit path.
8938 	 */
8939 enomem:
8940 	mutex_exit(&connp->conn_lock);
8941 	if (actp != NULL)
8942 		ipsec_actvec_free(actp, nact);
8943 	if (pin4 != NULL)
8944 		IPPOL_REFRELE(pin4);
8945 	if (pout4 != NULL)
8946 		IPPOL_REFRELE(pout4);
8947 	if (pin6 != NULL)
8948 		IPPOL_REFRELE(pin6);
8949 	if (pout6 != NULL)
8950 		IPPOL_REFRELE(pout6);
8951 	return (ENOMEM);
8952 }
8953 
8954 /*
8955  * Only for options that pass in an IP addr. Currently only V4 options
8956  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
8957  * So this function assumes level is IPPROTO_IP
8958  */
8959 int
8960 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
8961     mblk_t *first_mp)
8962 {
8963 	ipif_t *ipif = NULL;
8964 	int error;
8965 	ill_t *ill;
8966 
8967 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
8968 
8969 	if (addr != INADDR_ANY || checkonly) {
8970 		ASSERT(connp != NULL);
8971 		ipif = ipif_lookup_addr(addr, NULL, connp->conn_zoneid,
8972 		    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt, &error);
8973 		if (ipif == NULL) {
8974 			if (error == EINPROGRESS)
8975 				return (error);
8976 			else if (option == IP_MULTICAST_IF)
8977 				return (EHOSTUNREACH);
8978 			else
8979 				return (EINVAL);
8980 		} else if (checkonly) {
8981 			if (option == IP_MULTICAST_IF) {
8982 				ill = ipif->ipif_ill;
8983 				/* not supported by the virtual network iface */
8984 				if (IS_VNI(ill)) {
8985 					ipif_refrele(ipif);
8986 					return (EINVAL);
8987 				}
8988 			}
8989 			ipif_refrele(ipif);
8990 			return (0);
8991 		}
8992 		ill = ipif->ipif_ill;
8993 		mutex_enter(&connp->conn_lock);
8994 		mutex_enter(&ill->ill_lock);
8995 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
8996 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
8997 			mutex_exit(&ill->ill_lock);
8998 			mutex_exit(&connp->conn_lock);
8999 			ipif_refrele(ipif);
9000 			return (option == IP_MULTICAST_IF ?
9001 			    EHOSTUNREACH : EINVAL);
9002 		}
9003 	} else {
9004 		mutex_enter(&connp->conn_lock);
9005 	}
9006 
9007 	/* None of the options below are supported on the VNI */
9008 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
9009 		mutex_exit(&ill->ill_lock);
9010 		mutex_exit(&connp->conn_lock);
9011 		ipif_refrele(ipif);
9012 		return (EINVAL);
9013 	}
9014 
9015 	switch (option) {
9016 	case IP_DONTFAILOVER_IF:
9017 		/*
9018 		 * This option is used by in.mpathd to ensure
9019 		 * that IPMP probe packets only go out on the
9020 		 * test interfaces. in.mpathd sets this option
9021 		 * on the non-failover interfaces.
9022 		 * For backward compatibility, this option
9023 		 * implicitly sets IP_MULTICAST_IF, as used
9024 		 * be done in bind(), so that ip_wput gets
9025 		 * this ipif to send mcast packets.
9026 		 */
9027 		if (ipif != NULL) {
9028 			ASSERT(addr != INADDR_ANY);
9029 			connp->conn_nofailover_ill = ipif->ipif_ill;
9030 			connp->conn_multicast_ipif = ipif;
9031 		} else {
9032 			ASSERT(addr == INADDR_ANY);
9033 			connp->conn_nofailover_ill = NULL;
9034 			connp->conn_multicast_ipif = NULL;
9035 		}
9036 		break;
9037 
9038 	case IP_MULTICAST_IF:
9039 		connp->conn_multicast_ipif = ipif;
9040 		break;
9041 	}
9042 
9043 	if (ipif != NULL) {
9044 		mutex_exit(&ill->ill_lock);
9045 		mutex_exit(&connp->conn_lock);
9046 		ipif_refrele(ipif);
9047 		return (0);
9048 	}
9049 	mutex_exit(&connp->conn_lock);
9050 	/* We succeded in cleared the option */
9051 	return (0);
9052 }
9053 
9054 /*
9055  * For options that pass in an ifindex specifying the ill. V6 options always
9056  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
9057  */
9058 int
9059 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
9060     int level, int option, mblk_t *first_mp)
9061 {
9062 	ill_t *ill = NULL;
9063 	int error = 0;
9064 
9065 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
9066 	if (ifindex != 0) {
9067 		ASSERT(connp != NULL);
9068 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
9069 		    first_mp, ip_restart_optmgmt, &error);
9070 		if (ill != NULL) {
9071 			if (checkonly) {
9072 				/* not supported by the virtual network iface */
9073 				if (IS_VNI(ill)) {
9074 					ill_refrele(ill);
9075 					return (EINVAL);
9076 				}
9077 				ill_refrele(ill);
9078 				return (0);
9079 			}
9080 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
9081 			    0, NULL)) {
9082 				ill_refrele(ill);
9083 				ill = NULL;
9084 				mutex_enter(&connp->conn_lock);
9085 				goto setit;
9086 			}
9087 			mutex_enter(&connp->conn_lock);
9088 			mutex_enter(&ill->ill_lock);
9089 			if (ill->ill_state_flags & ILL_CONDEMNED) {
9090 				mutex_exit(&ill->ill_lock);
9091 				mutex_exit(&connp->conn_lock);
9092 				ill_refrele(ill);
9093 				ill = NULL;
9094 				mutex_enter(&connp->conn_lock);
9095 			}
9096 			goto setit;
9097 		} else if (error == EINPROGRESS) {
9098 			return (error);
9099 		} else {
9100 			error = 0;
9101 		}
9102 	}
9103 	mutex_enter(&connp->conn_lock);
9104 setit:
9105 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
9106 
9107 	/*
9108 	 * The options below assume that the ILL (if any) transmits and/or
9109 	 * receives traffic. Neither of which is true for the virtual network
9110 	 * interface, so fail setting these on a VNI.
9111 	 */
9112 	if (IS_VNI(ill)) {
9113 		ASSERT(ill != NULL);
9114 		mutex_exit(&ill->ill_lock);
9115 		mutex_exit(&connp->conn_lock);
9116 		ill_refrele(ill);
9117 		return (EINVAL);
9118 	}
9119 
9120 	if (level == IPPROTO_IP) {
9121 		switch (option) {
9122 		case IP_BOUND_IF:
9123 			connp->conn_incoming_ill = ill;
9124 			connp->conn_outgoing_ill = ill;
9125 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
9126 			    0 : ifindex;
9127 			break;
9128 
9129 		case IP_XMIT_IF:
9130 			/*
9131 			 * Similar to IP_BOUND_IF, but this only
9132 			 * determines the outgoing interface for
9133 			 * unicast packets. Also no IRE_CACHE entry
9134 			 * is added for the destination of the
9135 			 * outgoing packets. This feature is needed
9136 			 * for mobile IP.
9137 			 */
9138 			connp->conn_xmit_if_ill = ill;
9139 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
9140 			    0 : ifindex;
9141 			break;
9142 
9143 		case IP_MULTICAST_IF:
9144 			/*
9145 			 * This option is an internal special. The socket
9146 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
9147 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
9148 			 * specifies an ifindex and we try first on V6 ill's.
9149 			 * If we don't find one, we they try using on v4 ill's
9150 			 * intenally and we come here.
9151 			 */
9152 			if (!checkonly && ill != NULL) {
9153 				ipif_t	*ipif;
9154 				ipif = ill->ill_ipif;
9155 
9156 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
9157 					mutex_exit(&ill->ill_lock);
9158 					mutex_exit(&connp->conn_lock);
9159 					ill_refrele(ill);
9160 					ill = NULL;
9161 					mutex_enter(&connp->conn_lock);
9162 				} else {
9163 					connp->conn_multicast_ipif = ipif;
9164 				}
9165 			}
9166 			break;
9167 		}
9168 	} else {
9169 		switch (option) {
9170 		case IPV6_BOUND_IF:
9171 			connp->conn_incoming_ill = ill;
9172 			connp->conn_outgoing_ill = ill;
9173 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
9174 			    0 : ifindex;
9175 			break;
9176 
9177 		case IPV6_BOUND_PIF:
9178 			/*
9179 			 * Limit all transmit to this ill.
9180 			 * Unlike IPV6_BOUND_IF, using this option
9181 			 * prevents load spreading and failover from
9182 			 * happening when the interface is part of the
9183 			 * group. That's why we don't need to remember
9184 			 * the ifindex in orig_bound_ifindex as in
9185 			 * IPV6_BOUND_IF.
9186 			 */
9187 			connp->conn_outgoing_pill = ill;
9188 			break;
9189 
9190 		case IPV6_DONTFAILOVER_IF:
9191 			/*
9192 			 * This option is used by in.mpathd to ensure
9193 			 * that IPMP probe packets only go out on the
9194 			 * test interfaces. in.mpathd sets this option
9195 			 * on the non-failover interfaces.
9196 			 */
9197 			connp->conn_nofailover_ill = ill;
9198 			/*
9199 			 * For backward compatibility, this option
9200 			 * implicitly sets ip_multicast_ill as used in
9201 			 * IP_MULTICAST_IF so that ip_wput gets
9202 			 * this ipif to send mcast packets.
9203 			 */
9204 			connp->conn_multicast_ill = ill;
9205 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
9206 			    0 : ifindex;
9207 			break;
9208 
9209 		case IPV6_MULTICAST_IF:
9210 			/*
9211 			 * Set conn_multicast_ill to be the IPv6 ill.
9212 			 * Set conn_multicast_ipif to be an IPv4 ipif
9213 			 * for ifindex to make IPv4 mapped addresses
9214 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
9215 			 * Even if no IPv6 ill exists for the ifindex
9216 			 * we need to check for an IPv4 ifindex in order
9217 			 * for this to work with mapped addresses. In that
9218 			 * case only set conn_multicast_ipif.
9219 			 */
9220 			if (!checkonly) {
9221 				if (ifindex == 0) {
9222 					connp->conn_multicast_ill = NULL;
9223 					connp->conn_orig_multicast_ifindex = 0;
9224 					connp->conn_multicast_ipif = NULL;
9225 				} else if (ill != NULL) {
9226 					connp->conn_multicast_ill = ill;
9227 					connp->conn_orig_multicast_ifindex =
9228 					    ifindex;
9229 				}
9230 			}
9231 			break;
9232 		}
9233 	}
9234 
9235 	if (ill != NULL) {
9236 		mutex_exit(&ill->ill_lock);
9237 		mutex_exit(&connp->conn_lock);
9238 		ill_refrele(ill);
9239 		return (0);
9240 	}
9241 	mutex_exit(&connp->conn_lock);
9242 	/*
9243 	 * We succeeded in clearing the option (ifindex == 0) or failed to
9244 	 * locate the ill and could not set the option (ifindex != 0)
9245 	 */
9246 	return (ifindex == 0 ? 0 : EINVAL);
9247 }
9248 
9249 /* This routine sets socket options. */
9250 /* ARGSUSED */
9251 int
9252 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
9253     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9254     void *dummy, cred_t *cr, mblk_t *first_mp)
9255 {
9256 	int		*i1 = (int *)invalp;
9257 	conn_t		*connp = Q_TO_CONN(q);
9258 	int		error = 0;
9259 	boolean_t	checkonly;
9260 	ire_t		*ire;
9261 	boolean_t	found;
9262 
9263 	switch (optset_context) {
9264 
9265 	case SETFN_OPTCOM_CHECKONLY:
9266 		checkonly = B_TRUE;
9267 		/*
9268 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9269 		 * inlen != 0 implies value supplied and
9270 		 * 	we have to "pretend" to set it.
9271 		 * inlen == 0 implies that there is no
9272 		 * 	value part in T_CHECK request and just validation
9273 		 * done elsewhere should be enough, we just return here.
9274 		 */
9275 		if (inlen == 0) {
9276 			*outlenp = 0;
9277 			return (0);
9278 		}
9279 		break;
9280 	case SETFN_OPTCOM_NEGOTIATE:
9281 	case SETFN_UD_NEGOTIATE:
9282 	case SETFN_CONN_NEGOTIATE:
9283 		checkonly = B_FALSE;
9284 		break;
9285 	default:
9286 		/*
9287 		 * We should never get here
9288 		 */
9289 		*outlenp = 0;
9290 		return (EINVAL);
9291 	}
9292 
9293 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
9294 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
9295 
9296 	/*
9297 	 * For fixed length options, no sanity check
9298 	 * of passed in length is done. It is assumed *_optcom_req()
9299 	 * routines do the right thing.
9300 	 */
9301 
9302 	switch (level) {
9303 	case SOL_SOCKET:
9304 		/*
9305 		 * conn_lock protects the bitfields, and is used to
9306 		 * set the fields atomically.
9307 		 */
9308 		switch (name) {
9309 		case SO_BROADCAST:
9310 			if (!checkonly) {
9311 				/* TODO: use value someplace? */
9312 				mutex_enter(&connp->conn_lock);
9313 				connp->conn_broadcast = *i1 ? 1 : 0;
9314 				mutex_exit(&connp->conn_lock);
9315 			}
9316 			break;	/* goto sizeof (int) option return */
9317 		case SO_USELOOPBACK:
9318 			if (!checkonly) {
9319 				/* TODO: use value someplace? */
9320 				mutex_enter(&connp->conn_lock);
9321 				connp->conn_loopback = *i1 ? 1 : 0;
9322 				mutex_exit(&connp->conn_lock);
9323 			}
9324 			break;	/* goto sizeof (int) option return */
9325 		case SO_DONTROUTE:
9326 			if (!checkonly) {
9327 				mutex_enter(&connp->conn_lock);
9328 				connp->conn_dontroute = *i1 ? 1 : 0;
9329 				mutex_exit(&connp->conn_lock);
9330 			}
9331 			break;	/* goto sizeof (int) option return */
9332 		case SO_REUSEADDR:
9333 			if (!checkonly) {
9334 				mutex_enter(&connp->conn_lock);
9335 				connp->conn_reuseaddr = *i1 ? 1 : 0;
9336 				mutex_exit(&connp->conn_lock);
9337 			}
9338 			break;	/* goto sizeof (int) option return */
9339 		case SO_PROTOTYPE:
9340 			if (!checkonly) {
9341 				mutex_enter(&connp->conn_lock);
9342 				connp->conn_proto = *i1;
9343 				mutex_exit(&connp->conn_lock);
9344 			}
9345 			break;	/* goto sizeof (int) option return */
9346 		default:
9347 			/*
9348 			 * "soft" error (negative)
9349 			 * option not handled at this level
9350 			 * Note: Do not modify *outlenp
9351 			 */
9352 			return (-EINVAL);
9353 		}
9354 		break;
9355 	case IPPROTO_IP:
9356 		switch (name) {
9357 		case IP_MULTICAST_IF:
9358 		case IP_DONTFAILOVER_IF: {
9359 			ipaddr_t addr = *i1;
9360 
9361 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
9362 			    first_mp);
9363 			if (error != 0)
9364 				return (error);
9365 			break;	/* goto sizeof (int) option return */
9366 		}
9367 
9368 		case IP_MULTICAST_TTL:
9369 			/* Recorded in transport above IP */
9370 			*outvalp = *invalp;
9371 			*outlenp = sizeof (uchar_t);
9372 			return (0);
9373 		case IP_MULTICAST_LOOP:
9374 			if (!checkonly) {
9375 				mutex_enter(&connp->conn_lock);
9376 				connp->conn_multicast_loop = *invalp ? 1 : 0;
9377 				mutex_exit(&connp->conn_lock);
9378 			}
9379 			*outvalp = *invalp;
9380 			*outlenp = sizeof (uchar_t);
9381 			return (0);
9382 		case IP_ADD_MEMBERSHIP:
9383 		case MCAST_JOIN_GROUP:
9384 		case IP_DROP_MEMBERSHIP:
9385 		case MCAST_LEAVE_GROUP: {
9386 			struct ip_mreq *mreqp;
9387 			struct group_req *greqp;
9388 			ire_t *ire;
9389 			boolean_t done = B_FALSE;
9390 			ipaddr_t group, ifaddr;
9391 			struct sockaddr_in *sin;
9392 			uint32_t *ifindexp;
9393 			boolean_t mcast_opt = B_TRUE;
9394 			mcast_record_t fmode;
9395 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
9396 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
9397 
9398 			switch (name) {
9399 			case IP_ADD_MEMBERSHIP:
9400 				mcast_opt = B_FALSE;
9401 				/* FALLTHRU */
9402 			case MCAST_JOIN_GROUP:
9403 				fmode = MODE_IS_EXCLUDE;
9404 				optfn = ip_opt_add_group;
9405 				break;
9406 
9407 			case IP_DROP_MEMBERSHIP:
9408 				mcast_opt = B_FALSE;
9409 				/* FALLTHRU */
9410 			case MCAST_LEAVE_GROUP:
9411 				fmode = MODE_IS_INCLUDE;
9412 				optfn = ip_opt_delete_group;
9413 				break;
9414 			}
9415 
9416 			if (mcast_opt) {
9417 				greqp = (struct group_req *)i1;
9418 				sin = (struct sockaddr_in *)&greqp->gr_group;
9419 				if (sin->sin_family != AF_INET) {
9420 					*outlenp = 0;
9421 					return (ENOPROTOOPT);
9422 				}
9423 				group = (ipaddr_t)sin->sin_addr.s_addr;
9424 				ifaddr = INADDR_ANY;
9425 				ifindexp = &greqp->gr_interface;
9426 			} else {
9427 				mreqp = (struct ip_mreq *)i1;
9428 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
9429 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
9430 				ifindexp = NULL;
9431 			}
9432 
9433 			/*
9434 			 * In the multirouting case, we need to replicate
9435 			 * the request on all interfaces that will take part
9436 			 * in replication.  We do so because multirouting is
9437 			 * reflective, thus we will probably receive multi-
9438 			 * casts on those interfaces.
9439 			 * The ip_multirt_apply_membership() succeeds if the
9440 			 * operation succeeds on at least one interface.
9441 			 */
9442 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
9443 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
9444 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
9445 			if (ire != NULL) {
9446 				if (ire->ire_flags & RTF_MULTIRT) {
9447 					error = ip_multirt_apply_membership(
9448 					    optfn, ire, connp, checkonly, group,
9449 					    fmode, INADDR_ANY, first_mp);
9450 					done = B_TRUE;
9451 				}
9452 				ire_refrele(ire);
9453 			}
9454 			if (!done) {
9455 				error = optfn(connp, checkonly, group, ifaddr,
9456 				    ifindexp, fmode, INADDR_ANY, first_mp);
9457 			}
9458 			if (error) {
9459 				/*
9460 				 * EINPROGRESS is a soft error, needs retry
9461 				 * so don't make *outlenp zero.
9462 				 */
9463 				if (error != EINPROGRESS)
9464 					*outlenp = 0;
9465 				return (error);
9466 			}
9467 			/* OK return - copy input buffer into output buffer */
9468 			if (invalp != outvalp) {
9469 				/* don't trust bcopy for identical src/dst */
9470 				bcopy(invalp, outvalp, inlen);
9471 			}
9472 			*outlenp = inlen;
9473 			return (0);
9474 		}
9475 		case IP_BLOCK_SOURCE:
9476 		case IP_UNBLOCK_SOURCE:
9477 		case IP_ADD_SOURCE_MEMBERSHIP:
9478 		case IP_DROP_SOURCE_MEMBERSHIP:
9479 		case MCAST_BLOCK_SOURCE:
9480 		case MCAST_UNBLOCK_SOURCE:
9481 		case MCAST_JOIN_SOURCE_GROUP:
9482 		case MCAST_LEAVE_SOURCE_GROUP: {
9483 			struct ip_mreq_source *imreqp;
9484 			struct group_source_req *gsreqp;
9485 			in_addr_t grp, src, ifaddr = INADDR_ANY;
9486 			uint32_t ifindex = 0;
9487 			mcast_record_t fmode;
9488 			struct sockaddr_in *sin;
9489 			ire_t *ire;
9490 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
9491 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
9492 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
9493 
9494 			switch (name) {
9495 			case IP_BLOCK_SOURCE:
9496 				mcast_opt = B_FALSE;
9497 				/* FALLTHRU */
9498 			case MCAST_BLOCK_SOURCE:
9499 				fmode = MODE_IS_EXCLUDE;
9500 				optfn = ip_opt_add_group;
9501 				break;
9502 
9503 			case IP_UNBLOCK_SOURCE:
9504 				mcast_opt = B_FALSE;
9505 				/* FALLTHRU */
9506 			case MCAST_UNBLOCK_SOURCE:
9507 				fmode = MODE_IS_EXCLUDE;
9508 				optfn = ip_opt_delete_group;
9509 				break;
9510 
9511 			case IP_ADD_SOURCE_MEMBERSHIP:
9512 				mcast_opt = B_FALSE;
9513 				/* FALLTHRU */
9514 			case MCAST_JOIN_SOURCE_GROUP:
9515 				fmode = MODE_IS_INCLUDE;
9516 				optfn = ip_opt_add_group;
9517 				break;
9518 
9519 			case IP_DROP_SOURCE_MEMBERSHIP:
9520 				mcast_opt = B_FALSE;
9521 				/* FALLTHRU */
9522 			case MCAST_LEAVE_SOURCE_GROUP:
9523 				fmode = MODE_IS_INCLUDE;
9524 				optfn = ip_opt_delete_group;
9525 				break;
9526 			}
9527 
9528 			if (mcast_opt) {
9529 				gsreqp = (struct group_source_req *)i1;
9530 				if (gsreqp->gsr_group.ss_family != AF_INET) {
9531 					*outlenp = 0;
9532 					return (ENOPROTOOPT);
9533 				}
9534 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
9535 				grp = (ipaddr_t)sin->sin_addr.s_addr;
9536 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
9537 				src = (ipaddr_t)sin->sin_addr.s_addr;
9538 				ifindex = gsreqp->gsr_interface;
9539 			} else {
9540 				imreqp = (struct ip_mreq_source *)i1;
9541 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
9542 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
9543 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
9544 			}
9545 
9546 			/*
9547 			 * In the multirouting case, we need to replicate
9548 			 * the request as noted in the mcast cases above.
9549 			 */
9550 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
9551 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
9552 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
9553 			if (ire != NULL) {
9554 				if (ire->ire_flags & RTF_MULTIRT) {
9555 					error = ip_multirt_apply_membership(
9556 					    optfn, ire, connp, checkonly, grp,
9557 					    fmode, src, first_mp);
9558 					done = B_TRUE;
9559 				}
9560 				ire_refrele(ire);
9561 			}
9562 			if (!done) {
9563 				error = optfn(connp, checkonly, grp, ifaddr,
9564 				    &ifindex, fmode, src, first_mp);
9565 			}
9566 			if (error != 0) {
9567 				/*
9568 				 * EINPROGRESS is a soft error, needs retry
9569 				 * so don't make *outlenp zero.
9570 				 */
9571 				if (error != EINPROGRESS)
9572 					*outlenp = 0;
9573 				return (error);
9574 			}
9575 			/* OK return - copy input buffer into output buffer */
9576 			if (invalp != outvalp) {
9577 				bcopy(invalp, outvalp, inlen);
9578 			}
9579 			*outlenp = inlen;
9580 			return (0);
9581 		}
9582 		case IP_SEC_OPT:
9583 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
9584 			if (error != 0) {
9585 				*outlenp = 0;
9586 				return (error);
9587 			}
9588 			break;
9589 		case IP_HDRINCL:
9590 		case IP_OPTIONS:
9591 		case T_IP_OPTIONS:
9592 		case IP_TOS:
9593 		case T_IP_TOS:
9594 		case IP_TTL:
9595 		case IP_RECVDSTADDR:
9596 		case IP_RECVOPTS:
9597 			/* OK return - copy input buffer into output buffer */
9598 			if (invalp != outvalp) {
9599 				/* don't trust bcopy for identical src/dst */
9600 				bcopy(invalp, outvalp, inlen);
9601 			}
9602 			*outlenp = inlen;
9603 			return (0);
9604 		case IP_RECVIF:
9605 			/* Retrieve the inbound interface index */
9606 			if (!checkonly) {
9607 				mutex_enter(&connp->conn_lock);
9608 				connp->conn_recvif = *i1 ? 1 : 0;
9609 				mutex_exit(&connp->conn_lock);
9610 			}
9611 			break;	/* goto sizeof (int) option return */
9612 		case IP_RECVSLLA:
9613 			/* Retrieve the source link layer address */
9614 			if (!checkonly) {
9615 				mutex_enter(&connp->conn_lock);
9616 				connp->conn_recvslla = *i1 ? 1 : 0;
9617 				mutex_exit(&connp->conn_lock);
9618 			}
9619 			break;	/* goto sizeof (int) option return */
9620 		case MRT_INIT:
9621 		case MRT_DONE:
9622 		case MRT_ADD_VIF:
9623 		case MRT_DEL_VIF:
9624 		case MRT_ADD_MFC:
9625 		case MRT_DEL_MFC:
9626 		case MRT_ASSERT:
9627 			if ((error = secpolicy_net_config(cr, B_FALSE)) != 0) {
9628 				*outlenp = 0;
9629 				return (error);
9630 			}
9631 			error = ip_mrouter_set((int)name, q, checkonly,
9632 			    (uchar_t *)invalp, inlen, first_mp);
9633 			if (error) {
9634 				*outlenp = 0;
9635 				return (error);
9636 			}
9637 			/* OK return - copy input buffer into output buffer */
9638 			if (invalp != outvalp) {
9639 				/* don't trust bcopy for identical src/dst */
9640 				bcopy(invalp, outvalp, inlen);
9641 			}
9642 			*outlenp = inlen;
9643 			return (0);
9644 		case IP_BOUND_IF:
9645 		case IP_XMIT_IF:
9646 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
9647 			    level, name, first_mp);
9648 			if (error != 0)
9649 				return (error);
9650 			break; 		/* goto sizeof (int) option return */
9651 
9652 		case IP_UNSPEC_SRC:
9653 			/* Allow sending with a zero source address */
9654 			if (!checkonly) {
9655 				mutex_enter(&connp->conn_lock);
9656 				connp->conn_unspec_src = *i1 ? 1 : 0;
9657 				mutex_exit(&connp->conn_lock);
9658 			}
9659 			break;	/* goto sizeof (int) option return */
9660 		default:
9661 			/*
9662 			 * "soft" error (negative)
9663 			 * option not handled at this level
9664 			 * Note: Do not modify *outlenp
9665 			 */
9666 			return (-EINVAL);
9667 		}
9668 		break;
9669 	case IPPROTO_IPV6:
9670 		switch (name) {
9671 		case IPV6_BOUND_IF:
9672 		case IPV6_BOUND_PIF:
9673 		case IPV6_DONTFAILOVER_IF:
9674 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
9675 			    level, name, first_mp);
9676 			if (error != 0)
9677 				return (error);
9678 			break; 		/* goto sizeof (int) option return */
9679 
9680 		case IPV6_MULTICAST_IF:
9681 			/*
9682 			 * The only possible errors are EINPROGRESS and
9683 			 * EINVAL. EINPROGRESS will be restarted and is not
9684 			 * a hard error. We call this option on both V4 and V6
9685 			 * If both return EINVAL, then this call returns
9686 			 * EINVAL. If at least one of them succeeds we
9687 			 * return success.
9688 			 */
9689 			found = B_FALSE;
9690 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
9691 			    level, name, first_mp);
9692 			if (error == EINPROGRESS)
9693 				return (error);
9694 			if (error == 0)
9695 				found = B_TRUE;
9696 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
9697 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
9698 			if (error == 0)
9699 				found = B_TRUE;
9700 			if (!found)
9701 				return (error);
9702 			break; 		/* goto sizeof (int) option return */
9703 
9704 		case IPV6_MULTICAST_HOPS:
9705 			/* Recorded in transport above IP */
9706 			break;	/* goto sizeof (int) option return */
9707 		case IPV6_MULTICAST_LOOP:
9708 			if (!checkonly) {
9709 				mutex_enter(&connp->conn_lock);
9710 				connp->conn_multicast_loop = *i1;
9711 				mutex_exit(&connp->conn_lock);
9712 			}
9713 			break;	/* goto sizeof (int) option return */
9714 		case IPV6_JOIN_GROUP:
9715 		case MCAST_JOIN_GROUP:
9716 		case IPV6_LEAVE_GROUP:
9717 		case MCAST_LEAVE_GROUP: {
9718 			struct ipv6_mreq *ip_mreqp;
9719 			struct group_req *greqp;
9720 			ire_t *ire;
9721 			boolean_t done = B_FALSE;
9722 			in6_addr_t groupv6;
9723 			uint32_t ifindex;
9724 			boolean_t mcast_opt = B_TRUE;
9725 			mcast_record_t fmode;
9726 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
9727 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
9728 
9729 			switch (name) {
9730 			case IPV6_JOIN_GROUP:
9731 				mcast_opt = B_FALSE;
9732 				/* FALLTHRU */
9733 			case MCAST_JOIN_GROUP:
9734 				fmode = MODE_IS_EXCLUDE;
9735 				optfn = ip_opt_add_group_v6;
9736 				break;
9737 
9738 			case IPV6_LEAVE_GROUP:
9739 				mcast_opt = B_FALSE;
9740 				/* FALLTHRU */
9741 			case MCAST_LEAVE_GROUP:
9742 				fmode = MODE_IS_INCLUDE;
9743 				optfn = ip_opt_delete_group_v6;
9744 				break;
9745 			}
9746 
9747 			if (mcast_opt) {
9748 				struct sockaddr_in *sin;
9749 				struct sockaddr_in6 *sin6;
9750 				greqp = (struct group_req *)i1;
9751 				if (greqp->gr_group.ss_family == AF_INET) {
9752 					sin = (struct sockaddr_in *)
9753 					    &(greqp->gr_group);
9754 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
9755 					    &groupv6);
9756 				} else {
9757 					sin6 = (struct sockaddr_in6 *)
9758 					    &(greqp->gr_group);
9759 					groupv6 = sin6->sin6_addr;
9760 				}
9761 				ifindex = greqp->gr_interface;
9762 			} else {
9763 				ip_mreqp = (struct ipv6_mreq *)i1;
9764 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
9765 				ifindex = ip_mreqp->ipv6mr_interface;
9766 			}
9767 			/*
9768 			 * In the multirouting case, we need to replicate
9769 			 * the request on all interfaces that will take part
9770 			 * in replication.  We do so because multirouting is
9771 			 * reflective, thus we will probably receive multi-
9772 			 * casts on those interfaces.
9773 			 * The ip_multirt_apply_membership_v6() succeeds if
9774 			 * the operation succeeds on at least one interface.
9775 			 */
9776 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
9777 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
9778 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
9779 			if (ire != NULL) {
9780 				if (ire->ire_flags & RTF_MULTIRT) {
9781 					error = ip_multirt_apply_membership_v6(
9782 					    optfn, ire, connp, checkonly,
9783 					    &groupv6, fmode, &ipv6_all_zeros,
9784 					    first_mp);
9785 					done = B_TRUE;
9786 				}
9787 				ire_refrele(ire);
9788 			}
9789 			if (!done) {
9790 				error = optfn(connp, checkonly, &groupv6,
9791 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
9792 			}
9793 			if (error) {
9794 				/*
9795 				 * EINPROGRESS is a soft error, needs retry
9796 				 * so don't make *outlenp zero.
9797 				 */
9798 				if (error != EINPROGRESS)
9799 					*outlenp = 0;
9800 				return (error);
9801 			}
9802 			/* OK return - copy input buffer into output buffer */
9803 			if (invalp != outvalp) {
9804 				/* don't trust bcopy for identical src/dst */
9805 				bcopy(invalp, outvalp, inlen);
9806 			}
9807 			*outlenp = inlen;
9808 			return (0);
9809 		}
9810 		case MCAST_BLOCK_SOURCE:
9811 		case MCAST_UNBLOCK_SOURCE:
9812 		case MCAST_JOIN_SOURCE_GROUP:
9813 		case MCAST_LEAVE_SOURCE_GROUP: {
9814 			struct group_source_req *gsreqp;
9815 			in6_addr_t v6grp, v6src;
9816 			uint32_t ifindex;
9817 			mcast_record_t fmode;
9818 			ire_t *ire;
9819 			boolean_t done = B_FALSE;
9820 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
9821 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
9822 
9823 			switch (name) {
9824 			case MCAST_BLOCK_SOURCE:
9825 				fmode = MODE_IS_EXCLUDE;
9826 				optfn = ip_opt_add_group_v6;
9827 				break;
9828 			case MCAST_UNBLOCK_SOURCE:
9829 				fmode = MODE_IS_EXCLUDE;
9830 				optfn = ip_opt_delete_group_v6;
9831 				break;
9832 			case MCAST_JOIN_SOURCE_GROUP:
9833 				fmode = MODE_IS_INCLUDE;
9834 				optfn = ip_opt_add_group_v6;
9835 				break;
9836 			case MCAST_LEAVE_SOURCE_GROUP:
9837 				fmode = MODE_IS_INCLUDE;
9838 				optfn = ip_opt_delete_group_v6;
9839 				break;
9840 			}
9841 
9842 			gsreqp = (struct group_source_req *)i1;
9843 			ifindex = gsreqp->gsr_interface;
9844 			if (gsreqp->gsr_group.ss_family == AF_INET) {
9845 				struct sockaddr_in *s;
9846 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
9847 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
9848 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
9849 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
9850 			} else {
9851 				struct sockaddr_in6 *s6;
9852 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
9853 				v6grp = s6->sin6_addr;
9854 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
9855 				v6src = s6->sin6_addr;
9856 			}
9857 
9858 			/*
9859 			 * In the multirouting case, we need to replicate
9860 			 * the request as noted in the mcast cases above.
9861 			 */
9862 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
9863 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
9864 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
9865 			if (ire != NULL) {
9866 				if (ire->ire_flags & RTF_MULTIRT) {
9867 					error = ip_multirt_apply_membership_v6(
9868 					    optfn, ire, connp, checkonly,
9869 					    &v6grp, fmode, &v6src, first_mp);
9870 					done = B_TRUE;
9871 				}
9872 				ire_refrele(ire);
9873 			}
9874 			if (!done) {
9875 				error = optfn(connp, checkonly, &v6grp,
9876 				    ifindex, fmode, &v6src, first_mp);
9877 			}
9878 			if (error != 0) {
9879 				/*
9880 				 * EINPROGRESS is a soft error, needs retry
9881 				 * so don't make *outlenp zero.
9882 				 */
9883 				if (error != EINPROGRESS)
9884 					*outlenp = 0;
9885 				return (error);
9886 			}
9887 			/* OK return - copy input buffer into output buffer */
9888 			if (invalp != outvalp) {
9889 				bcopy(invalp, outvalp, inlen);
9890 			}
9891 			*outlenp = inlen;
9892 			return (0);
9893 		}
9894 		case IPV6_UNICAST_HOPS:
9895 			/* Recorded in transport above IP */
9896 			break;	/* goto sizeof (int) option return */
9897 		case IPV6_UNSPEC_SRC:
9898 			/* Allow sending with a zero source address */
9899 			if (!checkonly) {
9900 				mutex_enter(&connp->conn_lock);
9901 				connp->conn_unspec_src = *i1 ? 1 : 0;
9902 				mutex_exit(&connp->conn_lock);
9903 			}
9904 			break;	/* goto sizeof (int) option return */
9905 		case IPV6_RECVPKTINFO:
9906 			if (!checkonly) {
9907 				mutex_enter(&connp->conn_lock);
9908 				connp->conn_ipv6_recvpktinfo = *i1 ? 1 : 0;
9909 				mutex_exit(&connp->conn_lock);
9910 			}
9911 			break;	/* goto sizeof (int) option return */
9912 		case IPV6_RECVTCLASS:
9913 			if (!checkonly) {
9914 				if (*i1 < 0 || *i1 > 1) {
9915 					return (EINVAL);
9916 				}
9917 				mutex_enter(&connp->conn_lock);
9918 				connp->conn_ipv6_recvtclass = *i1;
9919 				mutex_exit(&connp->conn_lock);
9920 			}
9921 			break;
9922 		case IPV6_RECVPATHMTU:
9923 			if (!checkonly) {
9924 				if (*i1 < 0 || *i1 > 1) {
9925 					return (EINVAL);
9926 				}
9927 				mutex_enter(&connp->conn_lock);
9928 				connp->conn_ipv6_recvpathmtu = *i1;
9929 				mutex_exit(&connp->conn_lock);
9930 			}
9931 			break;
9932 		case IPV6_RECVHOPLIMIT:
9933 			if (!checkonly) {
9934 				mutex_enter(&connp->conn_lock);
9935 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
9936 				mutex_exit(&connp->conn_lock);
9937 			}
9938 			break;	/* goto sizeof (int) option return */
9939 		case IPV6_RECVHOPOPTS:
9940 			if (!checkonly) {
9941 				mutex_enter(&connp->conn_lock);
9942 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
9943 				mutex_exit(&connp->conn_lock);
9944 			}
9945 			break;	/* goto sizeof (int) option return */
9946 		case IPV6_RECVDSTOPTS:
9947 			if (!checkonly) {
9948 				mutex_enter(&connp->conn_lock);
9949 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
9950 				mutex_exit(&connp->conn_lock);
9951 			}
9952 			break;	/* goto sizeof (int) option return */
9953 		case IPV6_RECVRTHDR:
9954 			if (!checkonly) {
9955 				mutex_enter(&connp->conn_lock);
9956 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
9957 				mutex_exit(&connp->conn_lock);
9958 			}
9959 			break;	/* goto sizeof (int) option return */
9960 		case IPV6_RECVRTHDRDSTOPTS:
9961 			if (!checkonly) {
9962 				mutex_enter(&connp->conn_lock);
9963 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
9964 				mutex_exit(&connp->conn_lock);
9965 			}
9966 			break;	/* goto sizeof (int) option return */
9967 		case IPV6_PKTINFO:
9968 			if (inlen == 0)
9969 				return (-EINVAL);	/* clearing option */
9970 			error = ip6_set_pktinfo(cr, connp,
9971 			    (struct in6_pktinfo *)invalp, first_mp);
9972 			if (error != 0)
9973 				*outlenp = 0;
9974 			else
9975 				*outlenp = inlen;
9976 			return (error);
9977 		case IPV6_NEXTHOP: {
9978 			struct sockaddr_in6 *sin6;
9979 
9980 			/* Verify that the nexthop is reachable */
9981 			if (inlen == 0)
9982 				return (-EINVAL);	/* clearing option */
9983 
9984 			sin6 = (struct sockaddr_in6 *)invalp;
9985 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
9986 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
9987 			    MATCH_IRE_DEFAULT);
9988 
9989 			if (ire == NULL) {
9990 				*outlenp = 0;
9991 				return (EHOSTUNREACH);
9992 			}
9993 			ire_refrele(ire);
9994 			return (-EINVAL);
9995 		}
9996 		case IPV6_SEC_OPT:
9997 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
9998 			if (error != 0) {
9999 				*outlenp = 0;
10000 				return (error);
10001 			}
10002 			break;
10003 		case IPV6_SRC_PREFERENCES: {
10004 			/*
10005 			 * This is implemented strictly in the ip module
10006 			 * (here and in tcp_opt_*() to accomodate tcp
10007 			 * sockets).  Modules above ip pass this option
10008 			 * down here since ip is the only one that needs to
10009 			 * be aware of source address preferences.
10010 			 *
10011 			 * This socket option only affects connected
10012 			 * sockets that haven't already bound to a specific
10013 			 * IPv6 address.  In other words, sockets that
10014 			 * don't call bind() with an address other than the
10015 			 * unspecified address and that call connect().
10016 			 * ip_bind_connected_v6() passes these preferences
10017 			 * to the ipif_select_source_v6() function.
10018 			 */
10019 			if (inlen != sizeof (uint32_t))
10020 				return (EINVAL);
10021 			error = ip6_set_src_preferences(connp,
10022 			    *(uint32_t *)invalp);
10023 			if (error != 0) {
10024 				*outlenp = 0;
10025 				return (error);
10026 			} else {
10027 				*outlenp = sizeof (uint32_t);
10028 			}
10029 			break;
10030 		}
10031 		case IPV6_V6ONLY:
10032 			if (*i1 < 0 || *i1 > 1) {
10033 				return (EINVAL);
10034 			}
10035 			mutex_enter(&connp->conn_lock);
10036 			connp->conn_ipv6_v6only = *i1;
10037 			mutex_exit(&connp->conn_lock);
10038 			break;
10039 		default:
10040 			return (-EINVAL);
10041 		}
10042 		break;
10043 	default:
10044 		/*
10045 		 * "soft" error (negative)
10046 		 * option not handled at this level
10047 		 * Note: Do not modify *outlenp
10048 		 */
10049 		return (-EINVAL);
10050 	}
10051 	/*
10052 	 * Common case of return from an option that is sizeof (int)
10053 	 */
10054 	*(int *)outvalp = *i1;
10055 	*outlenp = sizeof (int);
10056 	return (0);
10057 }
10058 
10059 /*
10060  * This routine gets default values of certain options whose default
10061  * values are maintained by protocol specific code
10062  */
10063 /* ARGSUSED */
10064 int
10065 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
10066 {
10067 	int *i1 = (int *)ptr;
10068 
10069 	switch (level) {
10070 	case IPPROTO_IP:
10071 		switch (name) {
10072 		case IP_MULTICAST_TTL:
10073 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
10074 			return (sizeof (uchar_t));
10075 		case IP_MULTICAST_LOOP:
10076 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
10077 			return (sizeof (uchar_t));
10078 		default:
10079 			return (-1);
10080 		}
10081 	case IPPROTO_IPV6:
10082 		switch (name) {
10083 		case IPV6_UNICAST_HOPS:
10084 			*i1 = ipv6_def_hops;
10085 			return (sizeof (int));
10086 		case IPV6_MULTICAST_HOPS:
10087 			*i1 = IP_DEFAULT_MULTICAST_TTL;
10088 			return (sizeof (int));
10089 		case IPV6_MULTICAST_LOOP:
10090 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
10091 			return (sizeof (int));
10092 		case IPV6_V6ONLY:
10093 			*i1 = 1;
10094 			return (sizeof (int));
10095 		default:
10096 			return (-1);
10097 		}
10098 	default:
10099 		return (-1);
10100 	}
10101 	/* NOTREACHED */
10102 }
10103 
10104 /*
10105  * Given a destination address and a pointer to where to put the information
10106  * this routine fills in the mtuinfo.
10107  */
10108 int
10109 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
10110     struct ip6_mtuinfo *mtuinfo)
10111 {
10112 	ire_t *ire;
10113 
10114 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
10115 		return (-1);
10116 
10117 	bzero(mtuinfo, sizeof (*mtuinfo));
10118 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
10119 	mtuinfo->ip6m_addr.sin6_port = port;
10120 	mtuinfo->ip6m_addr.sin6_addr = *in6;
10121 
10122 	ire = ire_cache_lookup_v6(in6, ALL_ZONES);
10123 	if (ire != NULL) {
10124 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
10125 		ire_refrele(ire);
10126 	} else {
10127 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
10128 	}
10129 	return (sizeof (struct ip6_mtuinfo));
10130 }
10131 
10132 /*
10133  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
10134  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
10135  * isn't.  This doesn't matter as the error checking is done properly for the
10136  * other MRT options coming in through ip_opt_set.
10137  */
10138 int
10139 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
10140 {
10141 	conn_t		*connp = Q_TO_CONN(q);
10142 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
10143 
10144 	switch (level) {
10145 	case IPPROTO_IP:
10146 		switch (name) {
10147 		case MRT_VERSION:
10148 		case MRT_ASSERT:
10149 			(void) ip_mrouter_get(name, q, ptr);
10150 			return (sizeof (int));
10151 		case IP_SEC_OPT:
10152 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
10153 		default:
10154 			break;
10155 		}
10156 		break;
10157 	case IPPROTO_IPV6:
10158 		switch (name) {
10159 		case IPV6_SEC_OPT:
10160 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
10161 		case IPV6_SRC_PREFERENCES: {
10162 			return (ip6_get_src_preferences(connp,
10163 			    (uint32_t *)ptr));
10164 		}
10165 		case IPV6_V6ONLY:
10166 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
10167 			return (sizeof (int));
10168 		case IPV6_PATHMTU:
10169 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
10170 				(struct ip6_mtuinfo *)ptr));
10171 		default:
10172 			break;
10173 		}
10174 		break;
10175 	default:
10176 		break;
10177 	}
10178 	return (-1);
10179 }
10180 
10181 /* Named Dispatch routine to get a current value out of our parameter table. */
10182 /* ARGSUSED */
10183 static int
10184 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
10185 {
10186 	ipparam_t *ippa = (ipparam_t *)cp;
10187 
10188 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
10189 	return (0);
10190 }
10191 
10192 /* ARGSUSED */
10193 static int
10194 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
10195 {
10196 
10197 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
10198 	return (0);
10199 }
10200 
10201 /*
10202  * Set ip{,6}_forwarding values.  This means walking through all of the
10203  * ill's and toggling their forwarding values.
10204  */
10205 /* ARGSUSED */
10206 static int
10207 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
10208 {
10209 	long new_value;
10210 	int *forwarding_value = (int *)cp;
10211 	ill_t *walker;
10212 	boolean_t isv6 = (forwarding_value == &ipv6_forward);
10213 	ill_walk_context_t ctx;
10214 
10215 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10216 	    new_value < 0 || new_value > 1) {
10217 		return (EINVAL);
10218 	}
10219 
10220 	*forwarding_value = new_value;
10221 
10222 	/*
10223 	 * Regardless of the current value of ip_forwarding, set all per-ill
10224 	 * values of ip_forwarding to the value being set.
10225 	 *
10226 	 * Bring all the ill's up to date with the new global value.
10227 	 */
10228 	rw_enter(&ill_g_lock, RW_READER);
10229 
10230 	if (isv6)
10231 		walker = ILL_START_WALK_V6(&ctx);
10232 	else
10233 		walker = ILL_START_WALK_V4(&ctx);
10234 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
10235 		(void) ill_forward_set(q, mp, (new_value != 0),
10236 		    (caddr_t)walker);
10237 	}
10238 	rw_exit(&ill_g_lock);
10239 
10240 	return (0);
10241 }
10242 
10243 /*
10244  * Walk through the param array specified registering each element with the
10245  * Named Dispatch handler. This is called only during init. So it is ok
10246  * not to acquire any locks
10247  */
10248 static boolean_t
10249 ip_param_register(ipparam_t *ippa, size_t ippa_cnt,
10250     ipndp_t *ipnd, size_t ipnd_cnt)
10251 {
10252 	for (; ippa_cnt-- > 0; ippa++) {
10253 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
10254 			if (!nd_load(&ip_g_nd, ippa->ip_param_name,
10255 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
10256 				nd_free(&ip_g_nd);
10257 				return (B_FALSE);
10258 			}
10259 		}
10260 	}
10261 
10262 	for (; ipnd_cnt-- > 0; ipnd++) {
10263 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
10264 			if (!nd_load(&ip_g_nd, ipnd->ip_ndp_name,
10265 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
10266 			    ipnd->ip_ndp_data)) {
10267 				nd_free(&ip_g_nd);
10268 				return (B_FALSE);
10269 			}
10270 		}
10271 	}
10272 
10273 	return (B_TRUE);
10274 }
10275 
10276 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
10277 /* ARGSUSED */
10278 static int
10279 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
10280 {
10281 	long		new_value;
10282 	ipparam_t	*ippa = (ipparam_t *)cp;
10283 
10284 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10285 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
10286 		return (EINVAL);
10287 	}
10288 	ippa->ip_param_value = new_value;
10289 	return (0);
10290 }
10291 
10292 /*
10293  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
10294  * When an ipf is passed here for the first time, if
10295  * we already have in-order fragments on the queue, we convert from the fast-
10296  * path reassembly scheme to the hard-case scheme.  From then on, additional
10297  * fragments are reassembled here.  We keep track of the start and end offsets
10298  * of each piece, and the number of holes in the chain.  When the hole count
10299  * goes to zero, we are done!
10300  *
10301  * The ipf_count will be updated to account for any mblk(s) added (pointed to
10302  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
10303  * ipfb_count and ill_frag_count by the difference of ipf_count before and
10304  * after the call to ip_reassemble().
10305  */
10306 int
10307 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
10308     size_t msg_len)
10309 {
10310 	uint_t	end;
10311 	mblk_t	*next_mp;
10312 	mblk_t	*mp1;
10313 	uint_t	offset;
10314 	boolean_t incr_dups = B_TRUE;
10315 	boolean_t offset_zero_seen = B_FALSE;
10316 	boolean_t pkt_boundary_checked = B_FALSE;
10317 
10318 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
10319 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
10320 
10321 	/* Add in byte count */
10322 	ipf->ipf_count += msg_len;
10323 	if (ipf->ipf_end) {
10324 		/*
10325 		 * We were part way through in-order reassembly, but now there
10326 		 * is a hole.  We walk through messages already queued, and
10327 		 * mark them for hard case reassembly.  We know that up till
10328 		 * now they were in order starting from offset zero.
10329 		 */
10330 		offset = 0;
10331 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
10332 			IP_REASS_SET_START(mp1, offset);
10333 			if (offset == 0) {
10334 				ASSERT(ipf->ipf_nf_hdr_len != 0);
10335 				offset = -ipf->ipf_nf_hdr_len;
10336 			}
10337 			offset += mp1->b_wptr - mp1->b_rptr;
10338 			IP_REASS_SET_END(mp1, offset);
10339 		}
10340 		/* One hole at the end. */
10341 		ipf->ipf_hole_cnt = 1;
10342 		/* Brand it as a hard case, forever. */
10343 		ipf->ipf_end = 0;
10344 	}
10345 	/* Walk through all the new pieces. */
10346 	do {
10347 		end = start + (mp->b_wptr - mp->b_rptr);
10348 		/*
10349 		 * If start is 0, decrease 'end' only for the first mblk of
10350 		 * the fragment. Otherwise 'end' can get wrong value in the
10351 		 * second pass of the loop if first mblk is exactly the
10352 		 * size of ipf_nf_hdr_len.
10353 		 */
10354 		if (start == 0 && !offset_zero_seen) {
10355 			/* First segment */
10356 			ASSERT(ipf->ipf_nf_hdr_len != 0);
10357 			end -= ipf->ipf_nf_hdr_len;
10358 			offset_zero_seen = B_TRUE;
10359 		}
10360 		next_mp = mp->b_cont;
10361 		/*
10362 		 * We are checking to see if there is any interesing data
10363 		 * to process.  If there isn't and the mblk isn't the
10364 		 * one which carries the unfragmentable header then we
10365 		 * drop it.  It's possible to have just the unfragmentable
10366 		 * header come through without any data.  That needs to be
10367 		 * saved.
10368 		 *
10369 		 * If the assert at the top of this function holds then the
10370 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
10371 		 * is infrequently traveled enough that the test is left in
10372 		 * to protect against future code changes which break that
10373 		 * invariant.
10374 		 */
10375 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
10376 			/* Empty.  Blast it. */
10377 			IP_REASS_SET_START(mp, 0);
10378 			IP_REASS_SET_END(mp, 0);
10379 			/*
10380 			 * If the ipf points to the mblk we are about to free,
10381 			 * update ipf to point to the next mblk (or NULL
10382 			 * if none).
10383 			 */
10384 			if (ipf->ipf_mp->b_cont == mp)
10385 				ipf->ipf_mp->b_cont = next_mp;
10386 			freeb(mp);
10387 			continue;
10388 		}
10389 		mp->b_cont = NULL;
10390 		IP_REASS_SET_START(mp, start);
10391 		IP_REASS_SET_END(mp, end);
10392 		if (!ipf->ipf_tail_mp) {
10393 			ipf->ipf_tail_mp = mp;
10394 			ipf->ipf_mp->b_cont = mp;
10395 			if (start == 0 || !more) {
10396 				ipf->ipf_hole_cnt = 1;
10397 				/*
10398 				 * if the first fragment comes in more than one
10399 				 * mblk, this loop will be executed for each
10400 				 * mblk. Need to adjust hole count so exiting
10401 				 * this routine will leave hole count at 1.
10402 				 */
10403 				if (next_mp)
10404 					ipf->ipf_hole_cnt++;
10405 			} else
10406 				ipf->ipf_hole_cnt = 2;
10407 			continue;
10408 		} else if (ipf->ipf_last_frag_seen && !more &&
10409 			    !pkt_boundary_checked) {
10410 			/*
10411 			 * We check datagram boundary only if this fragment
10412 			 * claims to be the last fragment and we have seen a
10413 			 * last fragment in the past too. We do this only
10414 			 * once for a given fragment.
10415 			 *
10416 			 * start cannot be 0 here as fragments with start=0
10417 			 * and MF=0 gets handled as a complete packet. These
10418 			 * fragments should not reach here.
10419 			 */
10420 
10421 			if (start + msgdsize(mp) !=
10422 			    IP_REASS_END(ipf->ipf_tail_mp)) {
10423 				/*
10424 				 * We have two fragments both of which claim
10425 				 * to be the last fragment but gives conflicting
10426 				 * information about the whole datagram size.
10427 				 * Something fishy is going on. Drop the
10428 				 * fragment and free up the reassembly list.
10429 				 */
10430 				return (IP_REASS_FAILED);
10431 			}
10432 
10433 			/*
10434 			 * We shouldn't come to this code block again for this
10435 			 * particular fragment.
10436 			 */
10437 			pkt_boundary_checked = B_TRUE;
10438 		}
10439 
10440 		/* New stuff at or beyond tail? */
10441 		offset = IP_REASS_END(ipf->ipf_tail_mp);
10442 		if (start >= offset) {
10443 			if (ipf->ipf_last_frag_seen) {
10444 				/* current fragment is beyond last fragment */
10445 				return (IP_REASS_FAILED);
10446 			}
10447 			/* Link it on end. */
10448 			ipf->ipf_tail_mp->b_cont = mp;
10449 			ipf->ipf_tail_mp = mp;
10450 			if (more) {
10451 				if (start != offset)
10452 					ipf->ipf_hole_cnt++;
10453 			} else if (start == offset && next_mp == NULL)
10454 					ipf->ipf_hole_cnt--;
10455 			continue;
10456 		}
10457 		mp1 = ipf->ipf_mp->b_cont;
10458 		offset = IP_REASS_START(mp1);
10459 		/* New stuff at the front? */
10460 		if (start < offset) {
10461 			if (start == 0) {
10462 				if (end >= offset) {
10463 					/* Nailed the hole at the begining. */
10464 					ipf->ipf_hole_cnt--;
10465 				}
10466 			} else if (end < offset) {
10467 				/*
10468 				 * A hole, stuff, and a hole where there used
10469 				 * to be just a hole.
10470 				 */
10471 				ipf->ipf_hole_cnt++;
10472 			}
10473 			mp->b_cont = mp1;
10474 			/* Check for overlap. */
10475 			while (end > offset) {
10476 				if (end < IP_REASS_END(mp1)) {
10477 					mp->b_wptr -= end - offset;
10478 					IP_REASS_SET_END(mp, offset);
10479 					if (ill->ill_isv6) {
10480 						BUMP_MIB(ill->ill_ip6_mib,
10481 						    ipv6ReasmPartDups);
10482 					} else {
10483 						BUMP_MIB(&ip_mib,
10484 						    ipReasmPartDups);
10485 					}
10486 					break;
10487 				}
10488 				/* Did we cover another hole? */
10489 				if ((mp1->b_cont &&
10490 				    IP_REASS_END(mp1) !=
10491 				    IP_REASS_START(mp1->b_cont) &&
10492 				    end >= IP_REASS_START(mp1->b_cont)) ||
10493 				    (!ipf->ipf_last_frag_seen && !more)) {
10494 					ipf->ipf_hole_cnt--;
10495 				}
10496 				/* Clip out mp1. */
10497 				if ((mp->b_cont = mp1->b_cont) == NULL) {
10498 					/*
10499 					 * After clipping out mp1, this guy
10500 					 * is now hanging off the end.
10501 					 */
10502 					ipf->ipf_tail_mp = mp;
10503 				}
10504 				IP_REASS_SET_START(mp1, 0);
10505 				IP_REASS_SET_END(mp1, 0);
10506 				/* Subtract byte count */
10507 				ipf->ipf_count -= mp1->b_datap->db_lim -
10508 				    mp1->b_datap->db_base;
10509 				freeb(mp1);
10510 				if (ill->ill_isv6) {
10511 					BUMP_MIB(ill->ill_ip6_mib,
10512 					    ipv6ReasmPartDups);
10513 				} else {
10514 					BUMP_MIB(&ip_mib, ipReasmPartDups);
10515 				}
10516 				mp1 = mp->b_cont;
10517 				if (!mp1)
10518 					break;
10519 				offset = IP_REASS_START(mp1);
10520 			}
10521 			ipf->ipf_mp->b_cont = mp;
10522 			continue;
10523 		}
10524 		/*
10525 		 * The new piece starts somewhere between the start of the head
10526 		 * and before the end of the tail.
10527 		 */
10528 		for (; mp1; mp1 = mp1->b_cont) {
10529 			offset = IP_REASS_END(mp1);
10530 			if (start < offset) {
10531 				if (end <= offset) {
10532 					/* Nothing new. */
10533 					IP_REASS_SET_START(mp, 0);
10534 					IP_REASS_SET_END(mp, 0);
10535 					/* Subtract byte count */
10536 					ipf->ipf_count -= mp->b_datap->db_lim -
10537 					    mp->b_datap->db_base;
10538 					if (incr_dups) {
10539 						ipf->ipf_num_dups++;
10540 						incr_dups = B_FALSE;
10541 					}
10542 					freeb(mp);
10543 					if (ill->ill_isv6) {
10544 						BUMP_MIB(ill->ill_ip6_mib,
10545 						    ipv6ReasmDuplicates);
10546 					} else {
10547 						BUMP_MIB(&ip_mib,
10548 						    ipReasmDuplicates);
10549 					}
10550 					break;
10551 				}
10552 				/*
10553 				 * Trim redundant stuff off beginning of new
10554 				 * piece.
10555 				 */
10556 				IP_REASS_SET_START(mp, offset);
10557 				mp->b_rptr += offset - start;
10558 				if (ill->ill_isv6) {
10559 					BUMP_MIB(ill->ill_ip6_mib,
10560 					    ipv6ReasmPartDups);
10561 				} else {
10562 					BUMP_MIB(&ip_mib, ipReasmPartDups);
10563 				}
10564 				start = offset;
10565 				if (!mp1->b_cont) {
10566 					/*
10567 					 * After trimming, this guy is now
10568 					 * hanging off the end.
10569 					 */
10570 					mp1->b_cont = mp;
10571 					ipf->ipf_tail_mp = mp;
10572 					if (!more) {
10573 						ipf->ipf_hole_cnt--;
10574 					}
10575 					break;
10576 				}
10577 			}
10578 			if (start >= IP_REASS_START(mp1->b_cont))
10579 				continue;
10580 			/* Fill a hole */
10581 			if (start > offset)
10582 				ipf->ipf_hole_cnt++;
10583 			mp->b_cont = mp1->b_cont;
10584 			mp1->b_cont = mp;
10585 			mp1 = mp->b_cont;
10586 			offset = IP_REASS_START(mp1);
10587 			if (end >= offset) {
10588 				ipf->ipf_hole_cnt--;
10589 				/* Check for overlap. */
10590 				while (end > offset) {
10591 					if (end < IP_REASS_END(mp1)) {
10592 						mp->b_wptr -= end - offset;
10593 						IP_REASS_SET_END(mp, offset);
10594 						/*
10595 						 * TODO we might bump
10596 						 * this up twice if there is
10597 						 * overlap at both ends.
10598 						 */
10599 						if (ill->ill_isv6) {
10600 							BUMP_MIB(
10601 							    ill->ill_ip6_mib,
10602 							    ipv6ReasmPartDups);
10603 						} else {
10604 							BUMP_MIB(&ip_mib,
10605 							    ipReasmPartDups);
10606 						}
10607 						break;
10608 					}
10609 					/* Did we cover another hole? */
10610 					if ((mp1->b_cont &&
10611 					    IP_REASS_END(mp1)
10612 					    != IP_REASS_START(mp1->b_cont) &&
10613 					    end >=
10614 					    IP_REASS_START(mp1->b_cont)) ||
10615 					    (!ipf->ipf_last_frag_seen &&
10616 					    !more)) {
10617 						ipf->ipf_hole_cnt--;
10618 					}
10619 					/* Clip out mp1. */
10620 					if ((mp->b_cont = mp1->b_cont) ==
10621 					    NULL) {
10622 						/*
10623 						 * After clipping out mp1,
10624 						 * this guy is now hanging
10625 						 * off the end.
10626 						 */
10627 						ipf->ipf_tail_mp = mp;
10628 					}
10629 					IP_REASS_SET_START(mp1, 0);
10630 					IP_REASS_SET_END(mp1, 0);
10631 					/* Subtract byte count */
10632 					ipf->ipf_count -=
10633 					    mp1->b_datap->db_lim -
10634 					    mp1->b_datap->db_base;
10635 					freeb(mp1);
10636 					if (ill->ill_isv6) {
10637 						BUMP_MIB(ill->ill_ip6_mib,
10638 						    ipv6ReasmPartDups);
10639 					} else {
10640 						BUMP_MIB(&ip_mib,
10641 						    ipReasmPartDups);
10642 					}
10643 					mp1 = mp->b_cont;
10644 					if (!mp1)
10645 						break;
10646 					offset = IP_REASS_START(mp1);
10647 				}
10648 			}
10649 			break;
10650 		}
10651 	} while (start = end, mp = next_mp);
10652 
10653 	/* Fragment just processed could be the last one. Remember this fact */
10654 	if (!more)
10655 		ipf->ipf_last_frag_seen = B_TRUE;
10656 
10657 	/* Still got holes? */
10658 	if (ipf->ipf_hole_cnt)
10659 		return (IP_REASS_PARTIAL);
10660 	/* Clean up overloaded fields to avoid upstream disasters. */
10661 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
10662 		IP_REASS_SET_START(mp1, 0);
10663 		IP_REASS_SET_END(mp1, 0);
10664 	}
10665 	return (IP_REASS_COMPLETE);
10666 }
10667 
10668 /*
10669  * ipsec processing for the fast path, used for input UDP Packets
10670  */
10671 static boolean_t
10672 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
10673     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
10674 {
10675 	uint32_t	ill_index;
10676 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
10677 
10678 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
10679 	/* The ill_index of the incoming ILL */
10680 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
10681 
10682 	/* pass packet up to the transport */
10683 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
10684 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
10685 		    NULL, mctl_present);
10686 		if (*first_mpp == NULL) {
10687 			return (B_FALSE);
10688 		}
10689 	}
10690 
10691 	/* Initiate IPPF processing for fastpath UDP */
10692 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
10693 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
10694 		if (*mpp == NULL) {
10695 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
10696 			    "deferred/dropped during IPPF processing\n"));
10697 			return (B_FALSE);
10698 		}
10699 	}
10700 	/*
10701 	 * We make the checks as below since we are in the fast path
10702 	 * and want to minimize the number of checks if the IP_RECVIF and/or
10703 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
10704 	 */
10705 	if (connp->conn_recvif || connp->conn_recvslla ||
10706 	    connp->conn_ipv6_recvpktinfo) {
10707 		if (connp->conn_recvif ||
10708 		    connp->conn_ipv6_recvpktinfo) {
10709 			in_flags = IPF_RECVIF;
10710 		}
10711 		if (connp->conn_recvslla) {
10712 			in_flags |= IPF_RECVSLLA;
10713 		}
10714 		/*
10715 		 * since in_flags are being set ill will be
10716 		 * referenced in ip_add_info, so it better not
10717 		 * be NULL.
10718 		 */
10719 		/*
10720 		 * the actual data will be contained in b_cont
10721 		 * upon successful return of the following call.
10722 		 * If the call fails then the original mblk is
10723 		 * returned.
10724 		 */
10725 		*mpp = ip_add_info(*mpp, ill, in_flags);
10726 	}
10727 
10728 	return (B_TRUE);
10729 }
10730 
10731 /*
10732  * Do fragmentation reassembly.
10733  * returns B_TRUE if successful else B_FALSE.
10734  * frees mp on failure.
10735  */
10736 static boolean_t
10737 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha)
10738 {
10739 	uint32_t	frag_offset_flags;
10740 	ill_t   *ill = (ill_t *)q->q_ptr;
10741 	mblk_t *mp = *mpp;
10742 	mblk_t *t_mp;
10743 	ipaddr_t	dst;
10744 
10745 	/*
10746 	 * Drop the fragmented as early as possible, if
10747 	 * we don't have resource(s) to re-assemble.
10748 	 */
10749 
10750 	if (ip_reass_queue_bytes == 0) {
10751 		freemsg(mp);
10752 		return (B_FALSE);
10753 	}
10754 
10755 	dst = ipha->ipha_dst;
10756 
10757 	/* Clear hardware checksumming flag if set */
10758 	mp->b_datap->db_struioun.cksum.flags = 0;
10759 
10760 	/* Check for fragmentation offset. */
10761 	frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
10762 	    (IPH_MF | IPH_OFFSET);
10763 	if (frag_offset_flags) {
10764 		ipf_t		*ipf;
10765 		ipf_t		**ipfp;
10766 		ipfb_t		*ipfb;
10767 		uint16_t	ident;
10768 		uint32_t	offset;
10769 		ipaddr_t	src;
10770 		uint_t		hdr_length;
10771 		uint32_t	end;
10772 		uint8_t		proto;
10773 		mblk_t		*mp1;
10774 		mblk_t		*tail_mp;
10775 		size_t		count;
10776 		size_t		msg_len;
10777 		uint8_t		ecn_info = 0;
10778 		uint32_t	packet_size;
10779 		boolean_t 	pruned = B_FALSE;
10780 
10781 		ident = ipha->ipha_ident;
10782 		offset = (frag_offset_flags << 3) & 0xFFFF;
10783 		src = ipha->ipha_src;
10784 		hdr_length = IPH_HDR_LENGTH(ipha);
10785 		end = ntohs(ipha->ipha_length) - hdr_length;
10786 
10787 		/*
10788 		 * if end == 0 then we have a packet with no data, so just
10789 		 * free it.
10790 		 */
10791 		if (end == 0) {
10792 			freemsg(mp);
10793 			return (B_FALSE);
10794 		}
10795 		proto = ipha->ipha_protocol;
10796 
10797 		/*
10798 		 * Fragmentation reassembly.  Each ILL has a hash table for
10799 		 * queuing packets undergoing reassembly for all IPIFs
10800 		 * associated with the ILL.  The hash is based on the packet
10801 		 * IP ident field.  The ILL frag hash table was allocated
10802 		 * as a timer block at the time the ILL was created.  Whenever
10803 		 * there is anything on the reassembly queue, the timer will
10804 		 * be running.
10805 		 */
10806 		ASSERT(ill != NULL);
10807 
10808 		/* Record the ECN field info. */
10809 		ecn_info = (ipha->ipha_type_of_service & 0x3);
10810 		if (offset != 0) {
10811 			/*
10812 			 * If this isn't the first piece, strip the header, and
10813 			 * add the offset to the end value.
10814 			 */
10815 			mp->b_rptr += hdr_length;
10816 			end += offset;
10817 		}
10818 
10819 		msg_len = mp->b_datap->db_lim - mp->b_datap->db_base;
10820 		tail_mp = mp;
10821 		while (tail_mp->b_cont != NULL) {
10822 			tail_mp = tail_mp->b_cont;
10823 			msg_len += tail_mp->b_datap->db_lim -
10824 			    tail_mp->b_datap->db_base;
10825 		}
10826 
10827 		/*
10828 		 * If the reassembly list for this ILL will get too big
10829 		 * prune it.
10830 		 */
10831 		if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
10832 		    ip_reass_queue_bytes) {
10833 			ill_frag_prune(ill,
10834 			    (ip_reass_queue_bytes < msg_len) ? 0 :
10835 			    (ip_reass_queue_bytes - msg_len));
10836 			pruned = B_TRUE;
10837 		}
10838 
10839 		ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
10840 		mutex_enter(&ipfb->ipfb_lock);
10841 
10842 		ipfp = &ipfb->ipfb_ipf;
10843 		/* Try to find an existing fragment queue for this packet. */
10844 		for (;;) {
10845 			ipf = ipfp[0];
10846 			if (ipf != NULL) {
10847 				/*
10848 				 * It has to match on ident and src/dst address.
10849 				 */
10850 				if (ipf->ipf_ident == ident &&
10851 				    ipf->ipf_src == src &&
10852 				    ipf->ipf_dst == dst &&
10853 				    ipf->ipf_protocol == proto) {
10854 					/*
10855 					 * If we have received too many
10856 					 * duplicate fragments for this packet
10857 					 * free it.
10858 					 */
10859 					if (ipf->ipf_num_dups >
10860 					    ip_max_frag_dups) {
10861 						ill_frag_free_pkts(ill, ipfb,
10862 						    ipf, 1);
10863 						freemsg(mp);
10864 						mutex_exit(&ipfb->ipfb_lock);
10865 						return (B_FALSE);
10866 					}
10867 					/* Found it. */
10868 					break;
10869 				}
10870 				ipfp = &ipf->ipf_hash_next;
10871 				continue;
10872 			}
10873 
10874 			/*
10875 			 * If we pruned the list, do we want to store this new
10876 			 * fragment?. We apply an optimization here based on the
10877 			 * fact that most fragments will be received in order.
10878 			 * So if the offset of this incoming fragment is zero,
10879 			 * it is the first fragment of a new packet. We will
10880 			 * keep it.  Otherwise drop the fragment, as we have
10881 			 * probably pruned the packet already (since the
10882 			 * packet cannot be found).
10883 			 */
10884 			if (pruned && offset != 0) {
10885 				mutex_exit(&ipfb->ipfb_lock);
10886 				freemsg(mp);
10887 				return (B_FALSE);
10888 			}
10889 
10890 			if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS)  {
10891 				/*
10892 				 * Too many fragmented packets in this hash
10893 				 * bucket. Free the oldest.
10894 				 */
10895 				ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf,
10896 				    1);
10897 			}
10898 
10899 			/* New guy.  Allocate a frag message. */
10900 			mp1 = allocb(sizeof (*ipf), BPRI_MED);
10901 			if (mp1 == NULL) {
10902 				BUMP_MIB(&ip_mib, ipInDiscards);
10903 				freemsg(mp);
10904 reass_done:
10905 				mutex_exit(&ipfb->ipfb_lock);
10906 				return (B_FALSE);
10907 			}
10908 
10909 
10910 			BUMP_MIB(&ip_mib, ipReasmReqds);
10911 			mp1->b_cont = mp;
10912 
10913 			/* Initialize the fragment header. */
10914 			ipf = (ipf_t *)mp1->b_rptr;
10915 			ipf->ipf_mp = mp1;
10916 			ipf->ipf_ptphn = ipfp;
10917 			ipfp[0] = ipf;
10918 			ipf->ipf_hash_next = NULL;
10919 			ipf->ipf_ident = ident;
10920 			ipf->ipf_protocol = proto;
10921 			ipf->ipf_src = src;
10922 			ipf->ipf_dst = dst;
10923 			ipf->ipf_nf_hdr_len = 0;
10924 			/* Record reassembly start time. */
10925 			ipf->ipf_timestamp = gethrestime_sec();
10926 			/* Record ipf generation and account for frag header */
10927 			ipf->ipf_gen = ill->ill_ipf_gen++;
10928 			ipf->ipf_count = mp1->b_datap->db_lim -
10929 			    mp1->b_datap->db_base;
10930 			ipf->ipf_last_frag_seen = B_FALSE;
10931 			ipf->ipf_ecn = ecn_info;
10932 			ipf->ipf_num_dups = 0;
10933 			ipfb->ipfb_frag_pkts++;
10934 
10935 			/*
10936 			 * We handle reassembly two ways.  In the easy case,
10937 			 * where all the fragments show up in order, we do
10938 			 * minimal bookkeeping, and just clip new pieces on
10939 			 * the end.  If we ever see a hole, then we go off
10940 			 * to ip_reassemble which has to mark the pieces and
10941 			 * keep track of the number of holes, etc.  Obviously,
10942 			 * the point of having both mechanisms is so we can
10943 			 * handle the easy case as efficiently as possible.
10944 			 */
10945 			if (offset == 0) {
10946 				/* Easy case, in-order reassembly so far. */
10947 				ipf->ipf_count += msg_len;
10948 				ipf->ipf_tail_mp = tail_mp;
10949 				/*
10950 				 * Keep track of next expected offset in
10951 				 * ipf_end.
10952 				 */
10953 				ipf->ipf_end = end;
10954 				ipf->ipf_nf_hdr_len = hdr_length;
10955 			} else {
10956 				/* Hard case, hole at the beginning. */
10957 				ipf->ipf_tail_mp = NULL;
10958 				/*
10959 				 * ipf_end == 0 means that we have given up
10960 				 * on easy reassembly.
10961 				 */
10962 				ipf->ipf_end = 0;
10963 				/*
10964 				 * ipf_hole_cnt is set by ip_reassemble.
10965 				 * ipf_count is updated by ip_reassemble.
10966 				 * No need to check for return value here
10967 				 * as we don't expect reassembly to complete
10968 				 * or fail for the first fragment itself.
10969 				 */
10970 				(void) ip_reassemble(mp, ipf,
10971 				    (frag_offset_flags & IPH_OFFSET) << 3,
10972 				    (frag_offset_flags & IPH_MF), ill, msg_len);
10973 			}
10974 			/* Update per ipfb and ill byte counts */
10975 			ipfb->ipfb_count += ipf->ipf_count;
10976 			ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
10977 			ill->ill_frag_count += ipf->ipf_count;
10978 			ASSERT(ill->ill_frag_count > 0); /* Wraparound */
10979 			/* If the frag timer wasn't already going, start it. */
10980 			mutex_enter(&ill->ill_lock);
10981 			ill_frag_timer_start(ill);
10982 			mutex_exit(&ill->ill_lock);
10983 			goto reass_done;
10984 		}
10985 
10986 		/*
10987 		 * We have a new piece of a datagram which is already being
10988 		 * reassembled.  Update the ECN info if all IP fragments
10989 		 * are ECN capable.  If there is one which is not, clear
10990 		 * all the info.  If there is at least one which has CE
10991 		 * code point, IP needs to report that up to transport.
10992 		 */
10993 		if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
10994 			if (ecn_info == IPH_ECN_CE)
10995 				ipf->ipf_ecn = IPH_ECN_CE;
10996 		} else {
10997 			ipf->ipf_ecn = IPH_ECN_NECT;
10998 		}
10999 		if (offset && ipf->ipf_end == offset) {
11000 			/* The new fragment fits at the end */
11001 			ipf->ipf_tail_mp->b_cont = mp;
11002 			/* Update the byte count */
11003 			ipf->ipf_count += msg_len;
11004 			/* Update per ipfb and ill byte counts */
11005 			ipfb->ipfb_count += msg_len;
11006 			ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
11007 			ill->ill_frag_count += msg_len;
11008 			ASSERT(ill->ill_frag_count > 0); /* Wraparound */
11009 			if (frag_offset_flags & IPH_MF) {
11010 				/* More to come. */
11011 				ipf->ipf_end = end;
11012 				ipf->ipf_tail_mp = tail_mp;
11013 				goto reass_done;
11014 			}
11015 		} else {
11016 			/* Go do the hard cases. */
11017 			int ret;
11018 
11019 			if (offset == 0)
11020 				ipf->ipf_nf_hdr_len = hdr_length;
11021 
11022 			/* Save current byte count */
11023 			count = ipf->ipf_count;
11024 			ret = ip_reassemble(mp, ipf,
11025 			    (frag_offset_flags & IPH_OFFSET) << 3,
11026 			    (frag_offset_flags & IPH_MF), ill, msg_len);
11027 			/* Count of bytes added and subtracted (freeb()ed) */
11028 			count = ipf->ipf_count - count;
11029 			if (count) {
11030 				/* Update per ipfb and ill byte counts */
11031 				ipfb->ipfb_count += count;
11032 				ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
11033 				ill->ill_frag_count += count;
11034 				ASSERT(ill->ill_frag_count > 0);
11035 			}
11036 			if (ret == IP_REASS_PARTIAL) {
11037 				goto reass_done;
11038 			} else if (ret == IP_REASS_FAILED) {
11039 				/* Reassembly failed. Free up all resources */
11040 				ill_frag_free_pkts(ill, ipfb, ipf, 1);
11041 				for (t_mp = mp; t_mp != NULL;
11042 				    t_mp = t_mp->b_cont) {
11043 					IP_REASS_SET_START(t_mp, 0);
11044 					IP_REASS_SET_END(t_mp, 0);
11045 				}
11046 				freemsg(mp);
11047 				goto reass_done;
11048 			}
11049 			/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
11050 		}
11051 		/*
11052 		 * We have completed reassembly.  Unhook the frag header from
11053 		 * the reassembly list.
11054 		 *
11055 		 * Before we free the frag header, record the ECN info
11056 		 * to report back to the transport.
11057 		 */
11058 		ecn_info = ipf->ipf_ecn;
11059 		BUMP_MIB(&ip_mib, ipReasmOKs);
11060 		ipfp = ipf->ipf_ptphn;
11061 		mp1 = ipf->ipf_mp;
11062 		count = ipf->ipf_count;
11063 		ipf = ipf->ipf_hash_next;
11064 		if (ipf)
11065 			ipf->ipf_ptphn = ipfp;
11066 		ipfp[0] = ipf;
11067 		ill->ill_frag_count -= count;
11068 		ASSERT(ipfb->ipfb_count >= count);
11069 		ipfb->ipfb_count -= count;
11070 		ipfb->ipfb_frag_pkts--;
11071 		mutex_exit(&ipfb->ipfb_lock);
11072 		/* Ditch the frag header. */
11073 		mp = mp1->b_cont;
11074 
11075 		freeb(mp1);
11076 
11077 		/* Restore original IP length in header. */
11078 		packet_size = (uint32_t)msgdsize(mp);
11079 		if (packet_size > IP_MAXPACKET) {
11080 			freemsg(mp);
11081 			BUMP_MIB(&ip_mib, ipInHdrErrors);
11082 			return (B_FALSE);
11083 		}
11084 
11085 		if (mp->b_datap->db_ref > 1) {
11086 			mblk_t *mp2;
11087 
11088 			mp2 = copymsg(mp);
11089 			freemsg(mp);
11090 			if (!mp2) {
11091 				BUMP_MIB(&ip_mib, ipInDiscards);
11092 				return (B_FALSE);
11093 			}
11094 			mp = mp2;
11095 		}
11096 		ipha = (ipha_t *)mp->b_rptr;
11097 
11098 		ipha->ipha_length = htons((uint16_t)packet_size);
11099 		/* We're now complete, zip the frag state */
11100 		ipha->ipha_fragment_offset_and_flags = 0;
11101 		/* Record the ECN info. */
11102 		ipha->ipha_type_of_service &= 0xFC;
11103 		ipha->ipha_type_of_service |= ecn_info;
11104 		*mpp = mp;
11105 
11106 	}
11107 	return (B_TRUE);
11108 }
11109 
11110 /*
11111  * Perform ip header check sum update local options.
11112  * return B_TRUE if all is well, else return B_FALSE and release
11113  * the mp. caller is responsible for decrementing ire ref cnt.
11114  */
11115 static boolean_t
11116 ip_options_cksum(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
11117 {
11118 	mblk_t		*first_mp;
11119 	boolean_t	mctl_present;
11120 	uint16_t	sum;
11121 
11122 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
11123 	/*
11124 	 * Don't do the checksum if it has gone through AH/ESP
11125 	 * processing.
11126 	 */
11127 	if (!mctl_present) {
11128 		sum = ip_csum_hdr(ipha);
11129 		if (sum != 0) {
11130 			BUMP_MIB(&ip_mib, ipInCksumErrs);
11131 			freemsg(first_mp);
11132 			return (B_FALSE);
11133 		}
11134 	}
11135 
11136 	if (!ip_rput_local_options(q, mp, ipha, ire)) {
11137 		if (mctl_present)
11138 			freeb(first_mp);
11139 		return (B_FALSE);
11140 	}
11141 
11142 	return (B_TRUE);
11143 }
11144 
11145 /*
11146  * All udp packet are delivered to the local host via this routine.
11147  */
11148 void
11149 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
11150     ill_t *recv_ill)
11151 {
11152 	uint32_t	sum;
11153 	uint32_t	u1;
11154 	uint32_t	u2;
11155 	boolean_t	mctl_present;
11156 	conn_t		*connp;
11157 	mblk_t		*first_mp;
11158 	mblk_t		*mp1;
11159 	dblk_t		*dp;
11160 	uint16_t	*up;
11161 	ill_t		*ill = (ill_t *)q->q_ptr;
11162 	uint32_t	ports;
11163 	boolean_t	cksum_computed = B_FALSE;
11164 
11165 #define	rptr    ((uchar_t *)ipha)
11166 
11167 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
11168 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
11169 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11170 
11171 	/*
11172 	 * FAST PATH for udp packets
11173 	 */
11174 
11175 	/* u1 is # words of IP options */
11176 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
11177 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
11178 
11179 	/* IP options present */
11180 	if (u1)
11181 		goto ipoptions;
11182 
11183 #define	IS_IPHDR_HWCKSUM(mctl_present, mp, ill)				\
11184 	((!mctl_present) && (mp->b_datap->db_struioun.cksum.flags &	\
11185 	HCK_IPV4_HDRCKSUM) && (ill->ill_capabilities &			\
11186 	ILL_CAPAB_HCKSUM) && dohwcksum)
11187 
11188 	/* Check the IP header checksum.  */
11189 	if (IS_IPHDR_HWCKSUM(mctl_present, mp, ill)) {
11190 		/* Clear the IP header h/w cksum flag */
11191 		mp->b_datap->db_struioun.cksum.flags &=
11192 		    ~HCK_IPV4_HDRCKSUM;
11193 	} else {
11194 #define	uph	((uint16_t *)ipha)
11195 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
11196 		    uph[6] + uph[7] + uph[8] + uph[9];
11197 #undef	uph
11198 		/* finish doing IP checksum */
11199 		sum = (sum & 0xFFFF) + (sum >> 16);
11200 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
11201 		/*
11202 		 * Don't verify header checksum if this packet is coming
11203 		 * back from AH/ESP as we already did it.
11204 		 */
11205 		if (!mctl_present && (sum && sum != 0xFFFF)) {
11206 			BUMP_MIB(&ip_mib, ipInCksumErrs);
11207 			freemsg(first_mp);
11208 			return;
11209 		}
11210 	}
11211 
11212 	/*
11213 	 * Count for SNMP of inbound packets for ire.
11214 	 * if mctl is present this might be a secure packet and
11215 	 * has already been counted for in ip_proto_input().
11216 	 */
11217 	if (!mctl_present) {
11218 		UPDATE_IB_PKT_COUNT(ire);
11219 		ire->ire_last_used_time = lbolt;
11220 	}
11221 
11222 	/* packet part of fragmented IP packet? */
11223 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11224 	if (u1 & (IPH_MF | IPH_OFFSET)) {
11225 		goto fragmented;
11226 	}
11227 
11228 	/* u1 = IP header length (20 bytes) */
11229 	u1 = IP_SIMPLE_HDR_LENGTH;
11230 
11231 	/* packet does not contain complete IP & UDP headers */
11232 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
11233 		goto udppullup;
11234 	/* up points to UDP header */
11235 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
11236 #define	iphs    ((uint16_t *)ipha)
11237 
11238 #define	IP_CKSUM_RECV(len, u1, u2, mp, mp1, error, dp) {		\
11239 	boolean_t	doswcksum = B_TRUE;				\
11240 	uint_t		hcksumflags = 0;				\
11241 									\
11242 	hcksumflags = dp->db_struioun.cksum.flags;			\
11243 									\
11244 	/* Clear the hardware checksum flags; they have been consumed */\
11245 	dp->db_struioun.cksum.flags = 0;				\
11246 	if (hcksumflags && (ill->ill_capabilities & ILL_CAPAB_HCKSUM) &&\
11247 		dohwcksum) {						\
11248 		if (hcksumflags & HCK_FULLCKSUM) {			\
11249 			/* 						\
11250 			 * Full checksum has been computed by the	\
11251 			 * hardware and has been attached. 		\
11252 			 */						\
11253 			doswcksum = B_FALSE;				\
11254 			if (!(hcksumflags & HCK_FULLCKSUM_OK) &&	\
11255 			    (dp->db_cksum16 != 0xffff)) {		\
11256 				ipcsumdbg("full hwcksumerr\n", mp);	\
11257 				goto error;				\
11258 			}						\
11259 		} else if ((hcksumflags & HCK_PARTIALCKSUM) &&		\
11260 		    (((len = (IP_SIMPLE_HDR_LENGTH - dp->db_cksumstart))\
11261 		    & 1) == 0)) {					\
11262 			uint32_t	tot_len = 0;			\
11263 									\
11264 			doswcksum = B_FALSE;				\
11265 			/* Partial checksum computed */			\
11266 			u1 += dp->db_cksum16;				\
11267 			tot_len = mp->b_wptr - mp->b_rptr;		\
11268 			if (!mp1)					\
11269 				mp1 = mp;				\
11270 			else						\
11271 				tot_len += mp1->b_wptr - mp1->b_rptr;	\
11272 			if (len > 0) {					\
11273 				/* 					\
11274 				 * Prepended extraneous data. Adjust	\
11275 				 * checksum.				\
11276 				 */					\
11277 				u2 = IP_BCSUM_PARTIAL((uchar_t *)(rptr +\
11278 				    dp->db_cksumstart),	(int32_t)len, 	\
11279 				    0);					\
11280 			} else						\
11281 				u2 = 0;					\
11282 			if ((len = (dp->db_cksumend - tot_len)) > 0) {	\
11283 				/* 					\
11284 				 * Postpended extraneous data. Adjust	\
11285 				 * checksum.				\
11286 				 */					\
11287 				uint32_t	u3;			\
11288 									\
11289 				u3 = IP_BCSUM_PARTIAL(mp1->b_wptr, 	\
11290 				    (int32_t)len, 0);			\
11291 				if ((uintptr_t)mp1->b_wptr & 1)		\
11292 					/*				\
11293 					 * Postpended extraneous data	\
11294 					 * was odd byte aligned, so 	\
11295 					 * swap resulting checksum 	\
11296 					 * bytes.			\
11297 					 */				\
11298 					u2 += ((u3 << 8) & 0xffff) | 	\
11299 					    (u3 >> 8);			\
11300 				else					\
11301 					u2 += u3;			\
11302 				u2 = (u2 & 0xFFFF) + ((int)(u2) >> 16);	\
11303 			}						\
11304 			/*						\
11305 			 * One's complement subtract extraneous checksum\
11306 			 */						\
11307 			if (u2 >= u1)					\
11308 				u1 = ~(u2 - u1) & 0xFFFF;		\
11309 			else						\
11310 				u1 -= u2;				\
11311 			u1 = (u1 & 0xFFFF) + ((int)u1 >> 16);		\
11312 			if (~(u1) & 0xFFFF) {				\
11313 				ipcsumdbg("partial hwcksumerr\n", mp);	\
11314 				goto error;				\
11315 			}						\
11316 		} 							\
11317 	} 								\
11318 	if (doswcksum) {						\
11319 		IP_STAT(ip_in_sw_cksum);				\
11320 		if ((IP_CSUM(mp, (int32_t)((uchar_t *)up -		\
11321 		    (uchar_t *)ipha), u1)) != 0) {			\
11322 			ipcsumdbg("swcksumerr\n", mp);			\
11323 			goto error;					\
11324 		}							\
11325 	}								\
11326 }
11327 
11328 	dp = mp->b_datap;
11329 	/* if udp hdr cksum != 0, then need to checksum udp packet */
11330 	if (up[3]) {
11331 		cksum_computed = B_TRUE;
11332 		/* multiple mblks of udp data? */
11333 		if ((mp1 = mp->b_cont) != NULL) {
11334 			/* more than two? */
11335 			if (mp1->b_cont)
11336 				goto multipktudp;
11337 		}
11338 
11339 		/* Pseudo-header checksum */
11340 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
11341 		    iphs[9] + up[2];
11342 		if (!mctl_present) {
11343 			ssize_t len = 0;
11344 
11345 			IP_CKSUM_RECV(len, u1, u2, mp, mp1, udpcksumerr, dp);
11346 		} else {
11347 multipktudp:
11348 			IP_STAT(ip_in_sw_cksum);
11349 			if ((IP_CSUM(mp, (int32_t)((uchar_t *)up -
11350 			    (uchar_t *)ipha), u1)) != 0) {
11351 udpcksumerr:
11352 				ip1dbg(("ip_udp_input: bad udp checksum\n"));
11353 				BUMP_MIB(&ip_mib, udpInCksumErrs);
11354 				freemsg(first_mp);
11355 				return;
11356 			}
11357 		}
11358 	}
11359 
11360 	/* broadcast IP packet? */
11361 	if (ire->ire_type == IRE_BROADCAST)
11362 		goto udpslowpath;
11363 
11364 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
11365 	    ire->ire_zoneid)) != NULL) {
11366 		ASSERT(connp->conn_upq != NULL);
11367 		IP_STAT(ip_udp_fast_path);
11368 
11369 		if (!canputnext(connp->conn_upq)) {
11370 			freemsg(mp);
11371 			BUMP_MIB(&ip_mib, udpInOverflows);
11372 		} else {
11373 			if (!mctl_present) {
11374 				BUMP_MIB(&ip_mib, ipInDelivers);
11375 			}
11376 			/*
11377 			 * mp and first_mp can change.
11378 			 */
11379 			if (ip_udp_check(q, connp, recv_ill,
11380 			    ipha, &mp, &first_mp, mctl_present)) {
11381 				putnext(connp->conn_upq, mp);
11382 			}
11383 		}
11384 		/*
11385 		 * freeb() cannot deal with null mblk being passed
11386 		 * in and first_mp can be set to null in the call
11387 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
11388 		 */
11389 		if (mctl_present && first_mp != NULL) {
11390 			freeb(first_mp);
11391 		}
11392 		CONN_DEC_REF(connp);
11393 		return;
11394 	}
11395 
11396 	/*
11397 	 * if we got here we know the packet is not fragmented and
11398 	 * has no options. The classifier could not find a conn_t and
11399 	 * most likely its an icmp packet so send it through slow path.
11400 	 */
11401 
11402 	goto udpslowpath;
11403 
11404 ipoptions:
11405 	if (!ip_options_cksum(q, mp, ipha, ire)) {
11406 		goto slow_done;
11407 	}
11408 
11409 	UPDATE_IB_PKT_COUNT(ire);
11410 	ire->ire_last_used_time = lbolt;
11411 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11412 	if (u1 & (IPH_MF | IPH_OFFSET)) {
11413 fragmented:
11414 		if (!ip_rput_fragment(q, &mp, ipha)) {
11415 			goto slow_done;
11416 		}
11417 		/*
11418 		 * Make sure that first_mp points back to mp as
11419 		 * the mp we came in with could have changed in
11420 		 * ip_rput_fragment().
11421 		 */
11422 		ASSERT(!mctl_present);
11423 		ipha = (ipha_t *)mp->b_rptr;
11424 		first_mp = mp;
11425 	}
11426 
11427 	/* Now we have a complete datagram, destined for this machine. */
11428 	u1 = IPH_HDR_LENGTH(ipha);
11429 	/* Pull up the UDP header, if necessary. */
11430 	if ((mp->b_wptr - mp->b_rptr) < (u1 + UDPH_SIZE)) {
11431 udppullup:
11432 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
11433 			BUMP_MIB(&ip_mib, ipInDiscards);
11434 			freemsg(first_mp);
11435 			goto slow_done;
11436 		}
11437 		ipha = (ipha_t *)mp->b_rptr;
11438 	}
11439 	/*
11440 	 * Validate the checksum.  This code is a bit funny looking
11441 	 * but may help out the compiler in this crucial spot.
11442 	 */
11443 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
11444 	if (!cksum_computed && up[3]) {
11445 		IP_STAT(ip_in_sw_cksum);
11446 		sum = IP_CSUM(mp, (int32_t)((uchar_t *)up - (uchar_t *)ipha),
11447 		    IP_UDP_CSUM_COMP + iphs[6] +
11448 		    iphs[7] + iphs[8] +
11449 		    iphs[9] + up[2]);
11450 		if (sum != 0) {
11451 			ip1dbg(("ip_udp_input: bad udp checksum\n"));
11452 				BUMP_MIB(&ip_mib, udpInCksumErrs);
11453 				freemsg(first_mp);
11454 				goto slow_done;
11455 		}
11456 	}
11457 udpslowpath:
11458 
11459 	ports = *(uint32_t *)up;
11460 	/* Clear hardware checksum flag */
11461 	mp->b_datap->db_struioun.cksum.flags = 0;
11462 	ip_fanout_udp(q, first_mp, ill, ipha, ports,
11463 	    (ire->ire_type == IRE_BROADCAST),
11464 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IP6INFO,
11465 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
11466 
11467 slow_done:
11468 	IP_STAT(ip_udp_slow_path);
11469 	return;
11470 
11471 #undef  rptr
11472 }
11473 
11474 /* ARGSUSED */
11475 static mblk_t *
11476 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
11477     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
11478     ill_rx_ring_t *ill_ring)
11479 {
11480 	conn_t		*connp;
11481 	uint32_t	sum;
11482 	uint32_t	u1;
11483 	uint32_t	u2;
11484 	uint16_t	*up;
11485 	int		offset;
11486 	ssize_t		len;
11487 	mblk_t		*mp1;
11488 	dblk_t		*dp;
11489 	boolean_t	syn_present = B_FALSE;
11490 	tcph_t		*tcph;
11491 	uint_t		ip_hdr_len;
11492 	ill_t		*ill = (ill_t *)q->q_ptr;
11493 	zoneid_t	zoneid = ire->ire_zoneid;
11494 
11495 #define	rptr	((uchar_t *)ipha)
11496 
11497 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
11498 
11499 	/*
11500 	 * FAST PATH for tcp packets
11501 	 */
11502 
11503 	/* u1 is # words of IP options */
11504 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
11505 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
11506 
11507 	/* IP options present */
11508 	if (u1) {
11509 		goto ipoptions;
11510 	} else {
11511 		/* Check the IP header checksum.  */
11512 		if (IS_IPHDR_HWCKSUM(mctl_present, mp, ill)) {
11513 			/* Clear the IP header h/w cksum flag */
11514 			mp->b_datap->db_struioun.cksum.flags &=
11515 			    ~HCK_IPV4_HDRCKSUM;
11516 		} else {
11517 #define	uph	((uint16_t *)ipha)
11518 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
11519 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
11520 #undef	uph
11521 			/* finish doing IP checksum */
11522 			sum = (sum & 0xFFFF) + (sum >> 16);
11523 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
11524 			/*
11525 			 * Don't verify header checksum if this packet
11526 			 * is coming back from AH/ESP as we already did it.
11527 			 */
11528 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
11529 				BUMP_MIB(&ip_mib, ipInCksumErrs);
11530 				goto error;
11531 			}
11532 		}
11533 	}
11534 
11535 	if (!mctl_present) {
11536 		UPDATE_IB_PKT_COUNT(ire);
11537 		ire->ire_last_used_time = lbolt;
11538 	}
11539 
11540 	/* packet part of fragmented IP packet? */
11541 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11542 	if (u1 & (IPH_MF | IPH_OFFSET)) {
11543 		goto fragmented;
11544 	}
11545 
11546 	/* u1 = IP header length (20 bytes) */
11547 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
11548 
11549 	/* does packet contain IP+TCP headers? */
11550 	len = mp->b_wptr - rptr;
11551 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
11552 		IP_STAT(ip_tcppullup);
11553 		goto tcppullup;
11554 	}
11555 
11556 	/* TCP options present? */
11557 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
11558 
11559 	/*
11560 	 * If options need to be pulled up, then goto tcpoptions.
11561 	 * otherwise we are still in the fast path
11562 	 */
11563 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
11564 		IP_STAT(ip_tcpoptions);
11565 		goto tcpoptions;
11566 	}
11567 
11568 	/* multiple mblks of tcp data? */
11569 	if ((mp1 = mp->b_cont) != NULL) {
11570 		/* more then two? */
11571 		if (mp1->b_cont != NULL) {
11572 			IP_STAT(ip_multipkttcp);
11573 			goto multipkttcp;
11574 		}
11575 		len += mp1->b_wptr - mp1->b_rptr;
11576 	}
11577 
11578 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
11579 
11580 	/* part of pseudo checksum */
11581 
11582 	/* TCP datagram length */
11583 	u1 = len - IP_SIMPLE_HDR_LENGTH;
11584 
11585 #define	iphs    ((uint16_t *)ipha)
11586 
11587 #ifdef	_BIG_ENDIAN
11588 	u1 += IPPROTO_TCP;
11589 #else
11590 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
11591 #endif
11592 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
11593 
11594 
11595 	/*
11596 	 * If the packet has gone through AH/ESP, do the checksum here
11597 	 * itself.
11598 	 *
11599 	 * If it has not gone through IPSEC processing and not a duped
11600 	 * mblk, then look for driver checksummed mblk. We validate or
11601 	 * postpone the checksum to TCP for single copy checksum.
11602 	 *
11603 	 * Note that we only honor HW cksum in the fastpath.
11604 	 */
11605 	dp = mp->b_datap;
11606 	if (!mctl_present) {
11607 		IP_CKSUM_RECV(len, u1, u2, mp, mp1, tcpcksumerr, dp);
11608 	} else {
11609 		IP_STAT(ip_in_sw_cksum);
11610 		if ((IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr),
11611 		    u1)) != 0) {
11612 tcpcksumerr:
11613 			BUMP_MIB(&ip_mib, tcpInErrs);
11614 			ip1dbg(("ip_tcp_input: bad tcp checksum \n"));
11615 			freemsg(first_mp);
11616 			goto slow_done;
11617 		}
11618 	}
11619 
11620 try_again:
11621 
11622 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
11623 	    NULL) {
11624 		/* Send the TH_RST */
11625 		goto no_conn;
11626 	}
11627 
11628 	/*
11629 	 * TCP FAST PATH for AF_INET socket.
11630 	 *
11631 	 * TCP fast path to avoid extra work. An AF_INET socket type
11632 	 * does not have facility to receive extra information via
11633 	 * ip_process or ip_add_info. Also, when the connection was
11634 	 * established, we made a check if this connection is impacted
11635 	 * by any global IPSec policy or per connection policy (a
11636 	 * policy that comes in effect later will not apply to this
11637 	 * connection). Since all this can be determined at the
11638 	 * connection establishment time, a quick check of flags
11639 	 * can avoid extra work.
11640 	 */
11641 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
11642 	    !IPP_ENABLED(IPP_LOCAL_IN)) {
11643 		ASSERT(first_mp == mp);
11644 		SET_SQUEUE(mp, tcp_rput_data, connp);
11645 		return (mp);
11646 	}
11647 
11648 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
11649 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
11650 		if (IPCL_IS_TCP(connp)) {
11651 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
11652 			mp->b_datap->db_cksumstart =
11653 			    (intptr_t)ip_squeue_get(ill_ring);
11654 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
11655 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
11656 				SET_SQUEUE(mp, connp->conn_recv, connp);
11657 				return (mp);
11658 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
11659 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
11660 				ip_squeue_enter_unbound++;
11661 				SET_SQUEUE(mp, tcp_conn_request_unbound,
11662 				    connp);
11663 				return (mp);
11664 			}
11665 			syn_present = B_TRUE;
11666 		}
11667 
11668 	}
11669 
11670 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
11671 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
11672 
11673 		/* No need to send this packet to TCP */
11674 		if ((flags & TH_RST) || (flags & TH_URG)) {
11675 			CONN_DEC_REF(connp);
11676 			freemsg(first_mp);
11677 			return (NULL);
11678 		}
11679 		if (flags & TH_ACK) {
11680 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
11681 			CONN_DEC_REF(connp);
11682 			return (NULL);
11683 		}
11684 
11685 		CONN_DEC_REF(connp);
11686 		freemsg(first_mp);
11687 		return (NULL);
11688 	}
11689 
11690 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
11691 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
11692 		    ipha, NULL, mctl_present);
11693 		if (first_mp == NULL) {
11694 			CONN_DEC_REF(connp);
11695 			return (NULL);
11696 		}
11697 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
11698 			ASSERT(syn_present);
11699 			if (mctl_present) {
11700 				ASSERT(first_mp != mp);
11701 				first_mp->b_datap->db_struioflag |=
11702 				    STRUIO_POLICY;
11703 			} else {
11704 				ASSERT(first_mp == mp);
11705 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
11706 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
11707 			}
11708 		} else {
11709 			/*
11710 			 * Discard first_mp early since we're dealing with a
11711 			 * fully-connected conn_t and tcp doesn't do policy in
11712 			 * this case.
11713 			 */
11714 			if (mctl_present) {
11715 				freeb(first_mp);
11716 				mctl_present = B_FALSE;
11717 			}
11718 			first_mp = mp;
11719 		}
11720 	}
11721 
11722 	/* Initiate IPPF processing for fastpath */
11723 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
11724 		uint32_t	ill_index;
11725 
11726 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
11727 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
11728 		if (mp == NULL) {
11729 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
11730 			    "deferred/dropped during IPPF processing\n"));
11731 			CONN_DEC_REF(connp);
11732 			if (mctl_present)
11733 				freeb(first_mp);
11734 			return (NULL);
11735 		} else if (mctl_present) {
11736 			/*
11737 			 * ip_process might return a new mp.
11738 			 */
11739 			ASSERT(first_mp != mp);
11740 			first_mp->b_cont = mp;
11741 		} else {
11742 			first_mp = mp;
11743 		}
11744 
11745 	}
11746 
11747 	if (!syn_present && connp->conn_ipv6_recvpktinfo) {
11748 		mp = ip_add_info(mp, recv_ill, flags);
11749 		if (mp == NULL) {
11750 			CONN_DEC_REF(connp);
11751 			if (mctl_present)
11752 				freeb(first_mp);
11753 			return (NULL);
11754 		} else if (mctl_present) {
11755 			/*
11756 			 * ip_add_info might return a new mp.
11757 			 */
11758 			ASSERT(first_mp != mp);
11759 			first_mp->b_cont = mp;
11760 		} else {
11761 			first_mp = mp;
11762 		}
11763 	}
11764 
11765 	if (IPCL_IS_TCP(connp)) {
11766 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
11767 		return (first_mp);
11768 	} else {
11769 		putnext(connp->conn_rq, first_mp);
11770 		CONN_DEC_REF(connp);
11771 		return (NULL);
11772 	}
11773 
11774 no_conn:
11775 	/* Initiate IPPf processing, if needed. */
11776 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
11777 		uint32_t ill_index;
11778 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
11779 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
11780 		if (first_mp == NULL) {
11781 			return (NULL);
11782 		}
11783 	}
11784 	BUMP_MIB(&ip_mib, ipInDelivers);
11785 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr));
11786 	return (NULL);
11787 ipoptions:
11788 	if (!ip_options_cksum(q, first_mp, ipha, ire)) {
11789 		goto slow_done;
11790 	}
11791 
11792 	UPDATE_IB_PKT_COUNT(ire);
11793 	ire->ire_last_used_time = lbolt;
11794 
11795 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11796 	if (u1 & (IPH_MF | IPH_OFFSET)) {
11797 fragmented:
11798 		if (!ip_rput_fragment(q, &mp, ipha)) {
11799 			if (mctl_present)
11800 				freeb(first_mp);
11801 			goto slow_done;
11802 		}
11803 		/*
11804 		 * Make sure that first_mp points back to mp as
11805 		 * the mp we came in with could have changed in
11806 		 * ip_rput_fragment().
11807 		 */
11808 		ASSERT(!mctl_present);
11809 		ipha = (ipha_t *)mp->b_rptr;
11810 		first_mp = mp;
11811 	}
11812 
11813 tcp_slow:
11814 	/* Now we have a complete datagram, destined for this machine. */
11815 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
11816 
11817 	len = mp->b_wptr - mp->b_rptr;
11818 	/* Pull up a minimal TCP header, if necessary. */
11819 	if (len < (u1 + 20)) {
11820 tcppullup:
11821 		if (!pullupmsg(mp, u1 + 20)) {
11822 			BUMP_MIB(&ip_mib, ipInDiscards);
11823 			goto error;
11824 		}
11825 		ipha = (ipha_t *)mp->b_rptr;
11826 		len = mp->b_wptr - mp->b_rptr;
11827 	}
11828 
11829 	/*
11830 	 * Extract the offset field from the TCP header.  As usual, we
11831 	 * try to help the compiler more than the reader.
11832 	 */
11833 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
11834 	if (offset != 5) {
11835 tcpoptions:
11836 		if (offset < 5) {
11837 			BUMP_MIB(&ip_mib, ipInDiscards);
11838 			goto error;
11839 		}
11840 		/*
11841 		 * There must be TCP options.
11842 		 * Make sure we can grab them.
11843 		 */
11844 		offset <<= 2;
11845 		offset += u1;
11846 		if (len < offset) {
11847 			if (!pullupmsg(mp, offset)) {
11848 				BUMP_MIB(&ip_mib, ipInDiscards);
11849 				goto error;
11850 			}
11851 			ipha = (ipha_t *)mp->b_rptr;
11852 			len = mp->b_wptr - rptr;
11853 		}
11854 	}
11855 
11856 	/* Get the total packet length in len, including headers. */
11857 	if (mp->b_cont) {
11858 multipkttcp:
11859 		len = msgdsize(mp);
11860 	}
11861 
11862 	/*
11863 	 * Check the TCP checksum by pulling together the pseudo-
11864 	 * header checksum, and passing it to ip_csum to be added in
11865 	 * with the TCP datagram.
11866 	 *
11867 	 * Since we are not using the hwcksum if available we must
11868 	 * clear the flag. We may come here via tcppullup or tcpoptions.
11869 	 * If either of these fails along the way the mblk is freed.
11870 	 * If this logic ever changes and mblk is reused to say send
11871 	 * ICMP's back, then this flag may need to be cleared in
11872 	 * other places as well.
11873 	 */
11874 	mp->b_datap->db_struioun.cksum.flags = 0;
11875 
11876 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
11877 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
11878 #ifdef	_BIG_ENDIAN
11879 	u1 += IPPROTO_TCP;
11880 #else
11881 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
11882 #endif
11883 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
11884 	/*
11885 	 * Not M_DATA mblk or its a dup, so do the checksum now.
11886 	 */
11887 	IP_STAT(ip_in_sw_cksum);
11888 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1)) {
11889 		BUMP_MIB(&ip_mib, tcpInErrs);
11890 		goto error;
11891 	}
11892 
11893 	IP_STAT(ip_tcp_slow_path);
11894 	goto try_again;
11895 #undef  iphs
11896 #undef  rptr
11897 
11898 error:
11899 	freemsg(first_mp);
11900 slow_done:
11901 	return (NULL);
11902 }
11903 
11904 /* ARGSUSED */
11905 static void
11906 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
11907     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
11908 {
11909 	conn_t		*connp;
11910 	uint32_t	sum;
11911 	uint32_t	u1;
11912 	ssize_t		len;
11913 	sctp_hdr_t	*sctph;
11914 	zoneid_t	zoneid = ire->ire_zoneid;
11915 	uint32_t	pktsum;
11916 	uint32_t	calcsum;
11917 	uint32_t	ports;
11918 	uint_t		ipif_seqid;
11919 	in6_addr_t	map_src, map_dst;
11920 	ill_t		*ill = (ill_t *)q->q_ptr;
11921 
11922 #define	rptr	((uchar_t *)ipha)
11923 
11924 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
11925 
11926 	/* u1 is # words of IP options */
11927 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
11928 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
11929 
11930 	/* IP options present */
11931 	if (u1 > 0) {
11932 		goto ipoptions;
11933 	} else {
11934 		/* Check the IP header checksum.  */
11935 		if (IS_IPHDR_HWCKSUM(mctl_present, mp, ill)) {
11936 			/*
11937 			 * Since there is no SCTP h/w cksum support yet, just
11938 			 * clear the flag.
11939 			 */
11940 			mp->b_datap->db_struioun.cksum.flags = 0;
11941 		} else {
11942 #define	uph	((uint16_t *)ipha)
11943 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
11944 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
11945 #undef	uph
11946 			/* finish doing IP checksum */
11947 			sum = (sum & 0xFFFF) + (sum >> 16);
11948 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
11949 			/*
11950 			 * Don't verify header checksum if this packet
11951 			 * is coming back from AH/ESP as we already did it.
11952 			 */
11953 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
11954 				BUMP_MIB(&ip_mib, ipInCksumErrs);
11955 				goto error;
11956 			}
11957 		}
11958 	}
11959 
11960 	/*
11961 	 * Don't verify header checksum if this packet is coming
11962 	 * back from AH/ESP as we already did it.
11963 	 */
11964 	if (!mctl_present) {
11965 		UPDATE_IB_PKT_COUNT(ire);
11966 		ire->ire_last_used_time = lbolt;
11967 	}
11968 
11969 	/* packet part of fragmented IP packet? */
11970 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11971 	if (u1 & (IPH_MF | IPH_OFFSET))
11972 		goto fragmented;
11973 
11974 	/* u1 = IP header length (20 bytes) */
11975 	u1 = IP_SIMPLE_HDR_LENGTH;
11976 
11977 find_sctp_client:
11978 	/* Pullup if we don't have the sctp common header. */
11979 	len = MBLKL(mp);
11980 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
11981 		if (mp->b_cont == NULL ||
11982 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
11983 			BUMP_MIB(&ip_mib, ipInDiscards);
11984 			goto error;
11985 		}
11986 		ipha = (ipha_t *)mp->b_rptr;
11987 		len = MBLKL(mp);
11988 	}
11989 
11990 	sctph = (sctp_hdr_t *)(rptr + u1);
11991 #ifdef	DEBUG
11992 	if (!skip_sctp_cksum) {
11993 #endif
11994 		pktsum = sctph->sh_chksum;
11995 		sctph->sh_chksum = 0;
11996 		calcsum = sctp_cksum(mp, u1);
11997 		if (calcsum != pktsum) {
11998 			BUMP_MIB(&sctp_mib, sctpChecksumError);
11999 			goto error;
12000 		}
12001 		sctph->sh_chksum = pktsum;
12002 #ifdef	DEBUG	/* skip_sctp_cksum */
12003 	}
12004 #endif
12005 	/* get the ports */
12006 	ports = *(uint32_t *)&sctph->sh_sport;
12007 
12008 	ipif_seqid = ire->ire_ipif->ipif_seqid;
12009 	IRE_REFRELE(ire);
12010 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
12011 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
12012 	if ((connp = sctp_find_conn(&map_src, &map_dst, ports, ipif_seqid,
12013 	    zoneid)) == NULL) {
12014 		/* Check for raw socket or OOTB handling */
12015 		goto no_conn;
12016 	}
12017 
12018 	/* Found a client; up it goes */
12019 	BUMP_MIB(&ip_mib, ipInDelivers);
12020 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
12021 	return;
12022 
12023 no_conn:
12024 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
12025 	    ports, mctl_present, flags, B_TRUE, ipif_seqid, zoneid);
12026 	return;
12027 
12028 ipoptions:
12029 	mp->b_datap->db_struioun.cksum.flags = 0;
12030 	if (!ip_options_cksum(q, first_mp, ipha, ire))
12031 		goto slow_done;
12032 
12033 	UPDATE_IB_PKT_COUNT(ire);
12034 	ire->ire_last_used_time = lbolt;
12035 
12036 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12037 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12038 fragmented:
12039 		if (!ip_rput_fragment(q, &mp, ipha))
12040 			goto slow_done;
12041 		/*
12042 		 * Make sure that first_mp points back to mp as
12043 		 * the mp we came in with could have changed in
12044 		 * ip_rput_fragment().
12045 		 */
12046 		ASSERT(!mctl_present);
12047 		ipha = (ipha_t *)mp->b_rptr;
12048 		first_mp = mp;
12049 	}
12050 
12051 	/* Now we have a complete datagram, destined for this machine. */
12052 	u1 = IPH_HDR_LENGTH(ipha);
12053 	goto find_sctp_client;
12054 #undef  iphs
12055 #undef  rptr
12056 
12057 error:
12058 	freemsg(first_mp);
12059 slow_done:
12060 	IRE_REFRELE(ire);
12061 }
12062 
12063 #define	VER_BITS	0xF0
12064 #define	VERSION_6	0x60
12065 
12066 static boolean_t
12067 ip_rput_multimblk_ipoptions(queue_t *q, mblk_t *mp, ipha_t **iphapp,
12068     ipaddr_t *dstp)
12069 {
12070 	uint_t	opt_len;
12071 	ipha_t *ipha;
12072 	ssize_t len;
12073 	uint_t	pkt_len;
12074 
12075 	IP_STAT(ip_ipoptions);
12076 	ipha = *iphapp;
12077 
12078 #define	rptr    ((uchar_t *)ipha)
12079 	/* Assume no IPv6 packets arrive over the IPv4 queue */
12080 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
12081 		BUMP_MIB(&ip_mib, ipInIPv6);
12082 		freemsg(mp);
12083 		return (B_FALSE);
12084 	}
12085 
12086 	/* multiple mblk or too short */
12087 	pkt_len = ntohs(ipha->ipha_length);
12088 
12089 	/* Get the number of words of IP options in the IP header. */
12090 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
12091 	if (opt_len) {
12092 		/* IP Options present!  Validate and process. */
12093 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
12094 			BUMP_MIB(&ip_mib, ipInHdrErrors);
12095 			goto done;
12096 		}
12097 		/*
12098 		 * Recompute complete header length and make sure we
12099 		 * have access to all of it.
12100 		 */
12101 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
12102 		if (len > (mp->b_wptr - rptr)) {
12103 			if (len > pkt_len) {
12104 				BUMP_MIB(&ip_mib, ipInHdrErrors);
12105 				goto done;
12106 			}
12107 			if (!pullupmsg(mp, len)) {
12108 				BUMP_MIB(&ip_mib, ipInDiscards);
12109 				goto done;
12110 			}
12111 			ipha = (ipha_t *)mp->b_rptr;
12112 		}
12113 		/*
12114 		 * Go off to ip_rput_options which returns the next hop
12115 		 * destination address, which may have been affected
12116 		 * by source routing.
12117 		 */
12118 		IP_STAT(ip_opt);
12119 		if (ip_rput_options(q, mp, ipha, dstp) == -1) {
12120 			return (B_FALSE);
12121 		}
12122 	}
12123 	*iphapp = ipha;
12124 	return (B_TRUE);
12125 done:
12126 	/* clear b_prev - used by ip_mroute_decap */
12127 	mp->b_prev = NULL;
12128 	freemsg(mp);
12129 	return (B_FALSE);
12130 #undef  rptr
12131 }
12132 
12133 /*
12134  * Deal with the fact that there is no ire for the destination.
12135  * The incoming ill (in_ill) is passed in to ip_newroute only
12136  * in the case of packets coming from mobile ip forward tunnel.
12137  * It must be null otherwise.
12138  */
12139 static void
12140 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
12141     ipaddr_t dst)
12142 {
12143 	ipha_t	*ipha;
12144 	ill_t	*ill;
12145 
12146 	ipha = (ipha_t *)mp->b_rptr;
12147 	ill = (ill_t *)q->q_ptr;
12148 
12149 	ASSERT(ill != NULL);
12150 	/*
12151 	 * No IRE for this destination, so it can't be for us.
12152 	 * Unless we are forwarding, drop the packet.
12153 	 * We have to let source routed packets through
12154 	 * since we don't yet know if they are 'ping -l'
12155 	 * packets i.e. if they will go out over the
12156 	 * same interface as they came in on.
12157 	 */
12158 	if (ll_multicast) {
12159 		freemsg(mp);
12160 		return;
12161 	}
12162 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha)) {
12163 		BUMP_MIB(&ip_mib, ipForwProhibits);
12164 		freemsg(mp);
12165 		return;
12166 	}
12167 
12168 	/* Check for Martian addresses */
12169 	if ((in_ill == NULL) && (ip_no_forward(ipha, ill))) {
12170 		freemsg(mp);
12171 		return;
12172 	}
12173 
12174 	/* Mark this packet as having originated externally */
12175 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
12176 
12177 	/*
12178 	 * Clear the indication that this may have a hardware checksum
12179 	 * as we are not using it
12180 	 */
12181 	mp->b_datap->db_struioun.cksum.flags = 0;
12182 
12183 	/*
12184 	 * Now hand the packet to ip_newroute.
12185 	 */
12186 	ip_newroute(q, mp, dst, in_ill, NULL);
12187 }
12188 
12189 /*
12190  * check ip header length and align it.
12191  */
12192 static boolean_t
12193 ip_check_and_align_header(queue_t *q, mblk_t *mp)
12194 {
12195 	ssize_t len;
12196 	ill_t *ill;
12197 	ipha_t	*ipha;
12198 
12199 	len = MBLKL(mp);
12200 
12201 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
12202 		if (!OK_32PTR(mp->b_rptr))
12203 			IP_STAT(ip_notaligned1);
12204 		else
12205 			IP_STAT(ip_notaligned2);
12206 		/* Guard against bogus device drivers */
12207 		if (len < 0) {
12208 			/* clear b_prev - used by ip_mroute_decap */
12209 			mp->b_prev = NULL;
12210 			BUMP_MIB(&ip_mib, ipInHdrErrors);
12211 			freemsg(mp);
12212 			return (B_FALSE);
12213 		}
12214 
12215 		if (ip_rput_pullups++ == 0) {
12216 			ill = (ill_t *)q->q_ptr;
12217 			ipha = (ipha_t *)mp->b_rptr;
12218 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
12219 			    "ip_check_and_align_header: %s forced us to "
12220 			    " pullup pkt, hdr len %ld, hdr addr %p",
12221 			    ill->ill_name, len, ipha);
12222 		}
12223 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
12224 			/* clear b_prev - used by ip_mroute_decap */
12225 			mp->b_prev = NULL;
12226 			BUMP_MIB(&ip_mib, ipInDiscards);
12227 			freemsg(mp);
12228 			return (B_FALSE);
12229 		}
12230 	}
12231 	return (B_TRUE);
12232 }
12233 
12234 static boolean_t
12235 ip_rput_notforus(queue_t **qp, mblk_t *mp, ire_t *ire, ill_t *ill)
12236 {
12237 	ill_group_t	*ill_group;
12238 	ill_group_t	*ire_group;
12239 	queue_t 	*q;
12240 	ill_t		*ire_ill;
12241 	uint_t		ill_ifindex;
12242 
12243 	q = *qp;
12244 	/*
12245 	 * We need to check to make sure the packet came in
12246 	 * on the queue associated with the destination IRE.
12247 	 * Note that for multicast packets and broadcast packets sent to
12248 	 * a broadcast address which is shared between multiple interfaces
12249 	 * we should not do this since we just got a random broadcast ire.
12250 	 */
12251 	if (ire->ire_rfq && ire->ire_type != IRE_BROADCAST) {
12252 		boolean_t check_multi = B_TRUE;
12253 
12254 		/*
12255 		 * This packet came in on an interface other than the
12256 		 * one associated with the destination address.
12257 		 * "Gateway" it to the appropriate interface here.
12258 		 * As long as the ills belong to the same group,
12259 		 * we don't consider them to arriving on the wrong
12260 		 * interface. Thus, when the switch is doing inbound
12261 		 * load spreading, we won't drop packets when we
12262 		 * are doing strict multihoming checks. Note, the
12263 		 * same holds true for 'usesrc groups' where the
12264 		 * destination address may belong to another interface
12265 		 * to allow multipathing to happen
12266 		 */
12267 		ill_group = ill->ill_group;
12268 		ire_ill = (ill_t *)(ire->ire_rfq)->q_ptr;
12269 		ill_ifindex = ill->ill_usesrc_ifindex;
12270 		ire_group = ire_ill->ill_group;
12271 
12272 		/*
12273 		 * If it's part of the same IPMP group, or if it's a legal
12274 		 * address on the 'usesrc' interface, then bypass strict
12275 		 * checks.
12276 		 */
12277 		if (ill_group != NULL && ill_group == ire_group) {
12278 			check_multi = B_FALSE;
12279 		} else if (ill_ifindex != 0 &&
12280 		    ill_ifindex == ire_ill->ill_phyint->phyint_ifindex) {
12281 			check_multi = B_FALSE;
12282 		}
12283 
12284 		if (check_multi &&
12285 		    ip_strict_dst_multihoming &&
12286 		    ((ill->ill_flags &
12287 		    ire->ire_ipif->ipif_ill->ill_flags &
12288 		    ILLF_ROUTER) == 0)) {
12289 			/* Drop packet */
12290 			BUMP_MIB(&ip_mib, ipForwProhibits);
12291 			freemsg(mp);
12292 			ire_refrele(ire);
12293 			return (B_TRUE);
12294 		}
12295 
12296 		/*
12297 		 * Change the queue (for non-virtual destination network
12298 		 * interfaces) and ip_rput_local will be called with the right
12299 		 * queue
12300 		 */
12301 		q = ire->ire_rfq;
12302 	}
12303 	/* Must be broadcast.  We'll take it. */
12304 	*qp = q;
12305 	return (B_FALSE);
12306 }
12307 
12308 static void
12309 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
12310     ill_t *ill, int ll_multicast)
12311 {
12312 	ill_group_t	*ill_group;
12313 	ill_group_t	*ire_group;
12314 	queue_t	*dev_q;
12315 
12316 	ASSERT(ire->ire_stq != NULL);
12317 	if (ll_multicast != 0)
12318 		goto drop_pkt;
12319 
12320 	if (ip_no_forward(ipha, ill))
12321 		goto drop_pkt;
12322 
12323 	ill_group = ill->ill_group;
12324 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
12325 	/*
12326 	 * Check if we want to forward this one at this time.
12327 	 * We allow source routed packets on a host provided that
12328 	 * they go out the same interface or same interface group
12329 	 * as they came in on.
12330 	 *
12331 	 * XXX To be quicker, we may wish to not chase pointers to
12332 	 * get the ILLF_ROUTER flag and instead store the
12333 	 * forwarding policy in the ire.  An unfortunate
12334 	 * side-effect of that would be requiring an ire flush
12335 	 * whenever the ILLF_ROUTER flag changes.
12336 	 */
12337 	if (((ill->ill_flags &
12338 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
12339 	    ILLF_ROUTER) == 0) &&
12340 	    !(ip_source_routed(ipha) && (ire->ire_rfq == q ||
12341 	    (ill_group != NULL && ill_group == ire_group)))) {
12342 		BUMP_MIB(&ip_mib, ipForwProhibits);
12343 		if (ip_source_routed(ipha)) {
12344 			q = WR(q);
12345 			/*
12346 			 * Clear the indication that this may have
12347 			 * hardware checksum as we are not using it.
12348 			 */
12349 			mp->b_datap->db_struioun.cksum.flags = 0;
12350 			icmp_unreachable(q, mp,
12351 			    ICMP_SOURCE_ROUTE_FAILED);
12352 			ire_refrele(ire);
12353 			return;
12354 		}
12355 		goto drop_pkt;
12356 	}
12357 
12358 	/* Packet is being forwarded. Turning off hwcksum flag. */
12359 	mp->b_datap->db_struioun.cksum.flags = 0;
12360 	if (ip_g_send_redirects) {
12361 		/*
12362 		 * Check whether the incoming interface and outgoing
12363 		 * interface is part of the same group. If so,
12364 		 * send redirects.
12365 		 *
12366 		 * Check the source address to see if it originated
12367 		 * on the same logical subnet it is going back out on.
12368 		 * If so, we should be able to send it a redirect.
12369 		 * Avoid sending a redirect if the destination
12370 		 * is directly connected (gw_addr == 0),
12371 		 * or if the packet was source routed out this
12372 		 * interface.
12373 		 */
12374 		ipaddr_t src;
12375 		mblk_t	*mp1;
12376 		ire_t	*src_ire = NULL;
12377 
12378 		/*
12379 		 * Check whether ire_rfq and q are from the same ill
12380 		 * or if they are not same, they at least belong
12381 		 * to the same group. If so, send redirects.
12382 		 */
12383 		if ((ire->ire_rfq == q ||
12384 		    (ill_group != NULL && ill_group == ire_group)) &&
12385 		    (ire->ire_gateway_addr != 0) &&
12386 		    !ip_source_routed(ipha)) {
12387 
12388 			src = ipha->ipha_src;
12389 			src_ire = ire_ftable_lookup(src, 0, 0,
12390 			    IRE_INTERFACE, ire->ire_ipif, NULL, ALL_ZONES,
12391 			    0, MATCH_IRE_IPIF | MATCH_IRE_TYPE);
12392 
12393 			if (src_ire != NULL) {
12394 				/*
12395 				 * The source is directly connected.
12396 				 * Just copy the ip header (which is
12397 				 * in the first mblk)
12398 				 */
12399 				mp1 = copyb(mp);
12400 				if (mp1 != NULL) {
12401 					icmp_send_redirect(WR(q), mp1,
12402 					    ire->ire_gateway_addr);
12403 				}
12404 				ire_refrele(src_ire);
12405 			}
12406 		}
12407 	}
12408 
12409 	dev_q = ire->ire_stq->q_next;
12410 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
12411 		BUMP_MIB(&ip_mib, ipInDiscards);
12412 		freemsg(mp);
12413 		ire_refrele(ire);
12414 		return;
12415 	}
12416 
12417 	ip_rput_forward(ire, ipha, mp, ill);
12418 	IRE_REFRELE(ire);
12419 	return;
12420 
12421 drop_pkt:
12422 	ire_refrele(ire);
12423 	ip2dbg(("ip_rput_forward: drop pkt\n"));
12424 	freemsg(mp);
12425 }
12426 
12427 static boolean_t
12428 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t **irep, ipha_t *ipha,
12429     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
12430 {
12431 	queue_t		*q;
12432 	ire_t		*ire;
12433 
12434 	q = *qp;
12435 	ire = *irep;
12436 
12437 	/*
12438 	 * Clear the indication that this may have hardware
12439 	 * checksum as we are not using it.
12440 	 */
12441 	mp->b_datap->db_struioun.cksum.flags = 0;
12442 
12443 	/*
12444 	 * Directed broadcast forwarding: if the packet came in over a
12445 	 * different interface then it is routed out over we can forward it.
12446 	 */
12447 	if (ipha->ipha_protocol == IPPROTO_TCP) {
12448 		ire_refrele(ire);
12449 		freemsg(mp);
12450 		BUMP_MIB(&ip_mib, ipInDiscards);
12451 		return (B_TRUE);
12452 	}
12453 	/*
12454 	 * For multicast we have set dst to be INADDR_BROADCAST
12455 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
12456 	 * only for broadcast packets.
12457 	 */
12458 	if (!CLASSD(ipha->ipha_dst)) {
12459 		ire_t *new_ire;
12460 		ipif_t *ipif;
12461 		/*
12462 		 * For ill groups, as the switch duplicates broadcasts
12463 		 * across all the ports, we need to filter out and
12464 		 * send up only one copy. There is one copy for every
12465 		 * broadcast address on each ill. Thus, we look for a
12466 		 * specific IRE on this ill and look at IRE_MARK_NORECV
12467 		 * later to see whether this ill is eligible to receive
12468 		 * them or not. ill_nominate_bcast_rcv() nominates only
12469 		 * one set of IREs for receiving.
12470 		 */
12471 
12472 		ipif = ipif_get_next_ipif(NULL, ill);
12473 		if (ipif == NULL) {
12474 			ire_refrele(ire);
12475 			freemsg(mp);
12476 			BUMP_MIB(&ip_mib, ipInDiscards);
12477 			return (B_TRUE);
12478 		}
12479 		new_ire = ire_ctable_lookup(dst, 0, 0,
12480 		    ipif, ALL_ZONES, MATCH_IRE_ILL);
12481 		ipif_refrele(ipif);
12482 
12483 		if (new_ire != NULL) {
12484 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
12485 				ire_refrele(ire);
12486 				ire_refrele(new_ire);
12487 				freemsg(mp);
12488 				BUMP_MIB(&ip_mib, ipInDiscards);
12489 				return (B_TRUE);
12490 			}
12491 			/*
12492 			 * In the special case of multirouted broadcast
12493 			 * packets, we unconditionally need to "gateway"
12494 			 * them to the appropriate interface here.
12495 			 * In the normal case, this cannot happen, because
12496 			 * there is no broadcast IRE tagged with the
12497 			 * RTF_MULTIRT flag.
12498 			 */
12499 			if (new_ire->ire_flags & RTF_MULTIRT) {
12500 				ire_refrele(new_ire);
12501 				if (ire->ire_rfq != NULL) {
12502 					q = ire->ire_rfq;
12503 					*qp = q;
12504 				}
12505 			} else {
12506 				ire_refrele(ire);
12507 				ire = new_ire;
12508 			}
12509 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
12510 			if (!ip_g_forward_directed_bcast) {
12511 				/*
12512 				 * Free the message if
12513 				 * ip_g_forward_directed_bcast is turned
12514 				 * off for non-local broadcast.
12515 				 */
12516 				ire_refrele(ire);
12517 				freemsg(mp);
12518 				BUMP_MIB(&ip_mib, ipInDiscards);
12519 				return (B_TRUE);
12520 			}
12521 		} else {
12522 			/*
12523 			 * This CGTP packet successfully passed the
12524 			 * CGTP filter, but the related CGTP
12525 			 * broadcast IRE has not been found,
12526 			 * meaning that the redundant ipif is
12527 			 * probably down. However, if we discarded
12528 			 * this packet, its duplicate would be
12529 			 * filtered out by the CGTP filter so none
12530 			 * of them would get through. So we keep
12531 			 * going with this one.
12532 			 */
12533 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
12534 			if (ire->ire_rfq != NULL) {
12535 				q = ire->ire_rfq;
12536 				*qp = q;
12537 			}
12538 		}
12539 	}
12540 	if (ip_g_forward_directed_bcast && ll_multicast == 0) {
12541 		/*
12542 		 * Verify that there are not more then one
12543 		 * IRE_BROADCAST with this broadcast address which
12544 		 * has ire_stq set.
12545 		 * TODO: simplify, loop over all IRE's
12546 		 */
12547 		ire_t	*ire1;
12548 		int	num_stq = 0;
12549 		mblk_t	*mp1;
12550 
12551 		/* Find the first one with ire_stq set */
12552 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
12553 		for (ire1 = ire; ire1 &&
12554 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
12555 		    ire1 = ire1->ire_next)
12556 			;
12557 		if (ire1) {
12558 			ire_refrele(ire);
12559 			ire = ire1;
12560 			IRE_REFHOLD(ire);
12561 		}
12562 
12563 		/* Check if there are additional ones with stq set */
12564 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
12565 			if (ire->ire_addr != ire1->ire_addr)
12566 				break;
12567 			if (ire1->ire_stq) {
12568 				num_stq++;
12569 				break;
12570 			}
12571 		}
12572 		rw_exit(&ire->ire_bucket->irb_lock);
12573 		if (num_stq == 1 && ire->ire_stq != NULL) {
12574 			ip1dbg(("ip_rput_process_broadcast: directed "
12575 			    "broadcast to 0x%x\n",
12576 			    ntohl(ire->ire_addr)));
12577 			mp1 = copymsg(mp);
12578 			if (mp1) {
12579 				switch (ipha->ipha_protocol) {
12580 				case IPPROTO_UDP:
12581 					ip_udp_input(q, mp1, ipha, ire, ill);
12582 					break;
12583 				default:
12584 					ip_proto_input(q, mp1, ipha, ire, ill);
12585 					break;
12586 				}
12587 			}
12588 			/*
12589 			 * Adjust ttl to 2 (1+1 - the forward engine
12590 			 * will decrement it by one.
12591 			 */
12592 			if (ip_csum_hdr(ipha)) {
12593 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12594 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
12595 				freemsg(mp);
12596 				ire_refrele(ire);
12597 				return (B_TRUE);
12598 			}
12599 			ipha->ipha_ttl = ip_broadcast_ttl + 1;
12600 			ipha->ipha_hdr_checksum = 0;
12601 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
12602 			ip_rput_process_forward(q, mp, ire, ipha,
12603 			    ill, ll_multicast);
12604 			return (B_TRUE);
12605 		}
12606 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
12607 		    ntohl(ire->ire_addr)));
12608 	}
12609 
12610 	*irep = ire;
12611 	return (B_FALSE);
12612 }
12613 
12614 /* ARGSUSED */
12615 static boolean_t
12616 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
12617     int *ll_multicast, ipaddr_t *dstp)
12618 {
12619 	/*
12620 	 * Forward packets only if we have joined the allmulti
12621 	 * group on this interface.
12622 	 */
12623 	if (ip_g_mrouter && ill->ill_join_allmulti) {
12624 		int retval;
12625 
12626 		/*
12627 		 * Clear the indication that this may have hardware
12628 		 * checksum as we are not using it.
12629 		 */
12630 		mp->b_datap->db_struioun.cksum.flags = 0;
12631 		retval = ip_mforward(ill, ipha, mp);
12632 		/* ip_mforward updates mib variables if needed */
12633 		/* clear b_prev - used by ip_mroute_decap */
12634 		mp->b_prev = NULL;
12635 
12636 		switch (retval) {
12637 		case 0:
12638 			/*
12639 			 * pkt is okay and arrived on phyint.
12640 			 *
12641 			 * If we are running as a multicast router
12642 			 * we need to see all IGMP and/or PIM packets.
12643 			 */
12644 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
12645 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
12646 				goto done;
12647 			}
12648 			break;
12649 		case -1:
12650 			/* pkt is mal-formed, toss it */
12651 			goto drop_pkt;
12652 		case 1:
12653 			/* pkt is okay and arrived on a tunnel */
12654 			/*
12655 			 * If we are running a multicast router
12656 			 *  we need to see all igmp packets.
12657 			 */
12658 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
12659 				*dstp = INADDR_BROADCAST;
12660 				*ll_multicast = 1;
12661 				return (B_FALSE);
12662 			}
12663 
12664 			goto drop_pkt;
12665 		}
12666 	}
12667 
12668 	ILM_WALKER_HOLD(ill);
12669 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
12670 		/*
12671 		 * This might just be caused by the fact that
12672 		 * multiple IP Multicast addresses map to the same
12673 		 * link layer multicast - no need to increment counter!
12674 		 */
12675 		ILM_WALKER_RELE(ill);
12676 		freemsg(mp);
12677 		return (B_TRUE);
12678 	}
12679 	ILM_WALKER_RELE(ill);
12680 done:
12681 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
12682 	/*
12683 	 * This assumes the we deliver to all streams for multicast
12684 	 * and broadcast packets.
12685 	 */
12686 	*dstp = INADDR_BROADCAST;
12687 	*ll_multicast = 1;
12688 	return (B_FALSE);
12689 drop_pkt:
12690 	ip2dbg(("ip_rput: drop pkt\n"));
12691 	freemsg(mp);
12692 	return (B_TRUE);
12693 }
12694 
12695 static boolean_t
12696 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
12697     int *ll_multicast, mblk_t **mpp)
12698 {
12699 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
12700 	boolean_t must_copy = B_FALSE;
12701 	struct iocblk   *iocp;
12702 	ipha_t		*ipha;
12703 
12704 #define	rptr    ((uchar_t *)ipha)
12705 
12706 	first_mp = *first_mpp;
12707 	mp = *mpp;
12708 
12709 	ASSERT(first_mp == mp);
12710 
12711 	/*
12712 	 * if db_ref > 1 then copymsg and free original. Packet may be
12713 	 * changed and do not want other entity who has a reference to this
12714 	 * message to trip over the changes. This is a blind change because
12715 	 * trying to catch all places that might change packet is too
12716 	 * difficult (since it may be a module above this one)
12717 	 *
12718 	 * This corresponds to the non-fast path case. We walk down the full
12719 	 * chain in this case, and check the db_ref count of all the dblks,
12720 	 * and do a copymsg if required. It is possible that the db_ref counts
12721 	 * of the data blocks in the mblk chain can be different.
12722 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
12723 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
12724 	 * 'snoop' is running.
12725 	 */
12726 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
12727 		if (mp1->b_datap->db_ref > 1) {
12728 			must_copy = B_TRUE;
12729 			break;
12730 		}
12731 	}
12732 
12733 	if (must_copy) {
12734 		mp1 = copymsg(mp);
12735 		if (mp1 == NULL) {
12736 			for (mp1 = mp; mp1 != NULL;
12737 			    mp1 = mp1->b_cont) {
12738 				mp1->b_next = NULL;
12739 				mp1->b_prev = NULL;
12740 			}
12741 			freemsg(mp);
12742 			BUMP_MIB(&ip_mib, ipInDiscards);
12743 			return (B_TRUE);
12744 		}
12745 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
12746 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
12747 			/* Copy b_next - used in M_BREAK messages */
12748 			to_mp->b_next = from_mp->b_next;
12749 			from_mp->b_next = NULL;
12750 			/* Copy b_prev - used by ip_mroute_decap */
12751 			to_mp->b_prev = from_mp->b_prev;
12752 			from_mp->b_prev = NULL;
12753 		}
12754 		*first_mpp = first_mp = mp1;
12755 		freemsg(mp);
12756 		mp = mp1;
12757 		*mpp = mp1;
12758 	}
12759 
12760 	ipha = (ipha_t *)mp->b_rptr;
12761 
12762 	/*
12763 	 * previous code has a case for M_DATA.
12764 	 * We want to check how that happens.
12765 	 */
12766 	ASSERT(first_mp->b_datap->db_type != M_DATA);
12767 	switch (first_mp->b_datap->db_type) {
12768 	case M_PROTO:
12769 	case M_PCPROTO:
12770 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
12771 		    DL_UNITDATA_IND) {
12772 			/* Go handle anything other than data elsewhere. */
12773 			ip_rput_dlpi(q, mp);
12774 			return (B_TRUE);
12775 		}
12776 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
12777 		/* Ditch the DLPI header. */
12778 		mp1 = mp->b_cont;
12779 		ASSERT(first_mp == mp);
12780 		*first_mpp = mp1;
12781 		freeb(mp);
12782 		*mpp = mp1;
12783 		return (B_FALSE);
12784 	case M_BREAK:
12785 		/*
12786 		 * A packet arrives as M_BREAK following a cycle through
12787 		 * ip_rput, ip_newroute, ... and finally ire_add_then_send.
12788 		 * This is an IP datagram sans lower level header.
12789 		 * M_BREAK are also used to pass back in multicast packets
12790 		 * that are encapsulated with a source route.
12791 		 */
12792 		/* Ditch the M_BREAK mblk */
12793 		mp1 = mp->b_cont;
12794 		ASSERT(first_mp == mp);
12795 		*first_mpp = mp1;
12796 		freeb(mp);
12797 		mp = mp1;
12798 		mp->b_next = NULL;
12799 		*mpp = mp;
12800 		*ll_multicast = 0;
12801 		return (B_FALSE);
12802 	case M_IOCACK:
12803 		ip1dbg(("got iocack "));
12804 		iocp = (struct iocblk *)mp->b_rptr;
12805 		switch (iocp->ioc_cmd) {
12806 		case DL_IOC_HDR_INFO:
12807 			ill = (ill_t *)q->q_ptr;
12808 			ill_fastpath_ack(ill, mp);
12809 			return (B_TRUE);
12810 		case SIOCSTUNPARAM:
12811 		case OSIOCSTUNPARAM:
12812 			/* Go through qwriter_ip */
12813 			break;
12814 		case SIOCGTUNPARAM:
12815 		case OSIOCGTUNPARAM:
12816 			ip_rput_other(NULL, q, mp, NULL);
12817 			return (B_TRUE);
12818 		default:
12819 			putnext(q, mp);
12820 			return (B_TRUE);
12821 		}
12822 		/* FALLTHRU */
12823 	case M_ERROR:
12824 	case M_HANGUP:
12825 		/*
12826 		 * Since this is on the ill stream we unconditionally
12827 		 * bump up the refcount
12828 		 */
12829 		ill_refhold(ill);
12830 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
12831 		    B_FALSE);
12832 		return (B_TRUE);
12833 	case M_CTL:
12834 /* EXPORT DELETE START */
12835 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
12836 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
12837 			IPHADA_M_CTL)) {
12838 			/*
12839 			 * It's an IPsec accelerated packet.
12840 			 * Make sure that the ill from which we received the
12841 			 * packet has enabled IPsec hardware acceleration.
12842 			 */
12843 			if (!(ill->ill_capabilities &
12844 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
12845 				/* IPsec kstats: bean counter */
12846 				freemsg(mp);
12847 				return (B_TRUE);
12848 			}
12849 
12850 			/*
12851 			 * Make mp point to the mblk following the M_CTL,
12852 			 * then process according to type of mp.
12853 			 * After this processing, first_mp will point to
12854 			 * the data-attributes and mp to the pkt following
12855 			 * the M_CTL.
12856 			 */
12857 			mp = first_mp->b_cont;
12858 			if (mp == NULL) {
12859 				freemsg(first_mp);
12860 				return (B_TRUE);
12861 			}
12862 			/*
12863 			 * A Hardware Accelerated packet can only be M_DATA
12864 			 * ESP or AH packet.
12865 			 */
12866 			if (mp->b_datap->db_type != M_DATA) {
12867 				/* non-M_DATA IPsec accelerated packet */
12868 				IPSECHW_DEBUG(IPSECHW_PKT,
12869 				    ("non-M_DATA IPsec accelerated pkt\n"));
12870 				freemsg(first_mp);
12871 				return (B_TRUE);
12872 			}
12873 			ipha = (ipha_t *)mp->b_rptr;
12874 			if (ipha->ipha_protocol != IPPROTO_AH &&
12875 			    ipha->ipha_protocol != IPPROTO_ESP) {
12876 				IPSECHW_DEBUG(IPSECHW_PKT,
12877 				    ("non-M_DATA IPsec accelerated pkt\n"));
12878 				freemsg(first_mp);
12879 				return (B_TRUE);
12880 			}
12881 			*mpp = mp;
12882 			return (B_FALSE);
12883 		}
12884 /* EXPORT DELETE END */
12885 		putnext(q, mp);
12886 		return (B_TRUE);
12887 	case M_FLUSH:
12888 		if (*mp->b_rptr & FLUSHW) {
12889 			*mp->b_rptr &= ~FLUSHR;
12890 			qreply(q, mp);
12891 			return (B_TRUE);
12892 		}
12893 		freemsg(mp);
12894 		return (B_TRUE);
12895 	case M_IOCNAK:
12896 		ip1dbg(("got iocnak "));
12897 		iocp = (struct iocblk *)mp->b_rptr;
12898 		switch (iocp->ioc_cmd) {
12899 		case DL_IOC_HDR_INFO:
12900 		case SIOCSTUNPARAM:
12901 		case OSIOCSTUNPARAM:
12902 			/*
12903 			 * Since this is on the ill stream we unconditionally
12904 			 * bump up the refcount
12905 			 */
12906 			ill_refhold(ill);
12907 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
12908 			    CUR_OP, B_FALSE);
12909 			return (B_TRUE);
12910 		case SIOCGTUNPARAM:
12911 		case OSIOCGTUNPARAM:
12912 			ip_rput_other(NULL, q, mp, NULL);
12913 			return (B_TRUE);
12914 		default:
12915 			break;
12916 		}
12917 		/* FALLTHRU */
12918 	default:
12919 		putnext(q, mp);
12920 		return (B_TRUE);
12921 	}
12922 }
12923 
12924 /* Read side put procedure.  Packets coming from the wire arrive here. */
12925 void
12926 ip_rput(queue_t *q, mblk_t *mp)
12927 {
12928 	ill_t		*ill;
12929 
12930 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
12931 
12932 	ill = (ill_t *)q->q_ptr;
12933 
12934 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
12935 		union DL_primitives *dl;
12936 
12937 		/*
12938 		 * Things are opening or closing. Only accept DLPI control
12939 		 * messages. In the open case, the ill->ill_ipif has not yet
12940 		 * been created. In the close case, things hanging off the
12941 		 * ill could have been freed already. In either case it
12942 		 * may not be safe to proceed further.
12943 		 */
12944 
12945 		dl = (union DL_primitives *)mp->b_rptr;
12946 		if ((mp->b_datap->db_type != M_PCPROTO) ||
12947 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
12948 			/*
12949 			 * Also SIOC[GS]TUN* ioctls can come here.
12950 			 */
12951 			ip_ioctl_freemsg(mp);
12952 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
12953 			    "ip_input_end: q %p (%S)", q, "uninit");
12954 			return;
12955 		}
12956 	}
12957 
12958 	/*
12959 	 * if db_ref > 1 then copymsg and free original. Packet may be
12960 	 * changed and we do not want the other entity who has a reference to
12961 	 * this message to trip over the changes. This is a blind change because
12962 	 * trying to catch all places that might change the packet is too
12963 	 * difficult.
12964 	 *
12965 	 * This corresponds to the fast path case, where we have a chain of
12966 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
12967 	 * in the mblk chain. There doesn't seem to be a reason why a device
12968 	 * driver would send up data with varying db_ref counts in the mblk
12969 	 * chain. In any case the Fast path is a private interface, and our
12970 	 * drivers don't do such a thing. Given the above assumption, there is
12971 	 * no need to walk down the entire mblk chain (which could have a
12972 	 * potential performance problem)
12973 	 */
12974 	if (mp->b_datap->db_ref > 1) {
12975 		mblk_t  *mp1;
12976 		boolean_t adjusted = B_FALSE;
12977 		IP_STAT(ip_db_ref);
12978 
12979 		/*
12980 		 * The IP_RECVSLLA option depends on having the link layer
12981 		 * header. First check that:
12982 		 * a> the underlying device is of type ether, since this
12983 		 * option is currently supported only over ethernet.
12984 		 * b> there is enough room to copy over the link layer header.
12985 		 *
12986 		 * Once the checks are done, adjust rptr so that the link layer
12987 		 * header will be copied via copymsg. Note that, IFT_ETHER may
12988 		 * be returned by some non-ethernet drivers but in this case the
12989 		 * second check will fail.
12990 		 */
12991 		if (ill->ill_type == IFT_ETHER &&
12992 		    (mp->b_rptr - mp->b_datap->db_base) >=
12993 		    sizeof (struct ether_header)) {
12994 			mp->b_rptr -= sizeof (struct ether_header);
12995 			adjusted = B_TRUE;
12996 		}
12997 		mp1 = copymsg(mp);
12998 		if (mp1 == NULL) {
12999 			/* Clear b_next - used in M_BREAK messages */
13000 			mp->b_next = NULL;
13001 			/* clear b_prev - used by ip_mroute_decap */
13002 			mp->b_prev = NULL;
13003 			freemsg(mp);
13004 			BUMP_MIB(&ip_mib, ipInDiscards);
13005 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13006 			    "ip_rput_end: q %p (%S)", q, "copymsg");
13007 			return;
13008 		}
13009 		if (adjusted) {
13010 			/*
13011 			 * Copy is done. Restore the pointer in the _new_ mblk
13012 			 */
13013 			mp1->b_rptr += sizeof (struct ether_header);
13014 		}
13015 		/* Copy b_next - used in M_BREAK messages */
13016 		mp1->b_next = mp->b_next;
13017 		mp->b_next = NULL;
13018 		/* Copy b_prev - used by ip_mroute_decap */
13019 		mp1->b_prev = mp->b_prev;
13020 		mp->b_prev = NULL;
13021 		freemsg(mp);
13022 		mp = mp1;
13023 	}
13024 
13025 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13026 	    "ip_rput_end: q %p (%S)", q, "end");
13027 
13028 	ip_input(ill, NULL, mp, 0);
13029 }
13030 
13031 /*
13032  * Direct read side procedure capable of dealing with chains. GLDv3 based
13033  * drivers call this function directly with mblk chains while STREAMS
13034  * read side procedure ip_rput() calls this for single packet with ip_ring
13035  * set to NULL to process one packet at a time.
13036  *
13037  * The ill will always be valid if this function is called directly from
13038  * the driver.
13039  */
13040 /*ARGSUSED*/
13041 void
13042 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain, size_t hdrlen)
13043 {
13044 	ipaddr_t		dst;
13045 	ire_t			*ire;
13046 	ipha_t			*ipha;
13047 	uint_t			pkt_len;
13048 	ssize_t			len;
13049 	uint_t			opt_len;
13050 	int			ll_multicast;
13051 	int			cgtp_flt_pkt;
13052 	queue_t			*q = ill->ill_rq;
13053 	squeue_t		*curr_sqp = NULL;
13054 	mblk_t 			*head = NULL;
13055 	mblk_t			*tail = NULL;
13056 	mblk_t			*first_mp;
13057 	mblk_t 			*mp;
13058 	int			cnt = 0;
13059 
13060 	ASSERT(mp_chain != NULL);
13061 	ASSERT(ill != NULL);
13062 
13063 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
13064 
13065 #define	rptr	((uchar_t *)ipha)
13066 
13067 	while (mp_chain != NULL) {
13068 		first_mp = mp = mp_chain;
13069 		mp_chain = mp_chain->b_next;
13070 		mp->b_next = NULL;
13071 		ll_multicast = 0;
13072 		ire = NULL;
13073 
13074 		/*
13075 		 * ip_input fast path
13076 		 */
13077 
13078 		/* mblk type is not M_DATA */
13079 		if (mp->b_datap->db_type != M_DATA) {
13080 			if (ip_rput_process_notdata(q, &first_mp, ill,
13081 			    &ll_multicast, &mp))
13082 				continue;
13083 		}
13084 
13085 		ASSERT(mp->b_datap->db_type == M_DATA);
13086 		ASSERT(mp->b_datap->db_ref == 1);
13087 
13088 		/*
13089 		 * Invoke the CGTP (multirouting) filtering module to process
13090 		 * the incoming packet. Packets identified as duplicates
13091 		 * must be discarded. Filtering is active only if the
13092 		 * the ip_cgtp_filter ndd variable is non-zero.
13093 		 */
13094 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
13095 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL)) {
13096 			cgtp_flt_pkt =
13097 			    ip_cgtp_filter_ops->cfo_filter_fp(q, mp);
13098 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
13099 				freemsg(first_mp);
13100 				continue;
13101 			}
13102 		}
13103 
13104 		ipha = (ipha_t *)mp->b_rptr;
13105 		len = mp->b_wptr - rptr;
13106 
13107 		BUMP_MIB(&ip_mib, ipInReceives);
13108 
13109 		/*
13110 		 * IP header ptr not aligned?
13111 		 * OR IP header not complete in first mblk
13112 		 */
13113 		if (!OK_32PTR(rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13114 			if (!ip_check_and_align_header(q, mp))
13115 				continue;
13116 			ipha = (ipha_t *)mp->b_rptr;
13117 			len = mp->b_wptr - rptr;
13118 		}
13119 
13120 		/* multiple mblk or too short */
13121 		pkt_len = ntohs(ipha->ipha_length);
13122 		len -= pkt_len;
13123 		if (len != 0) {
13124 			/*
13125 			 * Make sure we have data length consistent
13126 			 * with the IP header.
13127 			 */
13128 			if (mp->b_cont == NULL) {
13129 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
13130 					BUMP_MIB(&ip_mib, ipInHdrErrors);
13131 					ip2dbg(("ip_input: drop pkt\n"));
13132 					freemsg(mp);
13133 					continue;
13134 				}
13135 				mp->b_wptr = rptr + pkt_len;
13136 			} else if (len += msgdsize(mp->b_cont)) {
13137 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
13138 					BUMP_MIB(&ip_mib, ipInHdrErrors);
13139 					ip2dbg(("ip_input: drop pkt\n"));
13140 					freemsg(mp);
13141 					continue;
13142 				}
13143 				(void) adjmsg(mp, -len);
13144 				IP_STAT(ip_multimblk3);
13145 			}
13146 		}
13147 
13148 		if (ip_loopback_src_or_dst(ipha, ill)) {
13149 			ip2dbg(("ip_input: drop pkt\n"));
13150 			freemsg(mp);
13151 			continue;
13152 		}
13153 
13154 		opt_len = ipha->ipha_version_and_hdr_length -
13155 		    IP_SIMPLE_HDR_VERSION;
13156 		/* IP version bad or there are IP options */
13157 		if (opt_len) {
13158 			if (len != 0)
13159 				IP_STAT(ip_multimblk4);
13160 			else
13161 				IP_STAT(ip_ipoptions);
13162 			if (!ip_rput_multimblk_ipoptions(q, mp, &ipha, &dst))
13163 				continue;
13164 		} else {
13165 			dst = ipha->ipha_dst;
13166 		}
13167 
13168 		/*
13169 		 * If rsvpd is running, let RSVP daemon handle its processing
13170 		 * and forwarding of RSVP multicast/unicast packets.
13171 		 * If rsvpd is not running but mrouted is running, RSVP
13172 		 * multicast packets are forwarded as multicast traffic
13173 		 * and RSVP unicast packets are forwarded by unicast router.
13174 		 * If neither rsvpd nor mrouted is running, RSVP multicast
13175 		 * packets are not forwarded, but the unicast packets are
13176 		 * forwarded like unicast traffic.
13177 		 */
13178 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
13179 		    ipcl_proto_search(IPPROTO_RSVP) != NULL) {
13180 			/* RSVP packet and rsvpd running. Treat as ours */
13181 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
13182 			/*
13183 			 * This assumes that we deliver to all streams for
13184 			 * multicast and broadcast packets.
13185 			 * We have to force ll_multicast to 1 to handle the
13186 			 * M_DATA messages passed in from ip_mroute_decap.
13187 			 */
13188 			dst = INADDR_BROADCAST;
13189 			ll_multicast = 1;
13190 		} else if (CLASSD(dst)) {
13191 			/* packet is multicast */
13192 			mp->b_next = NULL;
13193 			if (ip_rput_process_multicast(q, mp, ill, ipha,
13194 			    &ll_multicast, &dst))
13195 				continue;
13196 		}
13197 
13198 
13199 		/*
13200 		 * Check if the packet is coming from the Mobile IP
13201 		 * forward tunnel interface
13202 		 */
13203 		if (ill->ill_srcif_refcnt > 0) {
13204 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
13205 			    NULL, ill, MATCH_IRE_TYPE);
13206 			if (ire != NULL && ire->ire_dlureq_mp == NULL &&
13207 			    ire->ire_ipif->ipif_net_type ==
13208 			    IRE_IF_RESOLVER) {
13209 				/* We need to resolve the link layer info */
13210 				ire_refrele(ire);
13211 				ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
13212 				    ll_multicast, dst);
13213 				continue;
13214 			}
13215 		}
13216 
13217 		if (ire == NULL)
13218 			ire = ire_cache_lookup(dst, ALL_ZONES);
13219 
13220 		/*
13221 		 * If mipagent is running and reverse tunnel is created as per
13222 		 * mobile node request, then any packet coming through the
13223 		 * incoming interface from the mobile-node, should be reverse
13224 		 * tunneled to it's home agent except those that are destined
13225 		 * to foreign agent only.
13226 		 * This needs source address based ire lookup. The routing
13227 		 * entries for source address based lookup are only created by
13228 		 * mipagent program only when a reverse tunnel is created.
13229 		 * Reference : RFC2002, RFC2344
13230 		 */
13231 		if (ill->ill_mrtun_refcnt > 0) {
13232 			ipaddr_t	srcaddr;
13233 			ire_t		*tmp_ire;
13234 
13235 			tmp_ire = ire;	/* Save, we might need it later */
13236 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
13237 			    ire->ire_type != IRE_BROADCAST)) {
13238 				srcaddr = ipha->ipha_src;
13239 				ire = ire_mrtun_lookup(srcaddr, ill);
13240 				if (ire != NULL) {
13241 					/*
13242 					 * Should not be getting iphada packet
13243 					 * here. we should only get those for
13244 					 * IRE_LOCAL traffic, excluded above.
13245 					 * Fail-safe (drop packet) in the event
13246 					 * hardware is misbehaving.
13247 					 */
13248 					if (first_mp != mp) {
13249 						/* IPsec KSTATS: beancount me */
13250 						freemsg(first_mp);
13251 					} else {
13252 						/*
13253 						 * This packet must be forwarded
13254 						 * to Reverse Tunnel
13255 						 */
13256 						ip_mrtun_forward(ire, ill, mp);
13257 					}
13258 					ire_refrele(ire);
13259 					if (tmp_ire != NULL)
13260 						ire_refrele(tmp_ire);
13261 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13262 					    "ip_input_end: q %p (%S)",
13263 					    q, "uninit");
13264 					continue;
13265 				}
13266 			}
13267 			/*
13268 			 * If this packet is from a non-mobilenode  or a
13269 			 * mobile-node which does not request reverse
13270 			 * tunnel service
13271 			 */
13272 			ire = tmp_ire;
13273 		}
13274 
13275 
13276 		/*
13277 		 * If we reach here that means the incoming packet satisfies
13278 		 * one of the following conditions:
13279 		 *   - packet is from a mobile node which does not request
13280 		 *	reverse tunnel
13281 		 *   - packet is from a non-mobile node, which is the most
13282 		 *	common case
13283 		 *   - packet is from a reverse tunnel enabled mobile node
13284 		 *	and destined to foreign agent only
13285 		 */
13286 
13287 		if (ire == NULL) {
13288 			/*
13289 			 * No IRE for this destination, so it can't be for us.
13290 			 * Unless we are forwarding, drop the packet.
13291 			 * We have to let source routed packets through
13292 			 * since we don't yet know if they are 'ping -l'
13293 			 * packets i.e. if they will go out over the
13294 			 * same interface as they came in on.
13295 			 */
13296 			ip_rput_noire(q, NULL, mp, ll_multicast, dst);
13297 			continue;
13298 		}
13299 
13300 		/* broadcast? */
13301 		if (ire->ire_type == IRE_BROADCAST) {
13302 			if (ip_rput_process_broadcast(&q, mp, &ire, ipha, ill,
13303 			    dst, cgtp_flt_pkt, ll_multicast)) {
13304 				continue;
13305 			}
13306 		} else if (ire->ire_stq != NULL) {
13307 			/* fowarding? */
13308 			ip_rput_process_forward(q, mp, ire, ipha, ill,
13309 			    ll_multicast);
13310 			continue;
13311 		}
13312 
13313 		/* packet not for us */
13314 		if (ire->ire_rfq != q) {
13315 			if (ip_rput_notforus(&q, mp, ire, ill)) {
13316 				continue;
13317 			}
13318 		}
13319 
13320 		switch (ipha->ipha_protocol) {
13321 		case IPPROTO_TCP:
13322 			ASSERT(first_mp == mp);
13323 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
13324 				mp, 0, q, ip_ring)) != NULL) {
13325 				if (curr_sqp == NULL) {
13326 					curr_sqp = GET_SQUEUE(mp);
13327 					ASSERT(cnt == 0);
13328 					cnt++;
13329 					head = tail = mp;
13330 				} else if (curr_sqp == GET_SQUEUE(mp)) {
13331 					ASSERT(tail != NULL);
13332 					cnt++;
13333 					tail->b_next = mp;
13334 					tail = mp;
13335 				} else {
13336 					/*
13337 					 * A different squeue. Send the
13338 					 * chain for the previous squeue on
13339 					 * its way. This shouldn't happen
13340 					 * often unless interrupt binding
13341 					 * changes.
13342 					 */
13343 					IP_STAT(ip_input_multi_squeue);
13344 					squeue_enter_chain(curr_sqp, head,
13345 					    tail, cnt, SQTAG_IP_INPUT);
13346 					curr_sqp = GET_SQUEUE(mp);
13347 					head = mp;
13348 					tail = mp;
13349 					cnt = 1;
13350 				}
13351 			}
13352 			IRE_REFRELE(ire);
13353 			continue;
13354 		case IPPROTO_UDP:
13355 			ASSERT(first_mp == mp);
13356 			ip_udp_input(q, mp, ipha, ire, ill);
13357 			IRE_REFRELE(ire);
13358 			continue;
13359 		case IPPROTO_SCTP:
13360 			ASSERT(first_mp == mp);
13361 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
13362 			    q, dst);
13363 			continue;
13364 		default:
13365 			ip_proto_input(q, first_mp, ipha, ire, ill);
13366 			IRE_REFRELE(ire);
13367 			continue;
13368 		}
13369 	}
13370 
13371 	if (head != NULL)
13372 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
13373 
13374 	/*
13375 	 * This code is there just to make netperf/ttcp look good.
13376 	 *
13377 	 * Its possible that after being in polling mode (and having cleared
13378 	 * the backlog), squeues have turned the interrupt frequency higher
13379 	 * to improve latency at the expense of more CPU utilization (less
13380 	 * packets per interrupts or more number of interrupts). Workloads
13381 	 * like ttcp/netperf do manage to tickle polling once in a while
13382 	 * but for the remaining time, stay in higher interrupt mode since
13383 	 * their packet arrival rate is pretty uniform and this shows up
13384 	 * as higher CPU utilization. Since people care about CPU utilization
13385 	 * while running netperf/ttcp, turn the interrupt frequency back to
13386 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
13387 	 */
13388 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
13389 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
13390 			ip_ring->rr_poll_state &= ~ILL_POLLING;
13391 			ip_ring->rr_blank(ip_ring->rr_handle,
13392 			    ip_ring->rr_normal_blank_time,
13393 			    ip_ring->rr_normal_pkt_cnt);
13394 		}
13395 	}
13396 
13397 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13398 	    "ip_input_end: q %p (%S)", q, "end");
13399 #undef	rptr
13400 }
13401 
13402 static void
13403 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
13404     t_uscalar_t err)
13405 {
13406 	if (dl_err == DL_SYSERR) {
13407 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
13408 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
13409 		    ill->ill_name, dlpi_prim_str(prim), err);
13410 		return;
13411 	}
13412 
13413 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
13414 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
13415 	    dlpi_err_str(dl_err));
13416 }
13417 
13418 /*
13419  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
13420  * than DL_UNITDATA_IND messages. If we need to process this message
13421  * exclusively, we call qwriter_ip, in which case we also need to call
13422  * ill_refhold before that, since qwriter_ip does an ill_refrele.
13423  */
13424 void
13425 ip_rput_dlpi(queue_t *q, mblk_t *mp)
13426 {
13427 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
13428 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
13429 	ill_t		*ill;
13430 
13431 	ip1dbg(("ip_rput_dlpi"));
13432 	ill = (ill_t *)q->q_ptr;
13433 	switch (dloa->dl_primitive) {
13434 	case DL_ERROR_ACK:
13435 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
13436 		    "%s (0x%x), unix %u\n", ill->ill_name,
13437 		    dlpi_prim_str(dlea->dl_error_primitive),
13438 		    dlea->dl_error_primitive,
13439 		    dlpi_err_str(dlea->dl_errno),
13440 		    dlea->dl_errno,
13441 		    dlea->dl_unix_errno));
13442 		switch (dlea->dl_error_primitive) {
13443 		case DL_NOTIFY_REQ:
13444 		case DL_UNBIND_REQ:
13445 		case DL_ATTACH_REQ:
13446 		case DL_DETACH_REQ:
13447 		case DL_INFO_REQ:
13448 		case DL_BIND_REQ:
13449 		case DL_ENABMULTI_REQ:
13450 		case DL_PHYS_ADDR_REQ:
13451 		case DL_CAPABILITY_REQ:
13452 		case DL_CONTROL_REQ:
13453 			/*
13454 			 * Refhold the ill to match qwriter_ip which does a
13455 			 * refrele. Since this is on the ill stream we
13456 			 * unconditionally bump up the refcount without
13457 			 * checking for ILL_CAN_LOOKUP
13458 			 */
13459 			ill_refhold(ill);
13460 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13461 			    CUR_OP, B_FALSE);
13462 			return;
13463 		case DL_DISABMULTI_REQ:
13464 			freemsg(mp);	/* Don't want to pass this up */
13465 			return;
13466 		default:
13467 			break;
13468 		}
13469 		ip_dlpi_error(ill, dlea->dl_error_primitive,
13470 		    dlea->dl_errno, dlea->dl_unix_errno);
13471 		freemsg(mp);
13472 		return;
13473 	case DL_INFO_ACK:
13474 	case DL_BIND_ACK:
13475 	case DL_PHYS_ADDR_ACK:
13476 	case DL_NOTIFY_ACK:
13477 	case DL_CAPABILITY_ACK:
13478 	case DL_CONTROL_ACK:
13479 		/*
13480 		 * Refhold the ill to match qwriter_ip which does a refrele
13481 		 * Since this is on the ill stream we unconditionally
13482 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
13483 		 */
13484 		ill_refhold(ill);
13485 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13486 		    CUR_OP, B_FALSE);
13487 		return;
13488 	case DL_NOTIFY_IND:
13489 		ill_refhold(ill);
13490 		/*
13491 		 * The DL_NOTIFY_IND is an asynchronous message that has no
13492 		 * relation to the current ioctl in progress (if any). Hence we
13493 		 * pass in NEW_OP in this case.
13494 		 */
13495 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13496 		    NEW_OP, B_FALSE);
13497 		return;
13498 	case DL_OK_ACK:
13499 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
13500 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
13501 		switch (dloa->dl_correct_primitive) {
13502 		case DL_UNBIND_REQ:
13503 			mutex_enter(&ill->ill_lock);
13504 			ill->ill_state_flags |= ILL_DL_UNBIND_DONE;
13505 			cv_signal(&ill->ill_cv);
13506 			mutex_exit(&ill->ill_lock);
13507 			/* FALLTHRU */
13508 		case DL_ATTACH_REQ:
13509 		case DL_DETACH_REQ:
13510 			/*
13511 			 * Refhold the ill to match qwriter_ip which does a
13512 			 * refrele. Since this is on the ill stream we
13513 			 * unconditionally bump up the refcount
13514 			 */
13515 			ill_refhold(ill);
13516 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13517 			    CUR_OP, B_FALSE);
13518 			return;
13519 		case DL_ENABMULTI_REQ:
13520 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
13521 				ill->ill_dlpi_multicast_state = IDMS_OK;
13522 			break;
13523 
13524 		}
13525 		break;
13526 	default:
13527 		break;
13528 	}
13529 	freemsg(mp);
13530 }
13531 
13532 /*
13533  * This function is used to free a message that has gone through
13534  * mi_copyin processing which modifies the M_IOCTL mblk's b_next
13535  * and b_prev pointers. We use this function to set b_next/b_prev
13536  * to NULL and free them.
13537  */
13538 void
13539 ip_ioctl_freemsg(mblk_t *mp)
13540 {
13541 	mblk_t	*bp = mp;
13542 
13543 	for (; bp != NULL; bp = bp->b_cont) {
13544 		bp->b_prev = NULL;
13545 		bp->b_next = NULL;
13546 	}
13547 	freemsg(mp);
13548 }
13549 
13550 /*
13551  * Handling of DLPI messages that require exclusive access to the ipsq.
13552  *
13553  * Need to do ill_pending_mp_release on ioctl completion, which could
13554  * happen here. (along with mi_copy_done)
13555  */
13556 /* ARGSUSED */
13557 static void
13558 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
13559 {
13560 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
13561 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
13562 	int		err = 0;
13563 	ill_t		*ill;
13564 	ipif_t		*ipif = NULL;
13565 	mblk_t		*mp1 = NULL;
13566 	conn_t		*connp = NULL;
13567 	t_uscalar_t	physaddr_req;
13568 	mblk_t		*mp_hw;
13569 	union DL_primitives *dlp;
13570 	boolean_t	success;
13571 	boolean_t	ioctl_aborted = B_FALSE;
13572 	boolean_t	log = B_TRUE;
13573 
13574 	ip1dbg(("ip_rput_dlpi_writer .."));
13575 	ill = (ill_t *)q->q_ptr;
13576 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
13577 
13578 	ASSERT(IAM_WRITER_ILL(ill));
13579 
13580 	/*
13581 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
13582 	 * both are null or non-null. However we can assert that only
13583 	 * after grabbing the ipsq_lock. So we don't make any assertion
13584 	 * here and in other places in the code.
13585 	 */
13586 	ipif = ipsq->ipsq_pending_ipif;
13587 	/*
13588 	 * The current ioctl could have been aborted by the user and a new
13589 	 * ioctl to bring up another ill could have started. We could still
13590 	 * get a response from the driver later.
13591 	 */
13592 	if (ipif != NULL && ipif->ipif_ill != ill)
13593 		ioctl_aborted = B_TRUE;
13594 
13595 	switch (dloa->dl_primitive) {
13596 	case DL_ERROR_ACK:
13597 		switch (dlea->dl_error_primitive) {
13598 		case DL_UNBIND_REQ:
13599 		case DL_ATTACH_REQ:
13600 		case DL_DETACH_REQ:
13601 		case DL_INFO_REQ:
13602 			ill_dlpi_done(ill, dlea->dl_error_primitive);
13603 			break;
13604 		case DL_NOTIFY_REQ:
13605 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
13606 			log = B_FALSE;
13607 			break;
13608 		case DL_PHYS_ADDR_REQ:
13609 			/*
13610 			 * For IPv6 only, there are two additional
13611 			 * phys_addr_req's sent to the driver to get the
13612 			 * IPv6 token and lla. This allows IP to acquire
13613 			 * the hardware address format for a given interface
13614 			 * without having built in knowledge of the hardware
13615 			 * address. ill_phys_addr_pend keeps track of the last
13616 			 * DL_PAR sent so we know which response we are
13617 			 * dealing with. ill_dlpi_done will update
13618 			 * ill_phys_addr_pend when it sends the next req.
13619 			 * We don't complete the IOCTL until all three DL_PARs
13620 			 * have been attempted, so set *_len to 0 and break.
13621 			 */
13622 			physaddr_req = ill->ill_phys_addr_pend;
13623 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
13624 			if (physaddr_req == DL_IPV6_TOKEN) {
13625 				ill->ill_token_length = 0;
13626 				log = B_FALSE;
13627 				break;
13628 			} else if (physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
13629 				ill->ill_nd_lla_len = 0;
13630 				log = B_FALSE;
13631 				break;
13632 			}
13633 			/*
13634 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
13635 			 * We presumably have an IOCTL hanging out waiting
13636 			 * for completion. Find it and complete the IOCTL
13637 			 * with the error noted.
13638 			 * However, ill_dl_phys was called on an ill queue
13639 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
13640 			 * set. But the ioctl is known to be pending on ill_wq.
13641 			 */
13642 			if (!ill->ill_ifname_pending)
13643 				break;
13644 			ill->ill_ifname_pending = 0;
13645 			if (!ioctl_aborted)
13646 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
13647 			if (mp1 != NULL) {
13648 				/*
13649 				 * This operation (SIOCSLIFNAME) must have
13650 				 * happened on the ill. Assert there is no conn
13651 				 */
13652 				ASSERT(connp == NULL);
13653 				q = ill->ill_wq;
13654 			}
13655 			break;
13656 		case DL_BIND_REQ:
13657 			ill_dlpi_done(ill, DL_BIND_REQ);
13658 			if (ill->ill_ifname_pending)
13659 				break;
13660 			/*
13661 			 * Something went wrong with the bind.  We presumably
13662 			 * have an IOCTL hanging out waiting for completion.
13663 			 * Find it, take down the interface that was coming
13664 			 * up, and complete the IOCTL with the error noted.
13665 			 */
13666 			if (!ioctl_aborted)
13667 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
13668 			if (mp1 != NULL) {
13669 				/*
13670 				 * This operation (SIOCSLIFFLAGS) must have
13671 				 * happened from a conn.
13672 				 */
13673 				ASSERT(connp != NULL);
13674 				q = CONNP_TO_WQ(connp);
13675 				if (ill->ill_move_in_progress) {
13676 					ILL_CLEAR_MOVE(ill);
13677 				}
13678 				(void) ipif_down(ipif, NULL, NULL);
13679 				/* error is set below the switch */
13680 			}
13681 			break;
13682 		case DL_ENABMULTI_REQ:
13683 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
13684 
13685 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
13686 				ill->ill_dlpi_multicast_state = IDMS_FAILED;
13687 			if (ill->ill_dlpi_multicast_state == IDMS_FAILED) {
13688 				ipif_t *ipif;
13689 
13690 				log = B_FALSE;
13691 				printf("ip: joining multicasts failed (%d)"
13692 				    " on %s - will use link layer "
13693 				    "broadcasts for multicast\n",
13694 				    dlea->dl_errno, ill->ill_name);
13695 
13696 				/*
13697 				 * Set up the multicast mapping alone.
13698 				 * writer, so ok to access ill->ill_ipif
13699 				 * without any lock.
13700 				 */
13701 				ipif = ill->ill_ipif;
13702 				mutex_enter(&ill->ill_phyint->phyint_lock);
13703 				ill->ill_phyint->phyint_flags |=
13704 				    PHYI_MULTI_BCAST;
13705 				mutex_exit(&ill->ill_phyint->phyint_lock);
13706 
13707 				if (!ill->ill_isv6) {
13708 					(void) ipif_arp_setup_multicast(ipif,
13709 					    NULL);
13710 				} else {
13711 					(void) ipif_ndp_setup_multicast(ipif,
13712 					    NULL);
13713 				}
13714 			}
13715 			freemsg(mp);	/* Don't want to pass this up */
13716 			return;
13717 		case DL_CAPABILITY_REQ:
13718 		case DL_CONTROL_REQ:
13719 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
13720 			    "DL_CAPABILITY/CONTROL REQ\n"));
13721 			ill_dlpi_done(ill, dlea->dl_error_primitive);
13722 			ill->ill_capab_state = IDMS_FAILED;
13723 			freemsg(mp);
13724 			return;
13725 		}
13726 		/*
13727 		 * Note the error for IOCTL completion (mp1 is set when
13728 		 * ready to complete ioctl). If ill_ifname_pending_err is
13729 		 * set, an error occured during plumbing (ill_ifname_pending),
13730 		 * so we want to report that error.
13731 		 *
13732 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
13733 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
13734 		 * expected to get errack'd if the driver doesn't support
13735 		 * these flags (e.g. ethernet). log will be set to B_FALSE
13736 		 * if these error conditions are encountered.
13737 		 */
13738 		if (mp1 != NULL) {
13739 			if (ill->ill_ifname_pending_err != 0)  {
13740 				err = ill->ill_ifname_pending_err;
13741 				ill->ill_ifname_pending_err = 0;
13742 			} else {
13743 				err = dlea->dl_unix_errno ?
13744 				    dlea->dl_unix_errno : ENXIO;
13745 			}
13746 		/*
13747 		 * If we're plumbing an interface and an error hasn't already
13748 		 * been saved, set ill_ifname_pending_err to the error passed
13749 		 * up. Ignore the error if log is B_FALSE (see comment above).
13750 		 */
13751 		} else if (log && ill->ill_ifname_pending &&
13752 		    ill->ill_ifname_pending_err == 0) {
13753 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
13754 			dlea->dl_unix_errno : ENXIO;
13755 		}
13756 
13757 		if (log)
13758 			ip_dlpi_error(ill, dlea->dl_error_primitive,
13759 			    dlea->dl_errno, dlea->dl_unix_errno);
13760 		break;
13761 	case DL_CAPABILITY_ACK: {
13762 		boolean_t reneg_flag = B_FALSE;
13763 		/* Call a routine to handle this one. */
13764 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
13765 		/*
13766 		 * Check if the ACK is due to renegotiation case since we
13767 		 * will need to send a new CAPABILITY_REQ later.
13768 		 */
13769 		if (ill->ill_capab_state == IDMS_RENEG) {
13770 			/* This is the ack for a renogiation case */
13771 			reneg_flag = B_TRUE;
13772 			ill->ill_capab_state = IDMS_UNKNOWN;
13773 		}
13774 		ill_capability_ack(ill, mp);
13775 		if (reneg_flag)
13776 			ill_capability_probe(ill);
13777 		break;
13778 	}
13779 	case DL_CONTROL_ACK:
13780 		/* We treat all of these as "fire and forget" */
13781 		ill_dlpi_done(ill, DL_CONTROL_REQ);
13782 		break;
13783 	case DL_INFO_ACK:
13784 		/* Call a routine to handle this one. */
13785 		ill_dlpi_done(ill, DL_INFO_REQ);
13786 		ip_ll_subnet_defaults(ill, mp);
13787 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
13788 		return;
13789 	case DL_BIND_ACK:
13790 		/*
13791 		 * We should have an IOCTL waiting on this unless
13792 		 * sent by ill_dl_phys, in which case just return
13793 		 */
13794 		ill_dlpi_done(ill, DL_BIND_REQ);
13795 		if (ill->ill_ifname_pending)
13796 			break;
13797 
13798 		if (!ioctl_aborted)
13799 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
13800 		if (mp1 == NULL)
13801 			break;
13802 		ASSERT(connp != NULL);
13803 		q = CONNP_TO_WQ(connp);
13804 
13805 		/*
13806 		 * We are exclusive. So nothing can change even after
13807 		 * we get the pending mp. If need be we can put it back
13808 		 * and restart, as in calling ipif_arp_up()  below.
13809 		 */
13810 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
13811 
13812 		mutex_enter(&ill->ill_lock);
13813 		ill->ill_dl_up = 1;
13814 		mutex_exit(&ill->ill_lock);
13815 
13816 		/*
13817 		 * Now bring up the resolver, when that is
13818 		 * done we'll create IREs and we are done.
13819 		 */
13820 		if (ill->ill_isv6) {
13821 			/*
13822 			 * v6 interfaces.
13823 			 * Unlike ARP which has to do another bind
13824 			 * and attach, once we get here we are
13825 			 * done withh NDP. Except in the case of
13826 			 * ILLF_XRESOLV, in which case we send an
13827 			 * AR_INTERFACE_UP to the external resolver.
13828 			 * If all goes well, the ioctl will complete
13829 			 * in ip_rput(). If there's an error, we
13830 			 * complete it here.
13831 			 */
13832 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr,
13833 			    B_FALSE);
13834 			if (err == 0) {
13835 				if (ill->ill_flags & ILLF_XRESOLV) {
13836 					mutex_enter(&connp->conn_lock);
13837 					mutex_enter(&ill->ill_lock);
13838 					success = ipsq_pending_mp_add(
13839 					    connp, ipif, q, mp1, 0);
13840 					mutex_exit(&ill->ill_lock);
13841 					mutex_exit(&connp->conn_lock);
13842 					if (success) {
13843 						err = ipif_resolver_up(ipif,
13844 						    B_FALSE);
13845 						if (err == EINPROGRESS) {
13846 							freemsg(mp);
13847 							return;
13848 						}
13849 						ASSERT(err != 0);
13850 						mp1 = ipsq_pending_mp_get(ipsq,
13851 						    &connp);
13852 						ASSERT(mp1 != NULL);
13853 					} else {
13854 						/* conn has started closing */
13855 						err = EINTR;
13856 					}
13857 				} else { /* Non XRESOLV interface */
13858 					err = ipif_up_done_v6(ipif);
13859 				}
13860 			}
13861 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
13862 			/*
13863 			 * ARP and other v4 external resolvers.
13864 			 * Leave the pending mblk intact so that
13865 			 * the ioctl completes in ip_rput().
13866 			 */
13867 			mutex_enter(&connp->conn_lock);
13868 			mutex_enter(&ill->ill_lock);
13869 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
13870 			mutex_exit(&ill->ill_lock);
13871 			mutex_exit(&connp->conn_lock);
13872 			if (success) {
13873 				err = ipif_resolver_up(ipif, B_FALSE);
13874 				if (err == EINPROGRESS) {
13875 					freemsg(mp);
13876 					return;
13877 				}
13878 				ASSERT(err != 0);
13879 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
13880 			} else {
13881 				/* The conn has started closing */
13882 				err = EINTR;
13883 			}
13884 		} else {
13885 			/*
13886 			 * This one is complete. Reply to pending ioctl.
13887 			 */
13888 			err = ipif_up_done(ipif);
13889 		}
13890 
13891 		if ((err == 0) && (ill->ill_up_ipifs)) {
13892 			err = ill_up_ipifs(ill, q, mp1);
13893 			if (err == EINPROGRESS) {
13894 				freemsg(mp);
13895 				return;
13896 			}
13897 		}
13898 
13899 		if (ill->ill_up_ipifs) {
13900 			ill_group_cleanup(ill);
13901 		}
13902 
13903 		break;
13904 	case DL_NOTIFY_IND: {
13905 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
13906 		ire_t *ire;
13907 		boolean_t need_ire_walk_v4 = B_FALSE;
13908 		boolean_t need_ire_walk_v6 = B_FALSE;
13909 
13910 		/*
13911 		 * Change the address everywhere we need to.
13912 		 * What we're getting here is a link-level addr or phys addr.
13913 		 * The new addr is at notify + notify->dl_addr_offset
13914 		 * The address length is notify->dl_addr_length;
13915 		 */
13916 		switch (notify->dl_notification) {
13917 		case DL_NOTE_PHYS_ADDR:
13918 			mp_hw = copyb(mp);
13919 			if (mp_hw == NULL) {
13920 				err = ENOMEM;
13921 				break;
13922 			}
13923 			dlp = (union DL_primitives *)mp_hw->b_rptr;
13924 			/*
13925 			 * We currently don't support changing
13926 			 * the token via DL_NOTIFY_IND.
13927 			 * When we do support it, we have to consider
13928 			 * what the implications are with respect to
13929 			 * the token and the link local address.
13930 			 */
13931 			mutex_enter(&ill->ill_lock);
13932 			if (dlp->notify_ind.dl_data ==
13933 			    DL_IPV6_LINK_LAYER_ADDR) {
13934 				if (ill->ill_nd_lla_mp != NULL)
13935 					freemsg(ill->ill_nd_lla_mp);
13936 				ill->ill_nd_lla_mp = mp_hw;
13937 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
13938 				    dlp->notify_ind.dl_addr_offset;
13939 				ill->ill_nd_lla_len =
13940 				    dlp->notify_ind.dl_addr_length -
13941 				    ABS(ill->ill_sap_length);
13942 				mutex_exit(&ill->ill_lock);
13943 				break;
13944 			} else if (dlp->notify_ind.dl_data ==
13945 			    DL_CURR_PHYS_ADDR) {
13946 				if (ill->ill_phys_addr_mp != NULL)
13947 					freemsg(ill->ill_phys_addr_mp);
13948 				ill->ill_phys_addr_mp = mp_hw;
13949 				ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
13950 				    dlp->notify_ind.dl_addr_offset;
13951 				ill->ill_phys_addr_length =
13952 				    dlp->notify_ind.dl_addr_length -
13953 				    ABS(ill->ill_sap_length);
13954 				if (ill->ill_isv6 &&
13955 				    !(ill->ill_flags & ILLF_XRESOLV)) {
13956 					if (ill->ill_nd_lla_mp != NULL)
13957 						freemsg(ill->ill_nd_lla_mp);
13958 					ill->ill_nd_lla_mp = copyb(mp_hw);
13959 					ill->ill_nd_lla = (uchar_t *)
13960 					    ill->ill_nd_lla_mp->b_rptr +
13961 					    dlp->notify_ind.dl_addr_offset;
13962 					ill->ill_nd_lla_len =
13963 					    ill->ill_phys_addr_length;
13964 				}
13965 			}
13966 			mutex_exit(&ill->ill_lock);
13967 			/*
13968 			 * Send out gratuitous arp request for our new
13969 			 * hardware address.
13970 			 */
13971 			for (ipif = ill->ill_ipif; ipif != NULL;
13972 			    ipif = ipif->ipif_next) {
13973 				if (!(ipif->ipif_flags & IPIF_UP))
13974 					continue;
13975 				if (ill->ill_isv6) {
13976 					ipif_ndp_down(ipif);
13977 					/*
13978 					 * Set B_TRUE to enable
13979 					 * ipif_ndp_up() to send out
13980 					 * unsolicited advertisements.
13981 					 */
13982 					err = ipif_ndp_up(ipif,
13983 					    &ipif->ipif_v6lcl_addr,
13984 					    B_TRUE);
13985 					if (err) {
13986 						ip1dbg((
13987 						    "ip_rput_dlpi_writer: "
13988 						    "Failed to update ndp "
13989 						    "err %d\n", err));
13990 					}
13991 				} else {
13992 					/*
13993 					 * IPv4 ARP case
13994 					 *
13995 					 * Set B_TRUE, as we only want
13996 					 * ipif_resolver_up to send an
13997 					 * AR_ENTRY_ADD request up to
13998 					 * ARP.
13999 					 */
14000 					err = ipif_resolver_up(ipif,
14001 					    B_TRUE);
14002 					if (err) {
14003 						ip1dbg((
14004 						    "ip_rput_dlpi_writer: "
14005 						    "Failed to update arp "
14006 						    "err %d\n", err));
14007 					}
14008 				}
14009 			}
14010 			/*
14011 			 * Allow "fall through" to the DL_NOTE_FASTPATH_FLUSH
14012 			 * case so that all old fastpath information can be
14013 			 * purged from IRE caches.
14014 			 */
14015 		/* FALLTHRU */
14016 		case DL_NOTE_FASTPATH_FLUSH:
14017 			/*
14018 			 * Any fastpath probe sent henceforth will get the
14019 			 * new fp mp. So we first delete any ires that are
14020 			 * waiting for the fastpath. Then walk all ires and
14021 			 * delete the ire or delete the fp mp. In the case of
14022 			 * IRE_MIPRTUN and IRE_BROADCAST it is difficult to
14023 			 * recreate the ire's without going through a complex
14024 			 * ipif up/down dance. So we don't delete the ire
14025 			 * itself, but just the ire_fp_mp for these 2 ire's
14026 			 * In the case of the other ire's we delete the ire's
14027 			 * themselves. Access to ire_fp_mp is completely
14028 			 * protected by ire_lock for IRE_MIPRTUN and
14029 			 * IRE_BROADCAST. Deleting the ire is preferable in the
14030 			 * other cases for performance.
14031 			 */
14032 			if (ill->ill_isv6) {
14033 				nce_fastpath_list_dispatch(ill, NULL, NULL);
14034 				ndp_walk(ill, (pfi_t)ndp_fastpath_flush,
14035 				    NULL);
14036 			} else {
14037 				ire_fastpath_list_dispatch(ill, NULL, NULL);
14038 				ire_walk_ill_v4(MATCH_IRE_WQ | MATCH_IRE_TYPE,
14039 				    IRE_CACHE | IRE_BROADCAST,
14040 				    ire_fastpath_flush, NULL, ill);
14041 				mutex_enter(&ire_mrtun_lock);
14042 				if (ire_mrtun_count != 0) {
14043 					mutex_exit(&ire_mrtun_lock);
14044 					ire_walk_ill_mrtun(MATCH_IRE_WQ,
14045 					    IRE_MIPRTUN, ire_fastpath_flush,
14046 					    NULL, ill);
14047 				} else {
14048 					mutex_exit(&ire_mrtun_lock);
14049 				}
14050 			}
14051 			break;
14052 		case DL_NOTE_SDU_SIZE:
14053 			/*
14054 			 * Change the MTU size of the interface, of all
14055 			 * attached ipif's, and of all relevant ire's.  The
14056 			 * new value's a uint32_t at notify->dl_data.
14057 			 * Mtu change Vs. new ire creation - protocol below.
14058 			 *
14059 			 * a Mark the ipif as IPIF_CHANGING.
14060 			 * b Set the new mtu in the ipif.
14061 			 * c Change the ire_max_frag on all affected ires
14062 			 * d Unmark the IPIF_CHANGING
14063 			 *
14064 			 * To see how the protocol works, assume an interface
14065 			 * route is also being added simultaneously by
14066 			 * ip_rt_add and let 'ipif' be the ipif referenced by
14067 			 * the ire. If the ire is created before step a,
14068 			 * it will be cleaned up by step c. If the ire is
14069 			 * created after step d, it will see the new value of
14070 			 * ipif_mtu. Any attempt to create the ire between
14071 			 * steps a to d will fail because of the IPIF_CHANGING
14072 			 * flag. Note that ire_create() is passed a pointer to
14073 			 * the ipif_mtu, and not the value. During ire_add
14074 			 * under the bucket lock, the ire_max_frag of the
14075 			 * new ire being created is set from the ipif/ire from
14076 			 * which it is being derived.
14077 			 */
14078 			mutex_enter(&ill->ill_lock);
14079 			ill->ill_max_frag = (uint_t)notify->dl_data;
14080 
14081 			/*
14082 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
14083 			 * leave it alone
14084 			 */
14085 			if (ill->ill_mtu_userspecified) {
14086 				mutex_exit(&ill->ill_lock);
14087 				break;
14088 			}
14089 			ill->ill_max_mtu = ill->ill_max_frag;
14090 			if (ill->ill_isv6) {
14091 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
14092 					ill->ill_max_mtu = IPV6_MIN_MTU;
14093 			} else {
14094 				if (ill->ill_max_mtu < IP_MIN_MTU)
14095 					ill->ill_max_mtu = IP_MIN_MTU;
14096 			}
14097 			for (ipif = ill->ill_ipif; ipif != NULL;
14098 			    ipif = ipif->ipif_next) {
14099 				/*
14100 				 * Don't override the mtu if the user
14101 				 * has explicitly set it.
14102 				 */
14103 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
14104 					continue;
14105 				ipif->ipif_mtu = (uint_t)notify->dl_data;
14106 				if (ipif->ipif_isv6)
14107 					ire = ipif_to_ire_v6(ipif);
14108 				else
14109 					ire = ipif_to_ire(ipif);
14110 				if (ire != NULL) {
14111 					ire->ire_max_frag = ipif->ipif_mtu;
14112 					ire_refrele(ire);
14113 				}
14114 				if (ipif->ipif_flags & IPIF_UP) {
14115 					if (ill->ill_isv6)
14116 						need_ire_walk_v6 = B_TRUE;
14117 					else
14118 						need_ire_walk_v4 = B_TRUE;
14119 				}
14120 			}
14121 			mutex_exit(&ill->ill_lock);
14122 			if (need_ire_walk_v4)
14123 				ire_walk_v4(ill_mtu_change, (char *)ill,
14124 				    ALL_ZONES);
14125 			if (need_ire_walk_v6)
14126 				ire_walk_v6(ill_mtu_change, (char *)ill,
14127 				    ALL_ZONES);
14128 			break;
14129 		case DL_NOTE_LINK_UP:
14130 		case DL_NOTE_LINK_DOWN: {
14131 			/*
14132 			 * We are writer. ill / phyint / ipsq assocs stable.
14133 			 * The RUNNING flag reflects the state of the link.
14134 			 */
14135 			phyint_t *phyint = ill->ill_phyint;
14136 			uint64_t new_phyint_flags;
14137 			boolean_t changed = B_FALSE;
14138 
14139 			mutex_enter(&phyint->phyint_lock);
14140 			new_phyint_flags =
14141 			    (notify->dl_notification == DL_NOTE_LINK_UP) ?
14142 			    phyint->phyint_flags | PHYI_RUNNING :
14143 			    phyint->phyint_flags & ~PHYI_RUNNING;
14144 			if (new_phyint_flags != phyint->phyint_flags) {
14145 				phyint->phyint_flags = new_phyint_flags;
14146 				changed = B_TRUE;
14147 			}
14148 			mutex_exit(&phyint->phyint_lock);
14149 			/*
14150 			 * If the flags have changed, send a message to
14151 			 * the routing socket.
14152 			 */
14153 			if (changed) {
14154 				if (phyint->phyint_illv4 != NULL) {
14155 					ip_rts_ifmsg(
14156 					    phyint->phyint_illv4->ill_ipif);
14157 				}
14158 				if (phyint->phyint_illv6 != NULL) {
14159 					ip_rts_ifmsg(
14160 					    phyint->phyint_illv6->ill_ipif);
14161 				}
14162 			}
14163 			break;
14164 		}
14165 		case DL_NOTE_PROMISC_ON_PHYS:
14166 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
14167 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
14168 			mutex_enter(&ill->ill_lock);
14169 			ill->ill_promisc_on_phys = B_TRUE;
14170 			mutex_exit(&ill->ill_lock);
14171 			break;
14172 		case DL_NOTE_PROMISC_OFF_PHYS:
14173 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
14174 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
14175 			mutex_enter(&ill->ill_lock);
14176 			ill->ill_promisc_on_phys = B_FALSE;
14177 			mutex_exit(&ill->ill_lock);
14178 			break;
14179 		case DL_NOTE_CAPAB_RENEG:
14180 			/*
14181 			 * Something changed on the driver side.
14182 			 * It wants us to renegotiate the capabilities
14183 			 * on this ill. The most likely cause is the
14184 			 * aggregation interface under us where a
14185 			 * port got added or went away.
14186 			 *
14187 			 * We reset the capabilities and set the
14188 			 * state to IDMS_RENG so that when the ack
14189 			 * comes back, we can start the
14190 			 * renegotiation process.
14191 			 */
14192 			ill_capability_reset(ill);
14193 			ill->ill_capab_state = IDMS_RENEG;
14194 			break;
14195 		default:
14196 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
14197 			    "type 0x%x for DL_NOTIFY_IND\n",
14198 			    notify->dl_notification));
14199 			break;
14200 		}
14201 
14202 		/*
14203 		 * As this is an asynchronous operation, we
14204 		 * should not call ill_dlpi_done
14205 		 */
14206 		break;
14207 	}
14208 	case DL_NOTIFY_ACK:
14209 		/*
14210 		 * Don't really need to check for what notifications
14211 		 * are supported; we'll process what gets sent upstream,
14212 		 * and we know it'll be something we support changing
14213 		 * based on our DL_NOTIFY_REQ.
14214 		 */
14215 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
14216 		break;
14217 	case DL_PHYS_ADDR_ACK: {
14218 		/*
14219 		 * We should have an IOCTL waiting on this when request
14220 		 * sent by ill_dl_phys.
14221 		 * However, ill_dl_phys was called on an ill queue (from
14222 		 * SIOCSLIFNAME), thus conn_pending_ill is not set. But the
14223 		 * ioctl is known to be pending on ill_wq.
14224 		 * There are two additional phys_addr_req's sent to the
14225 		 * driver to get the token and lla. ill_phys_addr_pend
14226 		 * keeps track of the last one sent so we know which
14227 		 * response we are dealing with. ill_dlpi_done will
14228 		 * update ill_phys_addr_pend when it sends the next req.
14229 		 * We don't complete the IOCTL until all three DL_PARs
14230 		 * have been attempted.
14231 		 *
14232 		 * We don't need any lock to update ill_nd_lla* fields,
14233 		 * since the ill is not yet up, We grab the lock just
14234 		 * for uniformity with other code that accesses ill_nd_lla.
14235 		 */
14236 		physaddr_req = ill->ill_phys_addr_pend;
14237 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
14238 		if (physaddr_req == DL_IPV6_TOKEN ||
14239 		    physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
14240 			if (physaddr_req == DL_IPV6_TOKEN) {
14241 				/*
14242 				 * bcopy to low-order bits of ill_token
14243 				 *
14244 				 * XXX Temporary hack - currently,
14245 				 * all known tokens are 64 bits,
14246 				 * so I'll cheat for the moment.
14247 				 */
14248 				dlp = (union DL_primitives *)mp->b_rptr;
14249 
14250 				mutex_enter(&ill->ill_lock);
14251 				bcopy((uchar_t *)(mp->b_rptr +
14252 				dlp->physaddr_ack.dl_addr_offset),
14253 				(void *)&ill->ill_token.s6_addr32[2],
14254 				dlp->physaddr_ack.dl_addr_length);
14255 				ill->ill_token_length =
14256 					dlp->physaddr_ack.dl_addr_length;
14257 				mutex_exit(&ill->ill_lock);
14258 			} else {
14259 				ASSERT(ill->ill_nd_lla_mp == NULL);
14260 				mp_hw = copyb(mp);
14261 				if (mp_hw == NULL) {
14262 					err = ENOMEM;
14263 					break;
14264 				}
14265 				dlp = (union DL_primitives *)mp_hw->b_rptr;
14266 				mutex_enter(&ill->ill_lock);
14267 				ill->ill_nd_lla_mp = mp_hw;
14268 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
14269 				dlp->physaddr_ack.dl_addr_offset;
14270 				ill->ill_nd_lla_len =
14271 					dlp->physaddr_ack.dl_addr_length;
14272 				mutex_exit(&ill->ill_lock);
14273 			}
14274 			break;
14275 		}
14276 		ASSERT(physaddr_req == DL_CURR_PHYS_ADDR);
14277 		ASSERT(ill->ill_phys_addr_mp == NULL);
14278 		if (!ill->ill_ifname_pending)
14279 			break;
14280 		ill->ill_ifname_pending = 0;
14281 		if (!ioctl_aborted)
14282 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
14283 		if (mp1 != NULL) {
14284 			ASSERT(connp == NULL);
14285 			q = ill->ill_wq;
14286 		}
14287 		/*
14288 		 * If any error acks received during the plumbing sequence,
14289 		 * ill_ifname_pending_err will be set. Break out and send up
14290 		 * the error to the pending ioctl.
14291 		 */
14292 		if (ill->ill_ifname_pending_err != 0) {
14293 			err = ill->ill_ifname_pending_err;
14294 			ill->ill_ifname_pending_err = 0;
14295 			break;
14296 		}
14297 		/*
14298 		 * Get the interface token.  If the zeroth interface
14299 		 * address is zero then set the address to the link local
14300 		 * address
14301 		 */
14302 		mp_hw = copyb(mp);
14303 		if (mp_hw == NULL) {
14304 			err = ENOMEM;
14305 			break;
14306 		}
14307 		dlp = (union DL_primitives *)mp_hw->b_rptr;
14308 		ill->ill_phys_addr_mp = mp_hw;
14309 		ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
14310 				dlp->physaddr_ack.dl_addr_offset;
14311 		if (dlp->physaddr_ack.dl_addr_length == 0 ||
14312 		    ill->ill_phys_addr_length == 0 ||
14313 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
14314 			/*
14315 			 * Compatibility: atun driver returns a length of 0.
14316 			 * ipdptp has an ill_phys_addr_length of zero(from
14317 			 * DL_BIND_ACK) but a non-zero length here.
14318 			 * ipd has an ill_phys_addr_length of 4(from
14319 			 * DL_BIND_ACK) but a non-zero length here.
14320 			 */
14321 			ill->ill_phys_addr = NULL;
14322 		} else if (dlp->physaddr_ack.dl_addr_length !=
14323 		    ill->ill_phys_addr_length) {
14324 			ip0dbg(("DL_PHYS_ADDR_ACK: "
14325 			    "Address length mismatch %d %d\n",
14326 			    dlp->physaddr_ack.dl_addr_length,
14327 			    ill->ill_phys_addr_length));
14328 			err = EINVAL;
14329 			break;
14330 		}
14331 		mutex_enter(&ill->ill_lock);
14332 		if (ill->ill_nd_lla_mp == NULL) {
14333 			ill->ill_nd_lla_mp = copyb(mp_hw);
14334 			if (ill->ill_nd_lla_mp == NULL) {
14335 				err = ENOMEM;
14336 				mutex_exit(&ill->ill_lock);
14337 				break;
14338 			}
14339 			ill->ill_nd_lla =
14340 			    (uchar_t *)ill->ill_nd_lla_mp->b_rptr +
14341 			    dlp->physaddr_ack.dl_addr_offset;
14342 			ill->ill_nd_lla_len = ill->ill_phys_addr_length;
14343 		}
14344 		mutex_exit(&ill->ill_lock);
14345 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
14346 			(void) ill_setdefaulttoken(ill);
14347 
14348 		/*
14349 		 * If the ill zero interface has a zero address assign
14350 		 * it the proper link local address.
14351 		 */
14352 		ASSERT(ill->ill_ipif->ipif_id == 0);
14353 		if (ipif != NULL &&
14354 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
14355 			(void) ipif_setlinklocal(ipif);
14356 		break;
14357 	}
14358 	case DL_OK_ACK:
14359 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
14360 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
14361 		    dloa->dl_correct_primitive));
14362 		switch (dloa->dl_correct_primitive) {
14363 		case DL_UNBIND_REQ:
14364 		case DL_ATTACH_REQ:
14365 		case DL_DETACH_REQ:
14366 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
14367 			break;
14368 		}
14369 		break;
14370 	default:
14371 		break;
14372 	}
14373 
14374 	freemsg(mp);
14375 	if (mp1) {
14376 		struct iocblk *iocp;
14377 		int mode;
14378 
14379 		/*
14380 		 * Complete the waiting IOCTL. For SIOCLIFADDIF or
14381 		 * SIOCSLIFNAME do a copyout.
14382 		 */
14383 		iocp = (struct iocblk *)mp1->b_rptr;
14384 
14385 		if (iocp->ioc_cmd == SIOCLIFADDIF ||
14386 		    iocp->ioc_cmd == SIOCSLIFNAME)
14387 			mode = COPYOUT;
14388 		else
14389 			mode = NO_COPYOUT;
14390 		/*
14391 		 * The ioctl must complete now without EINPROGRESS
14392 		 * since ipsq_pending_mp_get has removed the ioctl mblk
14393 		 * from ipsq_pending_mp. Otherwise the ioctl will be
14394 		 * stuck for ever in the ipsq.
14395 		 */
14396 		ASSERT(err != EINPROGRESS);
14397 		ip_ioctl_finish(q, mp1, err, mode, ipif, ipsq);
14398 
14399 	}
14400 }
14401 
14402 /*
14403  * ip_rput_other is called by ip_rput to handle messages modifying the global
14404  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
14405  */
14406 /* ARGSUSED */
14407 void
14408 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
14409 {
14410 	ill_t		*ill;
14411 	struct iocblk	*iocp;
14412 	mblk_t		*mp1;
14413 	conn_t		*connp = NULL;
14414 
14415 	ip1dbg(("ip_rput_other "));
14416 	ill = (ill_t *)q->q_ptr;
14417 	/*
14418 	 * This routine is not a writer in the case of SIOCGTUNPARAM
14419 	 * in which case ipsq is NULL.
14420 	 */
14421 	if (ipsq != NULL) {
14422 		ASSERT(IAM_WRITER_IPSQ(ipsq));
14423 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
14424 	}
14425 
14426 	switch (mp->b_datap->db_type) {
14427 	case M_ERROR:
14428 	case M_HANGUP:
14429 		/*
14430 		 * The device has a problem.  We force the ILL down.  It can
14431 		 * be brought up again manually using SIOCSIFFLAGS (via
14432 		 * ifconfig or equivalent).
14433 		 */
14434 		ASSERT(ipsq != NULL);
14435 		if (mp->b_rptr < mp->b_wptr)
14436 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
14437 		if (ill->ill_error == 0)
14438 			ill->ill_error = ENXIO;
14439 		if (!ill_down_start(q, mp))
14440 			return;
14441 		ipif_all_down_tail(ipsq, q, mp, NULL);
14442 		break;
14443 	case M_IOCACK:
14444 		iocp = (struct iocblk *)mp->b_rptr;
14445 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
14446 		switch (iocp->ioc_cmd) {
14447 		case SIOCSTUNPARAM:
14448 		case OSIOCSTUNPARAM:
14449 			ASSERT(ipsq != NULL);
14450 			/*
14451 			 * Finish socket ioctl passed through to tun.
14452 			 * We should have an IOCTL waiting on this.
14453 			 */
14454 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
14455 			if (ill->ill_isv6) {
14456 				struct iftun_req *ta;
14457 
14458 				/*
14459 				 * if a source or destination is
14460 				 * being set, try and set the link
14461 				 * local address for the tunnel
14462 				 */
14463 				ta = (struct iftun_req *)mp->b_cont->
14464 				    b_cont->b_rptr;
14465 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
14466 					ipif_set_tun_llink(ill, ta);
14467 				}
14468 
14469 			}
14470 			if (mp1 != NULL) {
14471 				/*
14472 				 * Now copy back the b_next/b_prev used by
14473 				 * mi code for the mi_copy* functions.
14474 				 * See ip_sioctl_tunparam() for the reason.
14475 				 * Also protect against missing b_cont.
14476 				 */
14477 				if (mp->b_cont != NULL) {
14478 					mp->b_cont->b_next =
14479 					    mp1->b_cont->b_next;
14480 					mp->b_cont->b_prev =
14481 					    mp1->b_cont->b_prev;
14482 				}
14483 				ip_ioctl_freemsg(mp1);
14484 				ASSERT(ipsq->ipsq_current_ipif != NULL);
14485 				ASSERT(connp != NULL);
14486 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
14487 				    iocp->ioc_error, NO_COPYOUT,
14488 				    ipsq->ipsq_current_ipif, ipsq);
14489 			} else {
14490 				ASSERT(connp == NULL);
14491 				putnext(q, mp);
14492 			}
14493 			break;
14494 		case SIOCGTUNPARAM:
14495 		case OSIOCGTUNPARAM:
14496 			/*
14497 			 * This is really M_IOCDATA from the tunnel driver.
14498 			 * convert back and complete the ioctl.
14499 			 * We should have an IOCTL waiting on this.
14500 			 */
14501 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
14502 			if (mp1) {
14503 				/*
14504 				 * Now copy back the b_next/b_prev used by
14505 				 * mi code for the mi_copy* functions.
14506 				 * See ip_sioctl_tunparam() for the reason.
14507 				 * Also protect against missing b_cont.
14508 				 */
14509 				if (mp->b_cont != NULL) {
14510 					mp->b_cont->b_next =
14511 					    mp1->b_cont->b_next;
14512 					mp->b_cont->b_prev =
14513 					    mp1->b_cont->b_prev;
14514 				}
14515 				ip_ioctl_freemsg(mp1);
14516 				if (iocp->ioc_error == 0)
14517 					mp->b_datap->db_type = M_IOCDATA;
14518 				ASSERT(connp != NULL);
14519 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
14520 				    iocp->ioc_error, COPYOUT, NULL, NULL);
14521 			} else {
14522 				ASSERT(connp == NULL);
14523 				putnext(q, mp);
14524 			}
14525 			break;
14526 		default:
14527 			break;
14528 		}
14529 		break;
14530 	case M_IOCNAK:
14531 		iocp = (struct iocblk *)mp->b_rptr;
14532 
14533 		switch (iocp->ioc_cmd) {
14534 		int mode;
14535 		ipif_t	*ipif;
14536 
14537 		case DL_IOC_HDR_INFO:
14538 			/*
14539 			 * If this was the first attempt turn of the
14540 			 * fastpath probing.
14541 			 */
14542 			mutex_enter(&ill->ill_lock);
14543 			if (ill->ill_dlpi_fastpath_state == IDMS_INPROGRESS) {
14544 				ill->ill_dlpi_fastpath_state = IDMS_FAILED;
14545 				mutex_exit(&ill->ill_lock);
14546 				ill_fastpath_nack(ill);
14547 				ip1dbg(("ip_rput: DLPI fastpath off on "
14548 				    "interface %s\n",
14549 				    ill->ill_name));
14550 			} else {
14551 				mutex_exit(&ill->ill_lock);
14552 			}
14553 			freemsg(mp);
14554 			break;
14555 		case SIOCSTUNPARAM:
14556 		case OSIOCSTUNPARAM:
14557 			ASSERT(ipsq != NULL);
14558 			/*
14559 			 * Finish socket ioctl passed through to tun
14560 			 * We should have an IOCTL waiting on this.
14561 			 */
14562 			/* FALLTHRU */
14563 		case SIOCGTUNPARAM:
14564 		case OSIOCGTUNPARAM:
14565 			/*
14566 			 * This is really M_IOCDATA from the tunnel driver.
14567 			 * convert back and complete the ioctl.
14568 			 * We should have an IOCTL waiting on this.
14569 			 */
14570 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
14571 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
14572 				mp1 = ill_pending_mp_get(ill, &connp,
14573 				    iocp->ioc_id);
14574 				mode = COPYOUT;
14575 				ipsq = NULL;
14576 				ipif = NULL;
14577 			} else {
14578 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14579 				mode = NO_COPYOUT;
14580 				ASSERT(ipsq->ipsq_current_ipif != NULL);
14581 				ipif = ipsq->ipsq_current_ipif;
14582 			}
14583 			if (mp1 != NULL) {
14584 				/*
14585 				 * Now copy back the b_next/b_prev used by
14586 				 * mi code for the mi_copy* functions.
14587 				 * See ip_sioctl_tunparam() for the reason.
14588 				 * Also protect against missing b_cont.
14589 				 */
14590 				if (mp->b_cont != NULL) {
14591 					mp->b_cont->b_next =
14592 					    mp1->b_cont->b_next;
14593 					mp->b_cont->b_prev =
14594 					    mp1->b_cont->b_prev;
14595 				}
14596 				ip_ioctl_freemsg(mp1);
14597 				if (iocp->ioc_error == 0)
14598 					iocp->ioc_error = EINVAL;
14599 				ASSERT(connp != NULL);
14600 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
14601 				    iocp->ioc_error, mode, ipif, ipsq);
14602 			} else {
14603 				ASSERT(connp == NULL);
14604 				putnext(q, mp);
14605 			}
14606 			break;
14607 		default:
14608 			break;
14609 		}
14610 	default:
14611 		break;
14612 	}
14613 }
14614 
14615 /*
14616  * NOTE : This function does not ire_refrele the ire argument passed in.
14617  *
14618  * IPQoS notes
14619  * IP policy is invoked twice for a forwarded packet, once on the read side
14620  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
14621  * enabled. An additional parameter, in_ill, has been added for this purpose.
14622  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
14623  * because ip_mroute drops this information.
14624  *
14625  */
14626 void
14627 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
14628 {
14629 	uint32_t	pkt_len;
14630 	queue_t	*q;
14631 	uint32_t	sum;
14632 #define	rptr	((uchar_t *)ipha)
14633 	uint32_t	max_frag;
14634 	uint32_t	ill_index;
14635 
14636 	/* Get the ill_index of the incoming ILL */
14637 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
14638 
14639 	/* Initiate Read side IPPF processing */
14640 	if (IPP_ENABLED(IPP_FWD_IN)) {
14641 		ip_process(IPP_FWD_IN, &mp, ill_index);
14642 		if (mp == NULL) {
14643 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
14644 			    "during IPPF processing\n"));
14645 			return;
14646 		}
14647 	}
14648 	pkt_len = ntohs(ipha->ipha_length);
14649 
14650 	/* Adjust the checksum to reflect the ttl decrement. */
14651 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14652 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14653 
14654 	if (ipha->ipha_ttl-- <= 1) {
14655 		if (ip_csum_hdr(ipha)) {
14656 			BUMP_MIB(&ip_mib, ipInCksumErrs);
14657 			goto drop_pkt;
14658 		}
14659 		/*
14660 		 * Note: ire_stq this will be NULL for multicast
14661 		 * datagrams using the long path through arp (the IRE
14662 		 * is not an IRE_CACHE). This should not cause
14663 		 * problems since we don't generate ICMP errors for
14664 		 * multicast packets.
14665 		 */
14666 		q = ire->ire_stq;
14667 		if (q)
14668 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED);
14669 		else
14670 			freemsg(mp);
14671 		return;
14672 	}
14673 
14674 	/*
14675 	 * Don't forward if the interface is down
14676 	 */
14677 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
14678 		BUMP_MIB(&ip_mib, ipInDiscards);
14679 		goto drop_pkt;
14680 	}
14681 
14682 	/* Get the ill_index of the outgoing ILL */
14683 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
14684 
14685 	/* Check if there are options to update */
14686 	if (!IS_SIMPLE_IPH(ipha)) {
14687 		if (ip_csum_hdr(ipha)) {
14688 			BUMP_MIB(&ip_mib, ipInCksumErrs);
14689 			goto drop_pkt;
14690 		}
14691 		if (ip_rput_forward_options(mp, ipha, ire)) {
14692 			return;
14693 		}
14694 
14695 		ipha->ipha_hdr_checksum = 0;
14696 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14697 	}
14698 	max_frag = ire->ire_max_frag;
14699 	if (pkt_len > max_frag) {
14700 		/*
14701 		 * It needs fragging on its way out.  We haven't
14702 		 * verified the header checksum yet.  Since we
14703 		 * are going to put a surely good checksum in the
14704 		 * outgoing header, we have to make sure that it
14705 		 * was good coming in.
14706 		 */
14707 		if (ip_csum_hdr(ipha)) {
14708 			BUMP_MIB(&ip_mib, ipInCksumErrs);
14709 			goto drop_pkt;
14710 		}
14711 		/* Initiate Write side IPPF processing */
14712 		if (IPP_ENABLED(IPP_FWD_OUT)) {
14713 			ip_process(IPP_FWD_OUT, &mp, ill_index);
14714 			if (mp == NULL) {
14715 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
14716 				    " during IPPF processing\n"));
14717 				return;
14718 			}
14719 		}
14720 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0);
14721 		return;
14722 	}
14723 
14724 	mp = ip_wput_attach_llhdr(mp, ire, IPP_FWD_OUT, ill_index);
14725 	if (mp == NULL) {
14726 		BUMP_MIB(&ip_mib, ipInDiscards);
14727 		return;
14728 	}
14729 
14730 	q = ire->ire_stq;
14731 	UPDATE_IB_PKT_COUNT(ire);
14732 	ire->ire_last_used_time = lbolt;
14733 	BUMP_MIB(&ip_mib, ipForwDatagrams);
14734 	putnext(q, mp);
14735 	return;
14736 
14737 drop_pkt:;
14738 	ip1dbg(("ip_rput_forward: drop pkt\n"));
14739 	freemsg(mp);
14740 #undef	rptr
14741 }
14742 
14743 void
14744 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
14745 {
14746 	ire_t	*ire;
14747 
14748 	ASSERT(!ipif->ipif_isv6);
14749 	/*
14750 	 * Find an IRE which matches the destination and the outgoing
14751 	 * queue in the cache table. All we need is an IRE_CACHE which
14752 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
14753 	 * then it is enough to have some IRE_CACHE in the group.
14754 	 */
14755 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
14756 		dst = ipif->ipif_pp_dst_addr;
14757 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES,
14758 	    MATCH_IRE_ILL_GROUP);
14759 	if (!ire) {
14760 		/*
14761 		 * Mark this packet to make it be delivered to
14762 		 * ip_rput_forward after the new ire has been
14763 		 * created.
14764 		 */
14765 		mp->b_prev = NULL;
14766 		mp->b_next = mp;
14767 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
14768 		    NULL, 0);
14769 	} else {
14770 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
14771 		IRE_REFRELE(ire);
14772 	}
14773 }
14774 
14775 /* Update any source route, record route or timestamp options */
14776 static int
14777 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire)
14778 {
14779 	ipoptp_t	opts;
14780 	uchar_t		*opt;
14781 	uint8_t		optval;
14782 	uint8_t		optlen;
14783 	ipaddr_t	dst;
14784 	uint32_t	ts;
14785 	ire_t		*dst_ire = NULL;
14786 	ire_t		*tmp_ire = NULL;
14787 	timestruc_t	now;
14788 
14789 	ip2dbg(("ip_rput_forward_options\n"));
14790 	dst = ipha->ipha_dst;
14791 	for (optval = ipoptp_first(&opts, ipha);
14792 	    optval != IPOPT_EOL;
14793 	    optval = ipoptp_next(&opts)) {
14794 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
14795 		opt = opts.ipoptp_cur;
14796 		optlen = opts.ipoptp_len;
14797 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
14798 		    optval, opts.ipoptp_len));
14799 		switch (optval) {
14800 			uint32_t off;
14801 		case IPOPT_SSRR:
14802 		case IPOPT_LSRR:
14803 			/* Check if adminstratively disabled */
14804 			if (!ip_forward_src_routed) {
14805 				BUMP_MIB(&ip_mib, ipForwProhibits);
14806 				if (ire->ire_stq)
14807 					icmp_unreachable(ire->ire_stq, mp,
14808 					    ICMP_SOURCE_ROUTE_FAILED);
14809 				else {
14810 					ip0dbg(("ip_rput_forward_options: "
14811 					    "unable to send unreach\n"));
14812 					freemsg(mp);
14813 				}
14814 				return (-1);
14815 			}
14816 
14817 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
14818 			    NULL, ALL_ZONES, MATCH_IRE_TYPE);
14819 			if (dst_ire == NULL) {
14820 				/*
14821 				 * Must be partial since ip_rput_options
14822 				 * checked for strict.
14823 				 */
14824 				break;
14825 			}
14826 			off = opt[IPOPT_OFFSET];
14827 			off--;
14828 		redo_srr:
14829 			if (optlen < IP_ADDR_LEN ||
14830 			    off > optlen - IP_ADDR_LEN) {
14831 				/* End of source route */
14832 				ip1dbg((
14833 				    "ip_rput_forward_options: end of SR\n"));
14834 				ire_refrele(dst_ire);
14835 				break;
14836 			}
14837 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
14838 			bcopy(&ire->ire_src_addr, (char *)opt + off,
14839 			    IP_ADDR_LEN);
14840 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
14841 			    ntohl(dst)));
14842 
14843 			/*
14844 			 * Check if our address is present more than
14845 			 * once as consecutive hops in source route.
14846 			 */
14847 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
14848 			    NULL, ALL_ZONES, MATCH_IRE_TYPE);
14849 			if (tmp_ire != NULL) {
14850 				ire_refrele(tmp_ire);
14851 				off += IP_ADDR_LEN;
14852 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
14853 				goto redo_srr;
14854 			}
14855 			ipha->ipha_dst = dst;
14856 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
14857 			ire_refrele(dst_ire);
14858 			break;
14859 		case IPOPT_RR:
14860 			off = opt[IPOPT_OFFSET];
14861 			off--;
14862 			if (optlen < IP_ADDR_LEN ||
14863 			    off > optlen - IP_ADDR_LEN) {
14864 				/* No more room - ignore */
14865 				ip1dbg((
14866 				    "ip_rput_forward_options: end of RR\n"));
14867 				break;
14868 			}
14869 			bcopy(&ire->ire_src_addr, (char *)opt + off,
14870 			    IP_ADDR_LEN);
14871 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
14872 			break;
14873 		case IPOPT_TS:
14874 			/* Insert timestamp if there is room */
14875 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
14876 			case IPOPT_TS_TSONLY:
14877 				off = IPOPT_TS_TIMELEN;
14878 				break;
14879 			case IPOPT_TS_PRESPEC:
14880 			case IPOPT_TS_PRESPEC_RFC791:
14881 				/* Verify that the address matched */
14882 				off = opt[IPOPT_OFFSET] - 1;
14883 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
14884 				dst_ire = ire_ctable_lookup(dst, 0,
14885 				    IRE_LOCAL, NULL, ALL_ZONES, MATCH_IRE_TYPE);
14886 				if (dst_ire == NULL) {
14887 					/* Not for us */
14888 					break;
14889 				}
14890 				ire_refrele(dst_ire);
14891 				/* FALLTHRU */
14892 			case IPOPT_TS_TSANDADDR:
14893 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
14894 				break;
14895 			default:
14896 				/*
14897 				 * ip_*put_options should have already
14898 				 * dropped this packet.
14899 				 */
14900 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
14901 				    "unknown IT - bug in ip_rput_options?\n");
14902 				return (0);	/* Keep "lint" happy */
14903 			}
14904 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
14905 				/* Increase overflow counter */
14906 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
14907 				opt[IPOPT_POS_OV_FLG] =
14908 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
14909 				    (off << 4));
14910 				break;
14911 			}
14912 			off = opt[IPOPT_OFFSET] - 1;
14913 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
14914 			case IPOPT_TS_PRESPEC:
14915 			case IPOPT_TS_PRESPEC_RFC791:
14916 			case IPOPT_TS_TSANDADDR:
14917 				bcopy(&ire->ire_src_addr,
14918 				    (char *)opt + off, IP_ADDR_LEN);
14919 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
14920 				/* FALLTHRU */
14921 			case IPOPT_TS_TSONLY:
14922 				off = opt[IPOPT_OFFSET] - 1;
14923 				/* Compute # of milliseconds since midnight */
14924 				gethrestime(&now);
14925 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
14926 				    now.tv_nsec / (NANOSEC / MILLISEC);
14927 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
14928 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
14929 				break;
14930 			}
14931 			break;
14932 		}
14933 	}
14934 	return (0);
14935 }
14936 
14937 /*
14938  * This is called after processing at least one of AH/ESP headers.
14939  *
14940  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
14941  * the actual, physical interface on which the packet was received,
14942  * but, when ip_strict_dst_multihoming is set to 1, could be the
14943  * interface which had the ipha_dst configured when the packet went
14944  * through ip_rput. The ill_index corresponding to the recv_ill
14945  * is saved in ipsec_in_rill_index
14946  */
14947 void
14948 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
14949 {
14950 	mblk_t *mp;
14951 	ipaddr_t dst;
14952 	in6_addr_t *v6dstp;
14953 	ipha_t *ipha;
14954 	ip6_t *ip6h;
14955 	ipsec_in_t *ii;
14956 	boolean_t ill_need_rele = B_FALSE;
14957 	boolean_t rill_need_rele = B_FALSE;
14958 	boolean_t ire_need_rele = B_FALSE;
14959 
14960 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
14961 	ASSERT(ii->ipsec_in_ill_index != 0);
14962 
14963 	mp = ipsec_mp->b_cont;
14964 	ASSERT(mp != NULL);
14965 
14966 
14967 	if (ill == NULL) {
14968 		ASSERT(recv_ill == NULL);
14969 		/*
14970 		 * We need to get the original queue on which ip_rput_local
14971 		 * or ip_rput_data_v6 was called.
14972 		 */
14973 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
14974 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL);
14975 		ill_need_rele = B_TRUE;
14976 
14977 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
14978 			recv_ill = ill_lookup_on_ifindex(
14979 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
14980 			    NULL, NULL, NULL, NULL);
14981 			rill_need_rele = B_TRUE;
14982 		} else {
14983 			recv_ill = ill;
14984 		}
14985 
14986 		if ((ill == NULL) || (recv_ill == NULL)) {
14987 			ip0dbg(("ip_fanout_proto_again: interface "
14988 			    "disappeared\n"));
14989 			if (ill != NULL)
14990 				ill_refrele(ill);
14991 			if (recv_ill != NULL)
14992 				ill_refrele(recv_ill);
14993 			freemsg(ipsec_mp);
14994 			return;
14995 		}
14996 	}
14997 
14998 	ASSERT(ill != NULL && recv_ill != NULL);
14999 
15000 	if (mp->b_datap->db_type == M_CTL) {
15001 		/*
15002 		 * AH/ESP is returning the ICMP message after
15003 		 * removing their headers. Fanout again till
15004 		 * it gets to the right protocol.
15005 		 */
15006 		if (ii->ipsec_in_v4) {
15007 			icmph_t *icmph;
15008 			int iph_hdr_length;
15009 			int hdr_length;
15010 
15011 			ipha = (ipha_t *)mp->b_rptr;
15012 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
15013 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
15014 			ipha = (ipha_t *)&icmph[1];
15015 			hdr_length = IPH_HDR_LENGTH(ipha);
15016 			/*
15017 			 * icmp_inbound_error_fanout may need to do pullupmsg.
15018 			 * Reset the type to M_DATA.
15019 			 */
15020 			mp->b_datap->db_type = M_DATA;
15021 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
15022 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
15023 			    B_FALSE, ill, ii->ipsec_in_zoneid);
15024 		} else {
15025 			icmp6_t *icmp6;
15026 			int hdr_length;
15027 
15028 			ip6h = (ip6_t *)mp->b_rptr;
15029 			/* Don't call hdr_length_v6() unless you have to. */
15030 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
15031 				hdr_length = ip_hdr_length_v6(mp, ip6h);
15032 			else
15033 				hdr_length = IPV6_HDR_LEN;
15034 
15035 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
15036 			/*
15037 			 * icmp_inbound_error_fanout_v6 may need to do
15038 			 * pullupmsg.  Reset the type to M_DATA.
15039 			 */
15040 			mp->b_datap->db_type = M_DATA;
15041 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
15042 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
15043 		}
15044 		if (ill_need_rele)
15045 			ill_refrele(ill);
15046 		if (rill_need_rele)
15047 			ill_refrele(recv_ill);
15048 		return;
15049 	}
15050 
15051 	if (ii->ipsec_in_v4) {
15052 		ipha = (ipha_t *)mp->b_rptr;
15053 		dst = ipha->ipha_dst;
15054 		if (CLASSD(dst)) {
15055 			/*
15056 			 * Multicast has to be delivered to all streams.
15057 			 */
15058 			dst = INADDR_BROADCAST;
15059 		}
15060 
15061 		if (ire == NULL) {
15062 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid);
15063 			if (ire == NULL) {
15064 				if (ill_need_rele)
15065 					ill_refrele(ill);
15066 				if (rill_need_rele)
15067 					ill_refrele(recv_ill);
15068 				ip1dbg(("ip_fanout_proto_again: "
15069 				    "IRE not found"));
15070 				freemsg(ipsec_mp);
15071 				return;
15072 			}
15073 			ire_need_rele = B_TRUE;
15074 		}
15075 
15076 		switch (ipha->ipha_protocol) {
15077 			case IPPROTO_UDP:
15078 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
15079 				    recv_ill);
15080 				if (ire_need_rele)
15081 					ire_refrele(ire);
15082 				break;
15083 			case IPPROTO_TCP:
15084 				if (!ire_need_rele)
15085 					IRE_REFHOLD(ire);
15086 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
15087 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
15088 				IRE_REFRELE(ire);
15089 				if (mp != NULL)
15090 					squeue_enter_chain(GET_SQUEUE(mp), mp,
15091 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
15092 				break;
15093 			case IPPROTO_SCTP:
15094 				if (!ire_need_rele)
15095 					IRE_REFHOLD(ire);
15096 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
15097 				    ipsec_mp, 0, ill->ill_rq, dst);
15098 				break;
15099 			default:
15100 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
15101 				    recv_ill);
15102 				if (ire_need_rele)
15103 					ire_refrele(ire);
15104 				break;
15105 		}
15106 	} else {
15107 		uint32_t rput_flags = 0;
15108 
15109 		ip6h = (ip6_t *)mp->b_rptr;
15110 		v6dstp = &ip6h->ip6_dst;
15111 		/*
15112 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
15113 		 * address.
15114 		 *
15115 		 * Currently, we don't store that state in the IPSEC_IN
15116 		 * message, and we may need to.
15117 		 */
15118 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
15119 		    IP6_IN_LLMCAST : 0);
15120 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
15121 		    NULL);
15122 	}
15123 	if (ill_need_rele)
15124 		ill_refrele(ill);
15125 	if (rill_need_rele)
15126 		ill_refrele(recv_ill);
15127 }
15128 
15129 /*
15130  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
15131  * returns 'true' if there are still fragments left on the queue, in
15132  * which case we restart the timer.
15133  */
15134 void
15135 ill_frag_timer(void *arg)
15136 {
15137 	ill_t	*ill = (ill_t *)arg;
15138 	boolean_t frag_pending;
15139 
15140 	mutex_enter(&ill->ill_lock);
15141 	ASSERT(!ill->ill_fragtimer_executing);
15142 	if (ill->ill_state_flags & ILL_CONDEMNED) {
15143 		ill->ill_frag_timer_id = 0;
15144 		mutex_exit(&ill->ill_lock);
15145 		return;
15146 	}
15147 	ill->ill_fragtimer_executing = 1;
15148 	mutex_exit(&ill->ill_lock);
15149 
15150 	frag_pending = ill_frag_timeout(ill, ip_g_frag_timeout);
15151 
15152 	/*
15153 	 * Restart the timer, if we have fragments pending or if someone
15154 	 * wanted us to be scheduled again.
15155 	 */
15156 	mutex_enter(&ill->ill_lock);
15157 	ill->ill_fragtimer_executing = 0;
15158 	ill->ill_frag_timer_id = 0;
15159 	if (frag_pending || ill->ill_fragtimer_needrestart)
15160 		ill_frag_timer_start(ill);
15161 	mutex_exit(&ill->ill_lock);
15162 }
15163 
15164 void
15165 ill_frag_timer_start(ill_t *ill)
15166 {
15167 	ASSERT(MUTEX_HELD(&ill->ill_lock));
15168 
15169 	/* If the ill is closing or opening don't proceed */
15170 	if (ill->ill_state_flags & ILL_CONDEMNED)
15171 		return;
15172 
15173 	if (ill->ill_fragtimer_executing) {
15174 		/*
15175 		 * ill_frag_timer is currently executing. Just record the
15176 		 * the fact that we want the timer to be restarted.
15177 		 * ill_frag_timer will post a timeout before it returns,
15178 		 * ensuring it will be called again.
15179 		 */
15180 		ill->ill_fragtimer_needrestart = 1;
15181 		return;
15182 	}
15183 
15184 	if (ill->ill_frag_timer_id == 0) {
15185 		/*
15186 		 * The timer is neither running nor is the timeout handler
15187 		 * executing. Post a timeout so that ill_frag_timer will be
15188 		 * called
15189 		 */
15190 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
15191 		    MSEC_TO_TICK(ip_g_frag_timo_ms >> 1));
15192 		ill->ill_fragtimer_needrestart = 0;
15193 	}
15194 }
15195 
15196 /*
15197  * This routine is needed for loopback when forwarding multicasts.
15198  *
15199  * IPQoS Notes:
15200  * IPPF processing is done in fanout routines.
15201  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
15202  * processing for IPSec packets is done when it comes back in clear.
15203  * NOTE : The callers of this function need to do the ire_refrele for the
15204  *	  ire that is being passed in.
15205  */
15206 void
15207 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
15208     ill_t *recv_ill)
15209 {
15210 	ill_t	*ill = (ill_t *)q->q_ptr;
15211 	uint32_t	sum;
15212 	uint32_t	u1;
15213 	uint32_t	u2;
15214 	int		hdr_length;
15215 	boolean_t	mctl_present;
15216 	mblk_t		*first_mp = mp;
15217 	mblk_t		*hada_mp = NULL;
15218 	ipha_t		*inner_ipha;
15219 
15220 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
15221 	    "ip_rput_locl_start: q %p", q);
15222 
15223 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
15224 
15225 
15226 #define	rptr	((uchar_t *)ipha)
15227 #define	iphs	((uint16_t *)ipha)
15228 
15229 	/*
15230 	 * no UDP or TCP packet should come here anymore.
15231 	 */
15232 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
15233 	    (ipha->ipha_protocol != IPPROTO_UDP));
15234 
15235 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
15236 /* EXPORT DELETE START */
15237 	if (mctl_present &&
15238 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
15239 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
15240 
15241 		/*
15242 		 * It's an IPsec accelerated packet.
15243 		 * Keep a pointer to the data attributes around until
15244 		 * we allocate the ipsec_info_t.
15245 		 */
15246 		IPSECHW_DEBUG(IPSECHW_PKT,
15247 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
15248 		hada_mp = first_mp;
15249 		hada_mp->b_cont = NULL;
15250 		/*
15251 		 * Since it is accelerated, it comes directly from
15252 		 * the ill and the data attributes is followed by
15253 		 * the packet data.
15254 		 */
15255 		ASSERT(mp->b_datap->db_type != M_CTL);
15256 		first_mp = mp;
15257 		mctl_present = B_FALSE;
15258 	}
15259 /* EXPORT DELETE END */
15260 
15261 	/*
15262 	 * IF M_CTL is not present, then ipsec_in_is_secure
15263 	 * should return B_TRUE. There is a case where loopback
15264 	 * packets has an M_CTL in the front with all the
15265 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
15266 	 * ipsec_in_is_secure will return B_FALSE. As loopback
15267 	 * packets never comes here, it is safe to ASSERT the
15268 	 * following.
15269 	 */
15270 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
15271 
15272 
15273 	/* u1 is # words of IP options */
15274 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
15275 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
15276 
15277 	if (u1) {
15278 		if (!ip_options_cksum(q, mp, ipha, ire)) {
15279 			if (hada_mp != NULL)
15280 				freemsg(hada_mp);
15281 			return;
15282 		}
15283 	} else {
15284 		/* Check the IP header checksum.  */
15285 #define	uph	((uint16_t *)ipha)
15286 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
15287 		    uph[6] + uph[7] + uph[8] + uph[9];
15288 #undef  uph
15289 		/* finish doing IP checksum */
15290 		sum = (sum & 0xFFFF) + (sum >> 16);
15291 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
15292 		/*
15293 		 * Don't verify header checksum if this packet is coming
15294 		 * back from AH/ESP as we already did it.
15295 		 */
15296 		if (!mctl_present && (sum && sum != 0xFFFF)) {
15297 			BUMP_MIB(&ip_mib, ipInCksumErrs);
15298 			goto drop_pkt;
15299 		}
15300 	}
15301 
15302 	/*
15303 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
15304 	 * might be called more than once for secure packets, count only
15305 	 * the first time.
15306 	 */
15307 	if (!mctl_present) {
15308 		UPDATE_IB_PKT_COUNT(ire);
15309 		ire->ire_last_used_time = lbolt;
15310 	}
15311 
15312 	/* Check for fragmentation offset. */
15313 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
15314 	u1 = u2 & (IPH_MF | IPH_OFFSET);
15315 	if (u1) {
15316 		/*
15317 		 * We re-assemble fragments before we do the AH/ESP
15318 		 * processing. Thus, M_CTL should not be present
15319 		 * while we are re-assembling.
15320 		 */
15321 		ASSERT(!mctl_present);
15322 		ASSERT(first_mp == mp);
15323 		if (!ip_rput_fragment(q, &mp, ipha)) {
15324 			return;
15325 		}
15326 		/*
15327 		 * Make sure that first_mp points back to mp as
15328 		 * the mp we came in with could have changed in
15329 		 * ip_rput_fragment().
15330 		 */
15331 		ipha = (ipha_t *)mp->b_rptr;
15332 		first_mp = mp;
15333 	}
15334 
15335 	/*
15336 	 * Clear hardware checksumming flag as it is currently only
15337 	 * used by TCP and UDP.
15338 	 */
15339 	mp->b_datap->db_struioun.cksum.flags = 0;
15340 
15341 	/* Now we have a complete datagram, destined for this machine. */
15342 	u1 = IPH_HDR_LENGTH(ipha);
15343 	switch (ipha->ipha_protocol) {
15344 	case IPPROTO_ICMP: {
15345 		ire_t		*ire_zone;
15346 		ilm_t		*ilm;
15347 		mblk_t		*mp1;
15348 		zoneid_t	last_zoneid;
15349 
15350 		if (CLASSD(ipha->ipha_dst) &&
15351 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
15352 			ASSERT(ire->ire_type == IRE_BROADCAST);
15353 			/*
15354 			 * In the multicast case, applications may have joined
15355 			 * the group from different zones, so we need to deliver
15356 			 * the packet to each of them. Loop through the
15357 			 * multicast memberships structures (ilm) on the receive
15358 			 * ill and send a copy of the packet up each matching
15359 			 * one. However, we don't do this for multicasts sent on
15360 			 * the loopback interface (PHYI_LOOPBACK flag set) as
15361 			 * they must stay in the sender's zone.
15362 			 *
15363 			 * ilm_add_v6() ensures that ilms in the same zone are
15364 			 * contiguous in the ill_ilm list. We use this property
15365 			 * to avoid sending duplicates needed when two
15366 			 * applications in the same zone join the same group on
15367 			 * different logical interfaces: we ignore the ilm if
15368 			 * its zoneid is the same as the last matching one.
15369 			 * In addition, the sending of the packet for
15370 			 * ire_zoneid is delayed until all of the other ilms
15371 			 * have been exhausted.
15372 			 */
15373 			last_zoneid = -1;
15374 			ILM_WALKER_HOLD(recv_ill);
15375 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
15376 			    ilm = ilm->ilm_next) {
15377 				if ((ilm->ilm_flags & ILM_DELETED) ||
15378 				    ipha->ipha_dst != ilm->ilm_addr ||
15379 				    ilm->ilm_zoneid == last_zoneid ||
15380 				    ilm->ilm_zoneid == ire->ire_zoneid ||
15381 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
15382 					continue;
15383 				mp1 = ip_copymsg(first_mp);
15384 				if (mp1 == NULL)
15385 					continue;
15386 				icmp_inbound(q, mp1, B_TRUE, ill,
15387 				    0, sum, mctl_present, B_TRUE,
15388 				    recv_ill, ilm->ilm_zoneid);
15389 				last_zoneid = ilm->ilm_zoneid;
15390 			}
15391 			ILM_WALKER_RELE(recv_ill);
15392 		} else if (ire->ire_type == IRE_BROADCAST) {
15393 			/*
15394 			 * In the broadcast case, there may be many zones
15395 			 * which need a copy of the packet delivered to them.
15396 			 * There is one IRE_BROADCAST per broadcast address
15397 			 * and per zone; we walk those using a helper function.
15398 			 * In addition, the sending of the packet for ire is
15399 			 * delayed until all of the other ires have been
15400 			 * processed.
15401 			 */
15402 			IRB_REFHOLD(ire->ire_bucket);
15403 			ire_zone = NULL;
15404 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
15405 			    ire)) != NULL) {
15406 				mp1 = ip_copymsg(first_mp);
15407 				if (mp1 == NULL)
15408 					continue;
15409 
15410 				UPDATE_IB_PKT_COUNT(ire_zone);
15411 				ire_zone->ire_last_used_time = lbolt;
15412 				icmp_inbound(q, mp1, B_TRUE, ill,
15413 				    0, sum, mctl_present, B_TRUE,
15414 				    recv_ill, ire_zone->ire_zoneid);
15415 			}
15416 			IRB_REFRELE(ire->ire_bucket);
15417 		}
15418 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
15419 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
15420 		    ire->ire_zoneid);
15421 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15422 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
15423 		return;
15424 	}
15425 	case IPPROTO_IGMP:
15426 		/*
15427 		 * If we are not willing to accept IGMP packets in clear,
15428 		 * then check with global policy.
15429 		 */
15430 		if (igmp_accept_clear_messages == 0) {
15431 			first_mp = ipsec_check_global_policy(first_mp, NULL,
15432 			    ipha, NULL, mctl_present);
15433 			if (first_mp == NULL)
15434 				return;
15435 		}
15436 		if (igmp_input(q, mp, ill)) {
15437 			/* Bad packet - discarded by igmp_input */
15438 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15439 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
15440 			if (mctl_present)
15441 				freeb(first_mp);
15442 			return;
15443 		}
15444 		/*
15445 		 * igmp_input() may have pulled up the message so ipha needs to
15446 		 * be reinitialized.
15447 		 */
15448 		ipha = (ipha_t *)mp->b_rptr;
15449 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
15450 			/* No user-level listener for IGMP packets */
15451 			goto drop_pkt;
15452 		}
15453 		/* deliver to local raw users */
15454 		break;
15455 	case IPPROTO_PIM:
15456 		/*
15457 		 * If we are not willing to accept PIM packets in clear,
15458 		 * then check with global policy.
15459 		 */
15460 		if (pim_accept_clear_messages == 0) {
15461 			first_mp = ipsec_check_global_policy(first_mp, NULL,
15462 			    ipha, NULL, mctl_present);
15463 			if (first_mp == NULL)
15464 				return;
15465 		}
15466 		if (pim_input(q, mp) != 0) {
15467 			/* Bad packet - discarded by pim_input */
15468 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15469 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
15470 			if (mctl_present)
15471 				freeb(first_mp);
15472 			return;
15473 		}
15474 
15475 		/*
15476 		 * pim_input() may have pulled up the message so ipha needs to
15477 		 * be reinitialized.
15478 		 */
15479 		ipha = (ipha_t *)mp->b_rptr;
15480 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
15481 			/* No user-level listener for PIM packets */
15482 			goto drop_pkt;
15483 		}
15484 		/* deliver to local raw users */
15485 		break;
15486 	case IPPROTO_ENCAP:
15487 		/*
15488 		 * Handle self-encapsulated packets (IP-in-IP where
15489 		 * the inner addresses == the outer addresses).
15490 		 */
15491 		hdr_length = IPH_HDR_LENGTH(ipha);
15492 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
15493 		    mp->b_wptr) {
15494 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
15495 			    sizeof (ipha_t) - mp->b_rptr)) {
15496 				BUMP_MIB(&ip_mib, ipInDiscards);
15497 				freemsg(first_mp);
15498 				return;
15499 			}
15500 			ipha = (ipha_t *)mp->b_rptr;
15501 		}
15502 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
15503 		/*
15504 		 * Check the sanity of the inner IP header.
15505 		 */
15506 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
15507 			BUMP_MIB(&ip_mib, ipInDiscards);
15508 			freemsg(first_mp);
15509 			return;
15510 		}
15511 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
15512 			BUMP_MIB(&ip_mib, ipInDiscards);
15513 			freemsg(first_mp);
15514 			return;
15515 		}
15516 		if (inner_ipha->ipha_src == ipha->ipha_src &&
15517 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
15518 			ipsec_in_t *ii;
15519 
15520 			/*
15521 			 * Self-encapsulated tunnel packet. Remove
15522 			 * the outer IP header and fanout again.
15523 			 * We also need to make sure that the inner
15524 			 * header is pulled up until options.
15525 			 */
15526 			mp->b_rptr = (uchar_t *)inner_ipha;
15527 			ipha = inner_ipha;
15528 			hdr_length = IPH_HDR_LENGTH(ipha);
15529 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
15530 				if (!pullupmsg(mp, (uchar_t *)ipha +
15531 				    + hdr_length - mp->b_rptr)) {
15532 					freemsg(first_mp);
15533 					return;
15534 				}
15535 				ipha = (ipha_t *)mp->b_rptr;
15536 			}
15537 			if (!mctl_present) {
15538 				ASSERT(first_mp == mp);
15539 				/*
15540 				 * This means that somebody is sending
15541 				 * Self-encapsualted packets without AH/ESP.
15542 				 * If AH/ESP was present, we would have already
15543 				 * allocated the first_mp.
15544 				 */
15545 				if ((first_mp = ipsec_in_alloc(B_TRUE)) ==
15546 				    NULL) {
15547 					ip1dbg(("ip_proto_input: IPSEC_IN "
15548 					    "allocation failure.\n"));
15549 					BUMP_MIB(&ip_mib, ipInDiscards);
15550 					freemsg(mp);
15551 					return;
15552 				}
15553 				first_mp->b_cont = mp;
15554 			}
15555 			/*
15556 			 * We generally store the ill_index if we need to
15557 			 * do IPSEC processing as we lose the ill queue when
15558 			 * we come back. But in this case, we never should
15559 			 * have to store the ill_index here as it should have
15560 			 * been stored previously when we processed the
15561 			 * AH/ESP header in this routine or for non-ipsec
15562 			 * cases, we still have the queue. But for some bad
15563 			 * packets from the wire, we can get to IPSEC after
15564 			 * this and we better store the index for that case.
15565 			 */
15566 			ill = (ill_t *)q->q_ptr;
15567 			ii = (ipsec_in_t *)first_mp->b_rptr;
15568 			ii->ipsec_in_ill_index =
15569 			    ill->ill_phyint->phyint_ifindex;
15570 			ii->ipsec_in_rill_index =
15571 			    recv_ill->ill_phyint->phyint_ifindex;
15572 			if (ii->ipsec_in_decaps) {
15573 				/*
15574 				 * This packet is self-encapsulated multiple
15575 				 * times. We don't want to recurse infinitely.
15576 				 * To keep it simple, drop the packet.
15577 				 */
15578 				BUMP_MIB(&ip_mib, ipInDiscards);
15579 				freemsg(first_mp);
15580 				return;
15581 			}
15582 			ii->ipsec_in_decaps = B_TRUE;
15583 			ip_proto_input(q, first_mp, ipha, ire, recv_ill);
15584 			return;
15585 		}
15586 		break;
15587 	case IPPROTO_AH:
15588 	case IPPROTO_ESP: {
15589 		/*
15590 		 * Fast path for AH/ESP. If this is the first time
15591 		 * we are sending a datagram to AH/ESP, allocate
15592 		 * a IPSEC_IN message and prepend it. Otherwise,
15593 		 * just fanout.
15594 		 */
15595 
15596 		int ipsec_rc;
15597 		ipsec_in_t *ii;
15598 
15599 		IP_STAT(ipsec_proto_ahesp);
15600 		if (!mctl_present) {
15601 			ASSERT(first_mp == mp);
15602 			if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
15603 				ip1dbg(("ip_proto_input: IPSEC_IN "
15604 				    "allocation failure.\n"));
15605 				freemsg(hada_mp); /* okay ifnull */
15606 				BUMP_MIB(&ip_mib, ipInDiscards);
15607 				freemsg(mp);
15608 				return;
15609 			}
15610 			/*
15611 			 * Store the ill_index so that when we come back
15612 			 * from IPSEC we ride on the same queue.
15613 			 */
15614 			ill = (ill_t *)q->q_ptr;
15615 			ii = (ipsec_in_t *)first_mp->b_rptr;
15616 			ii->ipsec_in_ill_index =
15617 			    ill->ill_phyint->phyint_ifindex;
15618 			ii->ipsec_in_rill_index =
15619 			    recv_ill->ill_phyint->phyint_ifindex;
15620 			first_mp->b_cont = mp;
15621 			/*
15622 			 * Cache hardware acceleration info.
15623 			 */
15624 			if (hada_mp != NULL) {
15625 				IPSECHW_DEBUG(IPSECHW_PKT,
15626 				    ("ip_rput_local: caching data attr.\n"));
15627 				ii->ipsec_in_accelerated = B_TRUE;
15628 				ii->ipsec_in_da = hada_mp;
15629 				hada_mp = NULL;
15630 			}
15631 		} else {
15632 			ii = (ipsec_in_t *)first_mp->b_rptr;
15633 		}
15634 
15635 		if (!ipsec_loaded()) {
15636 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
15637 			    ire->ire_zoneid);
15638 			return;
15639 		}
15640 
15641 		/* select inbound SA and have IPsec process the pkt */
15642 		if (ipha->ipha_protocol == IPPROTO_ESP) {
15643 			esph_t *esph = ipsec_inbound_esp_sa(first_mp);
15644 			if (esph == NULL)
15645 				return;
15646 			ASSERT(ii->ipsec_in_esp_sa != NULL);
15647 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
15648 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
15649 			    first_mp, esph);
15650 		} else {
15651 			ah_t *ah = ipsec_inbound_ah_sa(first_mp);
15652 			if (ah == NULL)
15653 				return;
15654 			ASSERT(ii->ipsec_in_ah_sa != NULL);
15655 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
15656 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
15657 			    first_mp, ah);
15658 		}
15659 
15660 		switch (ipsec_rc) {
15661 		case IPSEC_STATUS_SUCCESS:
15662 			break;
15663 		case IPSEC_STATUS_FAILED:
15664 			BUMP_MIB(&ip_mib, ipInDiscards);
15665 			/* FALLTHRU */
15666 		case IPSEC_STATUS_PENDING:
15667 			return;
15668 		}
15669 		/* we're done with IPsec processing, send it up */
15670 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
15671 		return;
15672 	}
15673 	default:
15674 		break;
15675 	}
15676 	/*
15677 	 * Handle protocols with which IP is less intimate.  There
15678 	 * can be more than one stream bound to a particular
15679 	 * protocol.  When this is the case, each one gets a copy
15680 	 * of any incoming packets.
15681 	 */
15682 	ip_fanout_proto(q, first_mp, ill, ipha,
15683 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
15684 	    B_TRUE, recv_ill, ire->ire_zoneid);
15685 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15686 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
15687 	return;
15688 
15689 drop_pkt:
15690 	freemsg(first_mp);
15691 	if (hada_mp != NULL)
15692 		freeb(hada_mp);
15693 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15694 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
15695 #undef	rptr
15696 #undef  iphs
15697 
15698 }
15699 
15700 /*
15701  * Update any source route, record route or timestamp options.
15702  * Check that we are at end of strict source route.
15703  * The options have already been checked for sanity in ip_rput_options().
15704  */
15705 static boolean_t
15706 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
15707 {
15708 	ipoptp_t	opts;
15709 	uchar_t		*opt;
15710 	uint8_t		optval;
15711 	uint8_t		optlen;
15712 	ipaddr_t	dst;
15713 	uint32_t	ts;
15714 	ire_t		*dst_ire;
15715 	timestruc_t	now;
15716 
15717 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
15718 
15719 	ip2dbg(("ip_rput_local_options\n"));
15720 
15721 	for (optval = ipoptp_first(&opts, ipha);
15722 	    optval != IPOPT_EOL;
15723 	    optval = ipoptp_next(&opts)) {
15724 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
15725 		opt = opts.ipoptp_cur;
15726 		optlen = opts.ipoptp_len;
15727 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
15728 		    optval, optlen));
15729 		switch (optval) {
15730 			uint32_t off;
15731 		case IPOPT_SSRR:
15732 		case IPOPT_LSRR:
15733 			off = opt[IPOPT_OFFSET];
15734 			off--;
15735 			if (optlen < IP_ADDR_LEN ||
15736 			    off > optlen - IP_ADDR_LEN) {
15737 				/* End of source route */
15738 				ip1dbg(("ip_rput_local_options: end of SR\n"));
15739 				break;
15740 			}
15741 			/*
15742 			 * This will only happen if two consecutive entries
15743 			 * in the source route contains our address or if
15744 			 * it is a packet with a loose source route which
15745 			 * reaches us before consuming the whole source route
15746 			 */
15747 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
15748 			if (optval == IPOPT_SSRR) {
15749 				goto bad_src_route;
15750 			}
15751 			/*
15752 			 * Hack: instead of dropping the packet truncate the
15753 			 * source route to what has been used by filling the
15754 			 * rest with IPOPT_NOP.
15755 			 */
15756 			opt[IPOPT_OLEN] = (uint8_t)off;
15757 			while (off < optlen) {
15758 				opt[off++] = IPOPT_NOP;
15759 			}
15760 			break;
15761 		case IPOPT_RR:
15762 			off = opt[IPOPT_OFFSET];
15763 			off--;
15764 			if (optlen < IP_ADDR_LEN ||
15765 			    off > optlen - IP_ADDR_LEN) {
15766 				/* No more room - ignore */
15767 				ip1dbg((
15768 				    "ip_rput_local_options: end of RR\n"));
15769 				break;
15770 			}
15771 			bcopy(&ire->ire_src_addr, (char *)opt + off,
15772 			    IP_ADDR_LEN);
15773 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15774 			break;
15775 		case IPOPT_TS:
15776 			/* Insert timestamp if there is romm */
15777 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15778 			case IPOPT_TS_TSONLY:
15779 				off = IPOPT_TS_TIMELEN;
15780 				break;
15781 			case IPOPT_TS_PRESPEC:
15782 			case IPOPT_TS_PRESPEC_RFC791:
15783 				/* Verify that the address matched */
15784 				off = opt[IPOPT_OFFSET] - 1;
15785 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
15786 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
15787 				    NULL, ALL_ZONES, MATCH_IRE_TYPE);
15788 				if (dst_ire == NULL) {
15789 					/* Not for us */
15790 					break;
15791 				}
15792 				ire_refrele(dst_ire);
15793 				/* FALLTHRU */
15794 			case IPOPT_TS_TSANDADDR:
15795 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
15796 				break;
15797 			default:
15798 				/*
15799 				 * ip_*put_options should have already
15800 				 * dropped this packet.
15801 				 */
15802 				cmn_err(CE_PANIC, "ip_rput_local_options: "
15803 				    "unknown IT - bug in ip_rput_options?\n");
15804 				return (B_TRUE);	/* Keep "lint" happy */
15805 			}
15806 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
15807 				/* Increase overflow counter */
15808 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
15809 				opt[IPOPT_POS_OV_FLG] =
15810 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
15811 				    (off << 4));
15812 				break;
15813 			}
15814 			off = opt[IPOPT_OFFSET] - 1;
15815 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15816 			case IPOPT_TS_PRESPEC:
15817 			case IPOPT_TS_PRESPEC_RFC791:
15818 			case IPOPT_TS_TSANDADDR:
15819 				bcopy(&ire->ire_src_addr, (char *)opt + off,
15820 				    IP_ADDR_LEN);
15821 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15822 				/* FALLTHRU */
15823 			case IPOPT_TS_TSONLY:
15824 				off = opt[IPOPT_OFFSET] - 1;
15825 				/* Compute # of milliseconds since midnight */
15826 				gethrestime(&now);
15827 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
15828 				    now.tv_nsec / (NANOSEC / MILLISEC);
15829 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
15830 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
15831 				break;
15832 			}
15833 			break;
15834 		}
15835 	}
15836 	return (B_TRUE);
15837 
15838 bad_src_route:
15839 	q = WR(q);
15840 	/* make sure we clear any indication of a hardware checksum */
15841 	mp->b_datap->db_struioun.cksum.flags = 0;
15842 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
15843 	return (B_FALSE);
15844 
15845 }
15846 
15847 /*
15848  * Process IP options in an inbound packet.  If an option affects the
15849  * effective destination address, return the next hop address via dstp.
15850  * Returns -1 if something fails in which case an ICMP error has been sent
15851  * and mp freed.
15852  */
15853 static int
15854 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp)
15855 {
15856 	ipoptp_t	opts;
15857 	uchar_t		*opt;
15858 	uint8_t		optval;
15859 	uint8_t		optlen;
15860 	ipaddr_t	dst;
15861 	intptr_t	code = 0;
15862 	ire_t		*ire = NULL;
15863 
15864 	ip2dbg(("ip_rput_options\n"));
15865 	dst = ipha->ipha_dst;
15866 	for (optval = ipoptp_first(&opts, ipha);
15867 	    optval != IPOPT_EOL;
15868 	    optval = ipoptp_next(&opts)) {
15869 		opt = opts.ipoptp_cur;
15870 		optlen = opts.ipoptp_len;
15871 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
15872 		    optval, optlen));
15873 		/*
15874 		 * Note: we need to verify the checksum before we
15875 		 * modify anything thus this routine only extracts the next
15876 		 * hop dst from any source route.
15877 		 */
15878 		switch (optval) {
15879 			uint32_t off;
15880 		case IPOPT_SSRR:
15881 		case IPOPT_LSRR:
15882 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
15883 			    ALL_ZONES, MATCH_IRE_TYPE);
15884 			if (ire == NULL) {
15885 				if (optval == IPOPT_SSRR) {
15886 					ip1dbg(("ip_rput_options: not next"
15887 					    " strict source route 0x%x\n",
15888 					    ntohl(dst)));
15889 					code = (char *)&ipha->ipha_dst -
15890 					    (char *)ipha;
15891 					goto param_prob; /* RouterReq's */
15892 				}
15893 				ip2dbg(("ip_rput_options: "
15894 				    "not next source route 0x%x\n",
15895 				    ntohl(dst)));
15896 				break;
15897 			}
15898 			ire_refrele(ire);
15899 
15900 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
15901 				ip1dbg((
15902 				    "ip_rput_options: bad option offset\n"));
15903 				code = (char *)&opt[IPOPT_OLEN] -
15904 				    (char *)ipha;
15905 				goto param_prob;
15906 			}
15907 			off = opt[IPOPT_OFFSET];
15908 			off--;
15909 		redo_srr:
15910 			if (optlen < IP_ADDR_LEN ||
15911 			    off > optlen - IP_ADDR_LEN) {
15912 				/* End of source route */
15913 				ip1dbg(("ip_rput_options: end of SR\n"));
15914 				break;
15915 			}
15916 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
15917 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
15918 			    ntohl(dst)));
15919 
15920 			/*
15921 			 * Check if our address is present more than
15922 			 * once as consecutive hops in source route.
15923 			 * XXX verify per-interface ip_forwarding
15924 			 * for source route?
15925 			 */
15926 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
15927 			    ALL_ZONES, MATCH_IRE_TYPE);
15928 
15929 			if (ire != NULL) {
15930 				ire_refrele(ire);
15931 				off += IP_ADDR_LEN;
15932 				goto redo_srr;
15933 			}
15934 
15935 			if (dst == htonl(INADDR_LOOPBACK)) {
15936 				ip1dbg(("ip_rput_options: loopback addr in "
15937 				    "source route!\n"));
15938 				goto bad_src_route;
15939 			}
15940 			/*
15941 			 * For strict: verify that dst is directly
15942 			 * reachable.
15943 			 */
15944 			if (optval == IPOPT_SSRR) {
15945 				ire = ire_ftable_lookup(dst, 0, 0,
15946 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
15947 				    MATCH_IRE_TYPE);
15948 				if (ire == NULL) {
15949 					ip1dbg(("ip_rput_options: SSRR not "
15950 					    "directly reachable: 0x%x\n",
15951 					    ntohl(dst)));
15952 					goto bad_src_route;
15953 				}
15954 				ire_refrele(ire);
15955 			}
15956 			/*
15957 			 * Defer update of the offset and the record route
15958 			 * until the packet is forwarded.
15959 			 */
15960 			break;
15961 		case IPOPT_RR:
15962 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
15963 				ip1dbg((
15964 				    "ip_rput_options: bad option offset\n"));
15965 				code = (char *)&opt[IPOPT_OLEN] -
15966 				    (char *)ipha;
15967 				goto param_prob;
15968 			}
15969 			break;
15970 		case IPOPT_TS:
15971 			/*
15972 			 * Verify that length >= 5 and that there is either
15973 			 * room for another timestamp or that the overflow
15974 			 * counter is not maxed out.
15975 			 */
15976 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
15977 			if (optlen < IPOPT_MINLEN_IT) {
15978 				goto param_prob;
15979 			}
15980 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
15981 				ip1dbg((
15982 				    "ip_rput_options: bad option offset\n"));
15983 				code = (char *)&opt[IPOPT_OFFSET] -
15984 				    (char *)ipha;
15985 				goto param_prob;
15986 			}
15987 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15988 			case IPOPT_TS_TSONLY:
15989 				off = IPOPT_TS_TIMELEN;
15990 				break;
15991 			case IPOPT_TS_TSANDADDR:
15992 			case IPOPT_TS_PRESPEC:
15993 			case IPOPT_TS_PRESPEC_RFC791:
15994 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
15995 				break;
15996 			default:
15997 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
15998 				    (char *)ipha;
15999 				goto param_prob;
16000 			}
16001 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
16002 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
16003 				/*
16004 				 * No room and the overflow counter is 15
16005 				 * already.
16006 				 */
16007 				goto param_prob;
16008 			}
16009 			break;
16010 		}
16011 	}
16012 
16013 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
16014 		*dstp = dst;
16015 		return (0);
16016 	}
16017 
16018 	ip1dbg(("ip_rput_options: error processing IP options."));
16019 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
16020 
16021 param_prob:
16022 	q = WR(q);
16023 	/* make sure we clear any indication of a hardware checksum */
16024 	mp->b_datap->db_struioun.cksum.flags = 0;
16025 	icmp_param_problem(q, mp, (uint8_t)code);
16026 	return (-1);
16027 
16028 bad_src_route:
16029 	q = WR(q);
16030 	/* make sure we clear any indication of a hardware checksum */
16031 	mp->b_datap->db_struioun.cksum.flags = 0;
16032 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
16033 	return (-1);
16034 }
16035 
16036 /*
16037  * IP & ICMP info in >=14 msg's ...
16038  *  - ip fixed part (mib2_ip_t)
16039  *  - icmp fixed part (mib2_icmp_t)
16040  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
16041  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
16042  *  - ipNetToMediaEntryTable (ip 22)	IPv4 IREs for on-link destinations
16043  *  - ip multicast membership (ip_member_t)
16044  *  - ip multicast source filtering (ip_grpsrc_t)
16045  *  - igmp fixed part (struct igmpstat)
16046  *  - multicast routing stats (struct mrtstat)
16047  *  - multicast routing vifs (array of struct vifctl)
16048  *  - multicast routing routes (array of struct mfcctl)
16049  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
16050  *					One per ill plus one generic
16051  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
16052  *					One per ill plus one generic
16053  *  - ipv6RouteEntry			all IPv6 IREs
16054  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
16055  *  - ipv6AddrEntry			all IPv6 ipifs
16056  *  - ipv6 multicast membership (ipv6_member_t)
16057  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
16058  *
16059  * IP_ROUTE and IP_MEDIA are augmented in arp to include arp cache entries not
16060  * already present.
16061  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part
16062  * already filled in by caller.
16063  * Return value of 0 indicates that no messages were sent and caller
16064  * should free mpctl.
16065  */
16066 int
16067 ip_snmp_get(queue_t *q, mblk_t *mpctl)
16068 {
16069 
16070 	if (mpctl == NULL || mpctl->b_cont == NULL) {
16071 		return (0);
16072 	}
16073 
16074 	if ((mpctl = ip_snmp_get_mib2_ip(q, mpctl)) == NULL) {
16075 		return (1);
16076 	}
16077 
16078 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl)) == NULL) {
16079 		return (1);
16080 	}
16081 
16082 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl)) == NULL) {
16083 		return (1);
16084 	}
16085 
16086 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl)) == NULL) {
16087 		return (1);
16088 	}
16089 
16090 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl)) == NULL) {
16091 		return (1);
16092 	}
16093 
16094 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl)) == NULL) {
16095 		return (1);
16096 	}
16097 
16098 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl)) == NULL) {
16099 		return (1);
16100 	}
16101 
16102 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl)) == NULL) {
16103 		return (1);
16104 	}
16105 
16106 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl)) == NULL) {
16107 		return (1);
16108 	}
16109 
16110 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl)) == NULL) {
16111 		return (1);
16112 	}
16113 
16114 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl)) == NULL) {
16115 		return (1);
16116 	}
16117 
16118 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl)) == NULL) {
16119 		return (1);
16120 	}
16121 
16122 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl)) == NULL) {
16123 		return (1);
16124 	}
16125 
16126 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl)) == NULL) {
16127 		return (1);
16128 	}
16129 
16130 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl)) == NULL) {
16131 		return (1);
16132 	}
16133 
16134 	if ((mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl)) == NULL) {
16135 		return (1);
16136 	}
16137 
16138 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl)) == NULL) {
16139 		return (1);
16140 	}
16141 	freemsg(mpctl);
16142 	return (1);
16143 }
16144 
16145 
16146 /* Get global IPv4 statistics */
16147 static mblk_t *
16148 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl)
16149 {
16150 	struct opthdr		*optp;
16151 	mblk_t			*mp2ctl;
16152 
16153 	/*
16154 	 * make a copy of the original message
16155 	 */
16156 	mp2ctl = copymsg(mpctl);
16157 
16158 	/* fixed length IP structure... */
16159 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16160 	optp->level = MIB2_IP;
16161 	optp->name = 0;
16162 	SET_MIB(ip_mib.ipForwarding,
16163 	    (WE_ARE_FORWARDING ? 1 : 2));
16164 	SET_MIB(ip_mib.ipDefaultTTL,
16165 	    (uint32_t)ip_def_ttl);
16166 	SET_MIB(ip_mib.ipReasmTimeout,
16167 	    ip_g_frag_timeout);
16168 	SET_MIB(ip_mib.ipAddrEntrySize,
16169 	    sizeof (mib2_ipAddrEntry_t));
16170 	SET_MIB(ip_mib.ipRouteEntrySize,
16171 	    sizeof (mib2_ipRouteEntry_t));
16172 	SET_MIB(ip_mib.ipNetToMediaEntrySize,
16173 	    sizeof (mib2_ipNetToMediaEntry_t));
16174 	SET_MIB(ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
16175 	SET_MIB(ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
16176 	if (!snmp_append_data(mpctl->b_cont, (char *)&ip_mib,
16177 	    (int)sizeof (ip_mib))) {
16178 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
16179 		    (uint_t)sizeof (ip_mib)));
16180 	}
16181 
16182 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16183 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
16184 	    (int)optp->level, (int)optp->name, (int)optp->len));
16185 	qreply(q, mpctl);
16186 	return (mp2ctl);
16187 }
16188 
16189 /* Global IPv4 ICMP statistics */
16190 static mblk_t *
16191 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl)
16192 {
16193 	struct opthdr		*optp;
16194 	mblk_t			*mp2ctl;
16195 
16196 	/*
16197 	 * Make a copy of the original message
16198 	 */
16199 	mp2ctl = copymsg(mpctl);
16200 
16201 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16202 	optp->level = MIB2_ICMP;
16203 	optp->name = 0;
16204 	if (!snmp_append_data(mpctl->b_cont, (char *)&icmp_mib,
16205 	    (int)sizeof (icmp_mib))) {
16206 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
16207 		    (uint_t)sizeof (icmp_mib)));
16208 	}
16209 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16210 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
16211 	    (int)optp->level, (int)optp->name, (int)optp->len));
16212 	qreply(q, mpctl);
16213 	return (mp2ctl);
16214 }
16215 
16216 /* Global IPv4 IGMP statistics */
16217 static mblk_t *
16218 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl)
16219 {
16220 	struct opthdr		*optp;
16221 	mblk_t			*mp2ctl;
16222 
16223 	/*
16224 	 * make a copy of the original message
16225 	 */
16226 	mp2ctl = copymsg(mpctl);
16227 
16228 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16229 	optp->level = EXPER_IGMP;
16230 	optp->name = 0;
16231 	if (!snmp_append_data(mpctl->b_cont, (char *)&igmpstat,
16232 	    (int)sizeof (igmpstat))) {
16233 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
16234 		    (uint_t)sizeof (igmpstat)));
16235 	}
16236 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16237 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
16238 	    (int)optp->level, (int)optp->name, (int)optp->len));
16239 	qreply(q, mpctl);
16240 	return (mp2ctl);
16241 }
16242 
16243 /* Global IPv4 Multicast Routing statistics */
16244 static mblk_t *
16245 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl)
16246 {
16247 	struct opthdr		*optp;
16248 	mblk_t			*mp2ctl;
16249 
16250 	/*
16251 	 * make a copy of the original message
16252 	 */
16253 	mp2ctl = copymsg(mpctl);
16254 
16255 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16256 	optp->level = EXPER_DVMRP;
16257 	optp->name = 0;
16258 	if (!ip_mroute_stats(mpctl->b_cont)) {
16259 		ip0dbg(("ip_mroute_stats: failed\n"));
16260 	}
16261 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16262 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
16263 	    (int)optp->level, (int)optp->name, (int)optp->len));
16264 	qreply(q, mpctl);
16265 	return (mp2ctl);
16266 }
16267 
16268 /* IPv4 address information */
16269 static mblk_t *
16270 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl)
16271 {
16272 	struct opthdr		*optp;
16273 	mblk_t			*mp2ctl;
16274 	mblk_t			*mp_tail = NULL;
16275 	ill_t			*ill;
16276 	ipif_t			*ipif;
16277 	uint_t			bitval;
16278 	mib2_ipAddrEntry_t	mae;
16279 	zoneid_t		zoneid;
16280 	ill_walk_context_t ctx;
16281 
16282 	/*
16283 	 * make a copy of the original message
16284 	 */
16285 	mp2ctl = copymsg(mpctl);
16286 
16287 	/* ipAddrEntryTable */
16288 
16289 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16290 	optp->level = MIB2_IP;
16291 	optp->name = MIB2_IP_ADDR;
16292 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16293 
16294 	rw_enter(&ill_g_lock, RW_READER);
16295 	ill = ILL_START_WALK_V4(&ctx);
16296 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16297 		for (ipif = ill->ill_ipif; ipif != NULL;
16298 		    ipif = ipif->ipif_next) {
16299 			if (ipif->ipif_zoneid != zoneid)
16300 				continue;
16301 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
16302 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
16303 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
16304 
16305 			(void) ipif_get_name(ipif,
16306 			    mae.ipAdEntIfIndex.o_bytes,
16307 			    OCTET_LENGTH);
16308 			mae.ipAdEntIfIndex.o_length =
16309 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
16310 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
16311 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
16312 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
16313 			mae.ipAdEntInfo.ae_subnet_len =
16314 			    ip_mask_to_plen(ipif->ipif_net_mask);
16315 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
16316 			for (bitval = 1;
16317 			    bitval &&
16318 			    !(bitval & ipif->ipif_brd_addr);
16319 			    bitval <<= 1)
16320 				noop;
16321 			mae.ipAdEntBcastAddr = bitval;
16322 			mae.ipAdEntReasmMaxSize = 65535;
16323 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
16324 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
16325 			mae.ipAdEntInfo.ae_broadcast_addr =
16326 			    ipif->ipif_brd_addr;
16327 			mae.ipAdEntInfo.ae_pp_dst_addr =
16328 			    ipif->ipif_pp_dst_addr;
16329 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
16330 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
16331 
16332 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16333 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
16334 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
16335 				    "allocate %u bytes\n",
16336 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
16337 			}
16338 		}
16339 	}
16340 	rw_exit(&ill_g_lock);
16341 
16342 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16343 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
16344 	    (int)optp->level, (int)optp->name, (int)optp->len));
16345 	qreply(q, mpctl);
16346 	return (mp2ctl);
16347 }
16348 
16349 /* IPv6 address information */
16350 static mblk_t *
16351 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl)
16352 {
16353 	struct opthdr		*optp;
16354 	mblk_t			*mp2ctl;
16355 	mblk_t			*mp_tail = NULL;
16356 	ill_t			*ill;
16357 	ipif_t			*ipif;
16358 	mib2_ipv6AddrEntry_t	mae6;
16359 	zoneid_t		zoneid;
16360 	ill_walk_context_t	ctx;
16361 
16362 	/*
16363 	 * make a copy of the original message
16364 	 */
16365 	mp2ctl = copymsg(mpctl);
16366 
16367 	/* ipv6AddrEntryTable */
16368 
16369 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16370 	optp->level = MIB2_IP6;
16371 	optp->name = MIB2_IP6_ADDR;
16372 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16373 
16374 	rw_enter(&ill_g_lock, RW_READER);
16375 	ill = ILL_START_WALK_V6(&ctx);
16376 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16377 		for (ipif = ill->ill_ipif; ipif; ipif = ipif->ipif_next) {
16378 			if (ipif->ipif_zoneid != zoneid)
16379 				continue;
16380 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
16381 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
16382 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
16383 
16384 			(void) ipif_get_name(ipif,
16385 			    mae6.ipv6AddrIfIndex.o_bytes,
16386 			    OCTET_LENGTH);
16387 			mae6.ipv6AddrIfIndex.o_length =
16388 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
16389 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
16390 			mae6.ipv6AddrPfxLength =
16391 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
16392 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
16393 			mae6.ipv6AddrInfo.ae_subnet_len =
16394 			    mae6.ipv6AddrPfxLength;
16395 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
16396 
16397 			/* Type: stateless(1), stateful(2), unknown(3) */
16398 			if (ipif->ipif_flags & IPIF_ADDRCONF)
16399 				mae6.ipv6AddrType = 1;
16400 			else
16401 				mae6.ipv6AddrType = 2;
16402 			/* Anycast: true(1), false(2) */
16403 			if (ipif->ipif_flags & IPIF_ANYCAST)
16404 				mae6.ipv6AddrAnycastFlag = 1;
16405 			else
16406 				mae6.ipv6AddrAnycastFlag = 2;
16407 
16408 			/*
16409 			 * Address status: preferred(1), deprecated(2),
16410 			 * invalid(3), inaccessible(4), unknown(5)
16411 			 */
16412 			if (ipif->ipif_flags & IPIF_NOLOCAL)
16413 				mae6.ipv6AddrStatus = 3;
16414 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
16415 				mae6.ipv6AddrStatus = 2;
16416 			else
16417 				mae6.ipv6AddrStatus = 1;
16418 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
16419 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
16420 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
16421 						ipif->ipif_v6pp_dst_addr;
16422 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
16423 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
16424 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16425 				(char *)&mae6,
16426 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
16427 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
16428 				    "allocate %u bytes\n",
16429 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
16430 			}
16431 		}
16432 	}
16433 	rw_exit(&ill_g_lock);
16434 
16435 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16436 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
16437 	    (int)optp->level, (int)optp->name, (int)optp->len));
16438 	qreply(q, mpctl);
16439 	return (mp2ctl);
16440 }
16441 
16442 /* IPv4 multicast group membership. */
16443 static mblk_t *
16444 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl)
16445 {
16446 	struct opthdr		*optp;
16447 	mblk_t			*mp2ctl;
16448 	ill_t			*ill;
16449 	ipif_t			*ipif;
16450 	ilm_t			*ilm;
16451 	ip_member_t		ipm;
16452 	mblk_t			*mp_tail = NULL;
16453 	ill_walk_context_t	ctx;
16454 	zoneid_t		zoneid;
16455 
16456 	/*
16457 	 * make a copy of the original message
16458 	 */
16459 	mp2ctl = copymsg(mpctl);
16460 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16461 
16462 	/* ipGroupMember table */
16463 	optp = (struct opthdr *)&mpctl->b_rptr[
16464 	    sizeof (struct T_optmgmt_ack)];
16465 	optp->level = MIB2_IP;
16466 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
16467 
16468 	rw_enter(&ill_g_lock, RW_READER);
16469 	ill = ILL_START_WALK_V4(&ctx);
16470 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16471 		ILM_WALKER_HOLD(ill);
16472 		for (ipif = ill->ill_ipif; ipif != NULL;
16473 		    ipif = ipif->ipif_next) {
16474 			if (ipif->ipif_zoneid != zoneid)
16475 				continue;	/* not this zone */
16476 			(void) ipif_get_name(ipif,
16477 			    ipm.ipGroupMemberIfIndex.o_bytes,
16478 			    OCTET_LENGTH);
16479 			ipm.ipGroupMemberIfIndex.o_length =
16480 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
16481 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16482 				ASSERT(ilm->ilm_ipif != NULL);
16483 				ASSERT(ilm->ilm_ill == NULL);
16484 				if (ilm->ilm_ipif != ipif)
16485 					continue;
16486 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
16487 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
16488 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
16489 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16490 				    (char *)&ipm, (int)sizeof (ipm))) {
16491 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
16492 					    "failed to allocate %u bytes\n",
16493 						(uint_t)sizeof (ipm)));
16494 				}
16495 			}
16496 		}
16497 		ILM_WALKER_RELE(ill);
16498 	}
16499 	rw_exit(&ill_g_lock);
16500 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16501 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16502 	    (int)optp->level, (int)optp->name, (int)optp->len));
16503 	qreply(q, mpctl);
16504 	return (mp2ctl);
16505 }
16506 
16507 /* IPv6 multicast group membership. */
16508 static mblk_t *
16509 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl)
16510 {
16511 	struct opthdr		*optp;
16512 	mblk_t			*mp2ctl;
16513 	ill_t			*ill;
16514 	ilm_t			*ilm;
16515 	ipv6_member_t		ipm6;
16516 	mblk_t			*mp_tail = NULL;
16517 	ill_walk_context_t	ctx;
16518 	zoneid_t		zoneid;
16519 
16520 	/*
16521 	 * make a copy of the original message
16522 	 */
16523 	mp2ctl = copymsg(mpctl);
16524 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16525 
16526 	/* ip6GroupMember table */
16527 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16528 	optp->level = MIB2_IP6;
16529 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
16530 
16531 	rw_enter(&ill_g_lock, RW_READER);
16532 	ill = ILL_START_WALK_V6(&ctx);
16533 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16534 		ILM_WALKER_HOLD(ill);
16535 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
16536 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16537 			ASSERT(ilm->ilm_ipif == NULL);
16538 			ASSERT(ilm->ilm_ill != NULL);
16539 			if (ilm->ilm_zoneid != zoneid)
16540 				continue;	/* not this zone */
16541 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
16542 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
16543 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
16544 			if (!snmp_append_data2(mpctl->b_cont,
16545 			    &mp_tail,
16546 			    (char *)&ipm6, (int)sizeof (ipm6))) {
16547 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
16548 				    "failed to allocate %u bytes\n",
16549 				    (uint_t)sizeof (ipm6)));
16550 			}
16551 		}
16552 		ILM_WALKER_RELE(ill);
16553 	}
16554 	rw_exit(&ill_g_lock);
16555 
16556 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16557 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16558 	    (int)optp->level, (int)optp->name, (int)optp->len));
16559 	qreply(q, mpctl);
16560 	return (mp2ctl);
16561 }
16562 
16563 /* IP multicast filtered sources */
16564 static mblk_t *
16565 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl)
16566 {
16567 	struct opthdr		*optp;
16568 	mblk_t			*mp2ctl;
16569 	ill_t			*ill;
16570 	ipif_t			*ipif;
16571 	ilm_t			*ilm;
16572 	ip_grpsrc_t		ips;
16573 	mblk_t			*mp_tail = NULL;
16574 	ill_walk_context_t	ctx;
16575 	zoneid_t		zoneid;
16576 	int			i;
16577 	slist_t			*sl;
16578 
16579 	/*
16580 	 * make a copy of the original message
16581 	 */
16582 	mp2ctl = copymsg(mpctl);
16583 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16584 
16585 	/* ipGroupSource table */
16586 	optp = (struct opthdr *)&mpctl->b_rptr[
16587 	    sizeof (struct T_optmgmt_ack)];
16588 	optp->level = MIB2_IP;
16589 	optp->name = EXPER_IP_GROUP_SOURCES;
16590 
16591 	rw_enter(&ill_g_lock, RW_READER);
16592 	ill = ILL_START_WALK_V4(&ctx);
16593 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16594 		ILM_WALKER_HOLD(ill);
16595 		for (ipif = ill->ill_ipif; ipif != NULL;
16596 		    ipif = ipif->ipif_next) {
16597 			if (ipif->ipif_zoneid != zoneid)
16598 				continue;	/* not this zone */
16599 			(void) ipif_get_name(ipif,
16600 			    ips.ipGroupSourceIfIndex.o_bytes,
16601 			    OCTET_LENGTH);
16602 			ips.ipGroupSourceIfIndex.o_length =
16603 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
16604 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16605 				ASSERT(ilm->ilm_ipif != NULL);
16606 				ASSERT(ilm->ilm_ill == NULL);
16607 				sl = ilm->ilm_filter;
16608 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
16609 					continue;
16610 				ips.ipGroupSourceGroup = ilm->ilm_addr;
16611 				for (i = 0; i < sl->sl_numsrc; i++) {
16612 					if (!IN6_IS_ADDR_V4MAPPED(
16613 					    &sl->sl_addr[i]))
16614 						continue;
16615 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
16616 					    ips.ipGroupSourceAddress);
16617 					if (snmp_append_data2(mpctl->b_cont,
16618 					    &mp_tail, (char *)&ips,
16619 					    (int)sizeof (ips)) == 0) {
16620 						ip1dbg(("ip_snmp_get_mib2_"
16621 						    "ip_group_src: failed to "
16622 						    "allocate %u bytes\n",
16623 						    (uint_t)sizeof (ips)));
16624 					}
16625 				}
16626 			}
16627 		}
16628 		ILM_WALKER_RELE(ill);
16629 	}
16630 	rw_exit(&ill_g_lock);
16631 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16632 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16633 	    (int)optp->level, (int)optp->name, (int)optp->len));
16634 	qreply(q, mpctl);
16635 	return (mp2ctl);
16636 }
16637 
16638 /* IPv6 multicast filtered sources. */
16639 static mblk_t *
16640 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl)
16641 {
16642 	struct opthdr		*optp;
16643 	mblk_t			*mp2ctl;
16644 	ill_t			*ill;
16645 	ilm_t			*ilm;
16646 	ipv6_grpsrc_t		ips6;
16647 	mblk_t			*mp_tail = NULL;
16648 	ill_walk_context_t	ctx;
16649 	zoneid_t		zoneid;
16650 	int			i;
16651 	slist_t			*sl;
16652 
16653 	/*
16654 	 * make a copy of the original message
16655 	 */
16656 	mp2ctl = copymsg(mpctl);
16657 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16658 
16659 	/* ip6GroupMember table */
16660 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16661 	optp->level = MIB2_IP6;
16662 	optp->name = EXPER_IP6_GROUP_SOURCES;
16663 
16664 	rw_enter(&ill_g_lock, RW_READER);
16665 	ill = ILL_START_WALK_V6(&ctx);
16666 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16667 		ILM_WALKER_HOLD(ill);
16668 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
16669 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16670 			ASSERT(ilm->ilm_ipif == NULL);
16671 			ASSERT(ilm->ilm_ill != NULL);
16672 			sl = ilm->ilm_filter;
16673 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
16674 				continue;
16675 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
16676 			for (i = 0; i < sl->sl_numsrc; i++) {
16677 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
16678 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16679 				    (char *)&ips6, (int)sizeof (ips6))) {
16680 					ip1dbg(("ip_snmp_get_mib2_ip6_"
16681 					    "group_src: failed to allocate "
16682 					    "%u bytes\n",
16683 					    (uint_t)sizeof (ips6)));
16684 				}
16685 			}
16686 		}
16687 		ILM_WALKER_RELE(ill);
16688 	}
16689 	rw_exit(&ill_g_lock);
16690 
16691 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16692 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16693 	    (int)optp->level, (int)optp->name, (int)optp->len));
16694 	qreply(q, mpctl);
16695 	return (mp2ctl);
16696 }
16697 
16698 /* Multicast routing virtual interface table. */
16699 static mblk_t *
16700 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl)
16701 {
16702 	struct opthdr		*optp;
16703 	mblk_t			*mp2ctl;
16704 
16705 	/*
16706 	 * make a copy of the original message
16707 	 */
16708 	mp2ctl = copymsg(mpctl);
16709 
16710 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16711 	optp->level = EXPER_DVMRP;
16712 	optp->name = EXPER_DVMRP_VIF;
16713 	if (!ip_mroute_vif(mpctl->b_cont)) {
16714 		ip0dbg(("ip_mroute_vif: failed\n"));
16715 	}
16716 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16717 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
16718 	    (int)optp->level, (int)optp->name, (int)optp->len));
16719 	qreply(q, mpctl);
16720 	return (mp2ctl);
16721 }
16722 
16723 /* Multicast routing table. */
16724 static mblk_t *
16725 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl)
16726 {
16727 	struct opthdr		*optp;
16728 	mblk_t			*mp2ctl;
16729 
16730 	/*
16731 	 * make a copy of the original message
16732 	 */
16733 	mp2ctl = copymsg(mpctl);
16734 
16735 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16736 	optp->level = EXPER_DVMRP;
16737 	optp->name = EXPER_DVMRP_MRT;
16738 	if (!ip_mroute_mrt(mpctl->b_cont)) {
16739 		ip0dbg(("ip_mroute_mrt: failed\n"));
16740 	}
16741 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16742 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
16743 	    (int)optp->level, (int)optp->name, (int)optp->len));
16744 	qreply(q, mpctl);
16745 	return (mp2ctl);
16746 }
16747 
16748 /*
16749  * Return both ipRouteEntryTable, and ipNetToMediaEntryTable
16750  * in one IRE walk.
16751  */
16752 static mblk_t *
16753 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl)
16754 {
16755 	struct opthdr		*optp;
16756 	mblk_t			*mp2ctl;	/* Returned */
16757 	mblk_t			*mp3ctl;	/* nettomedia */
16758 	/*
16759 	 * We need two listptrs, for ipRouteEntryTable and
16760 	 * ipNetToMediaEntryTable to pass to ip_snmp_get2_v4()
16761 	 */
16762 	listptr_t		re_ntme_v4[2];
16763 	zoneid_t		zoneid;
16764 
16765 	/*
16766 	 * make a copy of the original message
16767 	 */
16768 	mp2ctl = copymsg(mpctl);
16769 	mp3ctl = copymsg(mpctl);
16770 	if (mp3ctl == NULL) {
16771 		freemsg(mp2ctl);
16772 		freemsg(mpctl);
16773 		return (NULL);
16774 	}
16775 
16776 	re_ntme_v4[0].lp_head = mpctl->b_cont;	/* ipRouteEntryTable */
16777 	re_ntme_v4[1].lp_head = mp3ctl->b_cont;	/* ipNetToMediaEntryTable */
16778 	/*
16779 	 * We assign NULL to tail ptrs as snmp_append_data2() will assign
16780 	 * proper values when called.
16781 	 */
16782 	re_ntme_v4[0].lp_tail = NULL;
16783 	re_ntme_v4[1].lp_tail = NULL;
16784 
16785 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16786 	ire_walk_v4(ip_snmp_get2_v4, (char *)re_ntme_v4, zoneid);
16787 	if (zoneid == GLOBAL_ZONEID) {
16788 		/*
16789 		 * Those IREs are used by Mobile-IP; since mipagent(1M) requires
16790 		 * the sys_net_config privilege, it can only run in the global
16791 		 * zone, so we don't display these IREs in the other zones.
16792 		 */
16793 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, (char *)re_ntme_v4);
16794 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, (char *)re_ntme_v4,
16795 		    NULL);
16796 	}
16797 
16798 	/* ipRouteEntryTable in mpctl */
16799 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16800 	optp->level = MIB2_IP;
16801 	optp->name = MIB2_IP_ROUTE;
16802 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v4[0].lp_head);
16803 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
16804 	    (int)optp->level, (int)optp->name, (int)optp->len));
16805 	qreply(q, mpctl);
16806 
16807 	/* ipNetToMediaEntryTable in mp3ctl */
16808 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16809 	optp->level = MIB2_IP;
16810 	optp->name = MIB2_IP_MEDIA;
16811 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v4[1].lp_head);
16812 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
16813 	    (int)optp->level, (int)optp->name, (int)optp->len));
16814 	qreply(q, mp3ctl);
16815 	return (mp2ctl);
16816 }
16817 
16818 /*
16819  * Return both ipv6RouteEntryTable, and ipv6NetToMediaEntryTable
16820  * in one IRE walk.
16821  */
16822 static mblk_t *
16823 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl)
16824 {
16825 	struct opthdr		*optp;
16826 	mblk_t			*mp2ctl;	/* Returned */
16827 	mblk_t			*mp3ctl;	/* nettomedia */
16828 	listptr_t		re_ntme_v6;
16829 	zoneid_t		zoneid;
16830 
16831 	/*
16832 	 * make a copy of the original message
16833 	 */
16834 	mp2ctl = copymsg(mpctl);
16835 	mp3ctl = copymsg(mpctl);
16836 	if (mp3ctl == NULL) {
16837 		freemsg(mp2ctl);
16838 		freemsg(mpctl);
16839 		return (NULL);
16840 	}
16841 
16842 	/*
16843 	 * We assign NULL to tail ptrs as snmp_append_data2() will assign
16844 	 * proper values when called.  ipv6RouteEntryTable in is placed
16845 	 * in mpctl.
16846 	 */
16847 	re_ntme_v6.lp_head = mpctl->b_cont;	/* ip6RouteEntryTable */
16848 	re_ntme_v6.lp_tail = NULL;
16849 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16850 	ire_walk_v6(ip_snmp_get2_v6_route, (char *)&re_ntme_v6, zoneid);
16851 
16852 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16853 	optp->level = MIB2_IP6;
16854 	optp->name = MIB2_IP6_ROUTE;
16855 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v6.lp_head);
16856 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
16857 	    (int)optp->level, (int)optp->name, (int)optp->len));
16858 	qreply(q, mpctl);
16859 
16860 	/* ipv6NetToMediaEntryTable in mp3ctl */
16861 	re_ntme_v6.lp_head = mp3ctl->b_cont;	/* ip6NetToMediaEntryTable */
16862 	re_ntme_v6.lp_tail = NULL;
16863 	ndp_walk(NULL, ip_snmp_get2_v6_media, (uchar_t *)&re_ntme_v6);
16864 
16865 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16866 	optp->level = MIB2_IP6;
16867 	optp->name = MIB2_IP6_MEDIA;
16868 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v6.lp_head);
16869 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
16870 	    (int)optp->level, (int)optp->name, (int)optp->len));
16871 	qreply(q, mp3ctl);
16872 	return (mp2ctl);
16873 }
16874 
16875 /*
16876  * ICMPv6 mib: One per ill
16877  */
16878 static mblk_t *
16879 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl)
16880 {
16881 	struct opthdr		*optp;
16882 	mblk_t			*mp2ctl;
16883 	ill_t			*ill;
16884 	ill_walk_context_t	ctx;
16885 	mblk_t			*mp_tail = NULL;
16886 
16887 	/*
16888 	 * Make a copy of the original message
16889 	 */
16890 	mp2ctl = copymsg(mpctl);
16891 
16892 	/* fixed length IPv6 structure ... */
16893 
16894 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16895 	optp->level = MIB2_IP6;
16896 	optp->name = 0;
16897 	/* Include "unknown interface" ip6_mib */
16898 	ip6_mib.ipv6IfIndex = 0;	/* Flag to netstat */
16899 	SET_MIB(ip6_mib.ipv6Forwarding, ipv6_forward ? 1 : 2);
16900 	SET_MIB(ip6_mib.ipv6DefaultHopLimit, ipv6_def_hops);
16901 	SET_MIB(ip6_mib.ipv6IfStatsEntrySize,
16902 	    sizeof (mib2_ipv6IfStatsEntry_t));
16903 	SET_MIB(ip6_mib.ipv6AddrEntrySize, sizeof (mib2_ipv6AddrEntry_t));
16904 	SET_MIB(ip6_mib.ipv6RouteEntrySize, sizeof (mib2_ipv6RouteEntry_t));
16905 	SET_MIB(ip6_mib.ipv6NetToMediaEntrySize,
16906 	    sizeof (mib2_ipv6NetToMediaEntry_t));
16907 	SET_MIB(ip6_mib.ipv6MemberEntrySize, sizeof (ipv6_member_t));
16908 	SET_MIB(ip6_mib.ipv6GroupSourceEntrySize, sizeof (ipv6_grpsrc_t));
16909 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip6_mib,
16910 	    (int)sizeof (ip6_mib))) {
16911 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
16912 		    (uint_t)sizeof (ip6_mib)));
16913 	}
16914 
16915 	rw_enter(&ill_g_lock, RW_READER);
16916 	ill = ILL_START_WALK_V6(&ctx);
16917 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16918 		ill->ill_ip6_mib->ipv6IfIndex =
16919 		    ill->ill_phyint->phyint_ifindex;
16920 		SET_MIB(ill->ill_ip6_mib->ipv6Forwarding,
16921 		    ipv6_forward ? 1 : 2);
16922 		SET_MIB(ill->ill_ip6_mib->ipv6DefaultHopLimit,
16923 		    ill->ill_max_hops);
16924 		SET_MIB(ill->ill_ip6_mib->ipv6IfStatsEntrySize,
16925 		    sizeof (mib2_ipv6IfStatsEntry_t));
16926 		SET_MIB(ill->ill_ip6_mib->ipv6AddrEntrySize,
16927 		    sizeof (mib2_ipv6AddrEntry_t));
16928 		SET_MIB(ill->ill_ip6_mib->ipv6RouteEntrySize,
16929 		    sizeof (mib2_ipv6RouteEntry_t));
16930 		SET_MIB(ill->ill_ip6_mib->ipv6NetToMediaEntrySize,
16931 		    sizeof (mib2_ipv6NetToMediaEntry_t));
16932 		SET_MIB(ill->ill_ip6_mib->ipv6MemberEntrySize,
16933 		    sizeof (ipv6_member_t));
16934 
16935 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16936 		    (char *)ill->ill_ip6_mib,
16937 		    (int)sizeof (*ill->ill_ip6_mib))) {
16938 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
16939 				"%u bytes\n",
16940 				(uint_t)sizeof (*ill->ill_ip6_mib)));
16941 		}
16942 	}
16943 	rw_exit(&ill_g_lock);
16944 
16945 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16946 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
16947 	    (int)optp->level, (int)optp->name, (int)optp->len));
16948 	qreply(q, mpctl);
16949 	return (mp2ctl);
16950 }
16951 
16952 /*
16953  * ICMPv6 mib: One per ill
16954  */
16955 static mblk_t *
16956 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl)
16957 {
16958 	struct opthdr		*optp;
16959 	mblk_t			*mp2ctl;
16960 	ill_t			*ill;
16961 	ill_walk_context_t	ctx;
16962 	mblk_t			*mp_tail = NULL;
16963 	/*
16964 	 * Make a copy of the original message
16965 	 */
16966 	mp2ctl = copymsg(mpctl);
16967 
16968 	/* fixed length ICMPv6 structure ... */
16969 
16970 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16971 	optp->level = MIB2_ICMP6;
16972 	optp->name = 0;
16973 	/* Include "unknown interface" icmp6_mib */
16974 	icmp6_mib.ipv6IfIcmpIfIndex = 0;	/* Flag to netstat */
16975 	icmp6_mib.ipv6IfIcmpEntrySize = sizeof (mib2_ipv6IfIcmpEntry_t);
16976 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&icmp6_mib,
16977 	    (int)sizeof (icmp6_mib))) {
16978 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
16979 		    (uint_t)sizeof (icmp6_mib)));
16980 	}
16981 
16982 	rw_enter(&ill_g_lock, RW_READER);
16983 	ill = ILL_START_WALK_V6(&ctx);
16984 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16985 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
16986 		    ill->ill_phyint->phyint_ifindex;
16987 		ill->ill_icmp6_mib->ipv6IfIcmpEntrySize =
16988 		    sizeof (mib2_ipv6IfIcmpEntry_t);
16989 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16990 		    (char *)ill->ill_icmp6_mib,
16991 		    (int)sizeof (*ill->ill_icmp6_mib))) {
16992 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
16993 			    "%u bytes\n",
16994 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
16995 		}
16996 	}
16997 	rw_exit(&ill_g_lock);
16998 
16999 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17000 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
17001 	    (int)optp->level, (int)optp->name, (int)optp->len));
17002 	qreply(q, mpctl);
17003 	return (mp2ctl);
17004 }
17005 
17006 /*
17007  * ire_walk routine to create both ipRouteEntryTable and
17008  * ipNetToMediaEntryTable in one IRE walk
17009  */
17010 static void
17011 ip_snmp_get2_v4(ire_t *ire, listptr_t re_ntme[])
17012 {
17013 	ill_t				*ill;
17014 	ipif_t				*ipif;
17015 	mblk_t				*llmp;
17016 	dl_unitdata_req_t		*dlup;
17017 	mib2_ipRouteEntry_t		re;
17018 	mib2_ipNetToMediaEntry_t	ntme;
17019 	ipaddr_t			gw_addr;
17020 
17021 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17022 
17023 	/*
17024 	 * Return all IRE types for route table... let caller pick and choose
17025 	 */
17026 	re.ipRouteDest = ire->ire_addr;
17027 	ipif = ire->ire_ipif;
17028 	re.ipRouteIfIndex.o_length = 0;
17029 	if (ire->ire_type == IRE_CACHE) {
17030 		ill = (ill_t *)ire->ire_stq->q_ptr;
17031 		re.ipRouteIfIndex.o_length =
17032 		    ill->ill_name_length == 0 ? 0 :
17033 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17034 		bcopy(ill->ill_name, re.ipRouteIfIndex.o_bytes,
17035 		    re.ipRouteIfIndex.o_length);
17036 	} else if (ipif != NULL) {
17037 		(void) ipif_get_name(ipif, re.ipRouteIfIndex.o_bytes,
17038 		    OCTET_LENGTH);
17039 		re.ipRouteIfIndex.o_length =
17040 		    mi_strlen(re.ipRouteIfIndex.o_bytes);
17041 	}
17042 	re.ipRouteMetric1 = -1;
17043 	re.ipRouteMetric2 = -1;
17044 	re.ipRouteMetric3 = -1;
17045 	re.ipRouteMetric4 = -1;
17046 
17047 	gw_addr = ire->ire_gateway_addr;
17048 
17049 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
17050 		re.ipRouteNextHop = ire->ire_src_addr;
17051 	else
17052 		re.ipRouteNextHop = gw_addr;
17053 	/* indirect(4), direct(3), or invalid(2) */
17054 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
17055 		re.ipRouteType = 2;
17056 	else
17057 		re.ipRouteType = (gw_addr != 0) ? 4 : 3;
17058 	re.ipRouteProto = -1;
17059 	re.ipRouteAge = gethrestime_sec() - ire->ire_create_time;
17060 	re.ipRouteMask = ire->ire_mask;
17061 	re.ipRouteMetric5 = -1;
17062 	re.ipRouteInfo.re_max_frag  = ire->ire_max_frag;
17063 	re.ipRouteInfo.re_frag_flag = ire->ire_frag_flag;
17064 	re.ipRouteInfo.re_rtt	    = ire->ire_uinfo.iulp_rtt;
17065 	llmp = ire->ire_dlureq_mp;
17066 	re.ipRouteInfo.re_ref	    = ire->ire_refcnt;
17067 	re.ipRouteInfo.re_src_addr  = ire->ire_src_addr;
17068 	re.ipRouteInfo.re_ire_type  = ire->ire_type;
17069 	re.ipRouteInfo.re_obpkt	    = ire->ire_ob_pkt_count;
17070 	re.ipRouteInfo.re_ibpkt	    = ire->ire_ib_pkt_count;
17071 	re.ipRouteInfo.re_flags	    = ire->ire_flags;
17072 	re.ipRouteInfo.re_in_ill.o_length = 0;
17073 	if (ire->ire_in_ill != NULL) {
17074 		re.ipRouteInfo.re_in_ill.o_length =
17075 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
17076 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
17077 		bcopy(ire->ire_in_ill->ill_name,
17078 		    re.ipRouteInfo.re_in_ill.o_bytes,
17079 		    re.ipRouteInfo.re_in_ill.o_length);
17080 	}
17081 	re.ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
17082 	if (!snmp_append_data2(re_ntme[0].lp_head, &(re_ntme[0].lp_tail),
17083 	    (char *)&re, (int)sizeof (re))) {
17084 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
17085 		    (uint_t)sizeof (re)));
17086 	}
17087 
17088 	if (ire->ire_type != IRE_CACHE || gw_addr != 0)
17089 		return;
17090 	/*
17091 	 * only IRE_CACHE entries that are for a directly connected subnet
17092 	 * get appended to net -> phys addr table
17093 	 * (others in arp)
17094 	 */
17095 	ntme.ipNetToMediaIfIndex.o_length = 0;
17096 	ill = ire_to_ill(ire);
17097 	ASSERT(ill != NULL);
17098 	ntme.ipNetToMediaIfIndex.o_length =
17099 	    ill->ill_name_length == 0 ? 0 :
17100 	    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17101 	bcopy(ill->ill_name, ntme.ipNetToMediaIfIndex.o_bytes,
17102 		    ntme.ipNetToMediaIfIndex.o_length);
17103 
17104 	ntme.ipNetToMediaPhysAddress.o_length = 0;
17105 	if (llmp) {
17106 		uchar_t *addr;
17107 
17108 		dlup = (dl_unitdata_req_t *)llmp->b_rptr;
17109 		/* Remove sap from  address */
17110 		if (ill->ill_sap_length < 0)
17111 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset;
17112 		else
17113 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset +
17114 			    ill->ill_sap_length;
17115 
17116 		ntme.ipNetToMediaPhysAddress.o_length =
17117 		    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
17118 		bcopy(addr, ntme.ipNetToMediaPhysAddress.o_bytes,
17119 		    ntme.ipNetToMediaPhysAddress.o_length);
17120 	}
17121 	ntme.ipNetToMediaNetAddress = ire->ire_addr;
17122 	/* assume dynamic (may be changed in arp) */
17123 	ntme.ipNetToMediaType = 3;
17124 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (uint32_t);
17125 	bcopy(&ire->ire_mask, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
17126 	    ntme.ipNetToMediaInfo.ntm_mask.o_length);
17127 	ntme.ipNetToMediaInfo.ntm_flags = ACE_F_RESOLVED;
17128 	if (!snmp_append_data2(re_ntme[1].lp_head, &(re_ntme[1].lp_tail),
17129 	    (char *)&ntme, (int)sizeof (ntme))) {
17130 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
17131 		    (uint_t)sizeof (ntme)));
17132 	}
17133 }
17134 
17135 /*
17136  * ire_walk routine to create ipv6RouteEntryTable.
17137  */
17138 static void
17139 ip_snmp_get2_v6_route(ire_t *ire, listptr_t *re_ntme)
17140 {
17141 	ill_t				*ill;
17142 	ipif_t				*ipif;
17143 	mib2_ipv6RouteEntry_t		re;
17144 	in6_addr_t			gw_addr_v6;
17145 
17146 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
17147 
17148 	/*
17149 	 * Return all IRE types for route table... let caller pick and choose
17150 	 */
17151 	re.ipv6RouteDest = ire->ire_addr_v6;
17152 	re.ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
17153 	re.ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
17154 	re.ipv6RouteIfIndex.o_length = 0;
17155 	ipif = ire->ire_ipif;
17156 	if (ire->ire_type == IRE_CACHE) {
17157 		ill = (ill_t *)ire->ire_stq->q_ptr;
17158 		re.ipv6RouteIfIndex.o_length =
17159 		    ill->ill_name_length == 0 ? 0 :
17160 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17161 		bcopy(ill->ill_name, re.ipv6RouteIfIndex.o_bytes,
17162 		    re.ipv6RouteIfIndex.o_length);
17163 	} else if (ipif != NULL) {
17164 		(void) ipif_get_name(ipif, re.ipv6RouteIfIndex.o_bytes,
17165 		    OCTET_LENGTH);
17166 		re.ipv6RouteIfIndex.o_length =
17167 		    mi_strlen(re.ipv6RouteIfIndex.o_bytes);
17168 	}
17169 
17170 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
17171 
17172 	mutex_enter(&ire->ire_lock);
17173 	gw_addr_v6 = ire->ire_gateway_addr_v6;
17174 	mutex_exit(&ire->ire_lock);
17175 
17176 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
17177 		re.ipv6RouteNextHop = ire->ire_src_addr_v6;
17178 	else
17179 		re.ipv6RouteNextHop = gw_addr_v6;
17180 
17181 	/* remote(4), local(3), or discard(2) */
17182 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
17183 		re.ipv6RouteType = 2;
17184 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
17185 		re.ipv6RouteType = 3;
17186 	else
17187 		re.ipv6RouteType = 4;
17188 
17189 	re.ipv6RouteProtocol		= -1;
17190 	re.ipv6RoutePolicy		= 0;
17191 	re.ipv6RouteAge		= gethrestime_sec() - ire->ire_create_time;
17192 	re.ipv6RouteNextHopRDI		= 0;
17193 	re.ipv6RouteWeight		= 0;
17194 	re.ipv6RouteMetric		= 0;
17195 	re.ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
17196 	re.ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
17197 	re.ipv6RouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
17198 	re.ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
17199 	re.ipv6RouteInfo.re_ire_type	= ire->ire_type;
17200 	re.ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
17201 	re.ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
17202 	re.ipv6RouteInfo.re_ref		= ire->ire_refcnt;
17203 	re.ipv6RouteInfo.re_flags	= ire->ire_flags;
17204 
17205 	if (!snmp_append_data2(re_ntme->lp_head, &(re_ntme->lp_tail),
17206 	    (char *)&re, (int)sizeof (re))) {
17207 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
17208 		    (uint_t)sizeof (re)));
17209 	}
17210 }
17211 
17212 /*
17213  * ndp_walk routine to create ipv6NetToMediaEntryTable
17214  */
17215 static int
17216 ip_snmp_get2_v6_media(nce_t *nce, listptr_t *re_ntme)
17217 {
17218 	ill_t				*ill;
17219 	mib2_ipv6NetToMediaEntry_t	ntme;
17220 	dl_unitdata_req_t		*dl;
17221 
17222 	ill = nce->nce_ill;
17223 	ASSERT(ill->ill_isv6);
17224 
17225 	/*
17226 	 * Neighbor cache entry attached to IRE with on-link
17227 	 * destination.
17228 	 */
17229 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
17230 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
17231 	if ((ill->ill_flags & ILLF_XRESOLV) &&
17232 	    (nce->nce_res_mp != NULL)) {
17233 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
17234 		ntme.ipv6NetToMediaPhysAddress.o_length =
17235 		    dl->dl_dest_addr_length;
17236 	} else {
17237 		ntme.ipv6NetToMediaPhysAddress.o_length =
17238 		    ill->ill_phys_addr_length;
17239 	}
17240 	if (nce->nce_res_mp != NULL) {
17241 		bcopy((char *)nce->nce_res_mp->b_rptr +
17242 		    NCE_LL_ADDR_OFFSET(ill),
17243 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
17244 		    ntme.ipv6NetToMediaPhysAddress.o_length);
17245 	} else {
17246 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
17247 		    ill->ill_phys_addr_length);
17248 	}
17249 	/*
17250 	 * Note: Returns ND_* states. Should be:
17251 	 * reachable(1), stale(2), delay(3), probe(4),
17252 	 * invalid(5), unknown(6)
17253 	 */
17254 	ntme.ipv6NetToMediaState = nce->nce_state;
17255 	ntme.ipv6NetToMediaLastUpdated = 0;
17256 
17257 	/* other(1), dynamic(2), static(3), local(4) */
17258 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
17259 		ntme.ipv6NetToMediaType = 4;
17260 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
17261 		ntme.ipv6NetToMediaType = 1;
17262 	} else {
17263 		ntme.ipv6NetToMediaType = 2;
17264 	}
17265 
17266 	if (!snmp_append_data2(re_ntme->lp_head,
17267 	    &(re_ntme->lp_tail), (char *)&ntme, (int)sizeof (ntme))) {
17268 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
17269 		    (uint_t)sizeof (ntme)));
17270 	}
17271 	return (0);
17272 }
17273 
17274 /*
17275  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
17276  */
17277 /* ARGSUSED */
17278 int
17279 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
17280 {
17281 	switch (level) {
17282 	case MIB2_IP:
17283 	case MIB2_ICMP:
17284 		switch (name) {
17285 		default:
17286 			break;
17287 		}
17288 		return (1);
17289 	default:
17290 		return (1);
17291 	}
17292 }
17293 
17294 /*
17295  * Called before the options are updated to check if this packet will
17296  * be source routed from here.
17297  * This routine assumes that the options are well formed i.e. that they
17298  * have already been checked.
17299  */
17300 static boolean_t
17301 ip_source_routed(ipha_t *ipha)
17302 {
17303 	ipoptp_t	opts;
17304 	uchar_t		*opt;
17305 	uint8_t		optval;
17306 	uint8_t		optlen;
17307 	ipaddr_t	dst;
17308 	ire_t		*ire;
17309 
17310 	if (IS_SIMPLE_IPH(ipha)) {
17311 		ip2dbg(("not source routed\n"));
17312 		return (B_FALSE);
17313 	}
17314 	dst = ipha->ipha_dst;
17315 	for (optval = ipoptp_first(&opts, ipha);
17316 	    optval != IPOPT_EOL;
17317 	    optval = ipoptp_next(&opts)) {
17318 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17319 		opt = opts.ipoptp_cur;
17320 		optlen = opts.ipoptp_len;
17321 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
17322 		    optval, optlen));
17323 		switch (optval) {
17324 			uint32_t off;
17325 		case IPOPT_SSRR:
17326 		case IPOPT_LSRR:
17327 			/*
17328 			 * If dst is one of our addresses and there are some
17329 			 * entries left in the source route return (true).
17330 			 */
17331 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17332 			    ALL_ZONES, MATCH_IRE_TYPE);
17333 			if (ire == NULL) {
17334 				ip2dbg(("ip_source_routed: not next"
17335 				    " source route 0x%x\n",
17336 				    ntohl(dst)));
17337 				return (B_FALSE);
17338 			}
17339 			ire_refrele(ire);
17340 			off = opt[IPOPT_OFFSET];
17341 			off--;
17342 			if (optlen < IP_ADDR_LEN ||
17343 			    off > optlen - IP_ADDR_LEN) {
17344 				/* End of source route */
17345 				ip1dbg(("ip_source_routed: end of SR\n"));
17346 				return (B_FALSE);
17347 			}
17348 			return (B_TRUE);
17349 		}
17350 	}
17351 	ip2dbg(("not source routed\n"));
17352 	return (B_FALSE);
17353 }
17354 
17355 /*
17356  * Check if the packet contains any source route.
17357  */
17358 static boolean_t
17359 ip_source_route_included(ipha_t *ipha)
17360 {
17361 	ipoptp_t	opts;
17362 	uint8_t		optval;
17363 
17364 	if (IS_SIMPLE_IPH(ipha))
17365 		return (B_FALSE);
17366 	for (optval = ipoptp_first(&opts, ipha);
17367 	    optval != IPOPT_EOL;
17368 	    optval = ipoptp_next(&opts)) {
17369 		switch (optval) {
17370 		case IPOPT_SSRR:
17371 		case IPOPT_LSRR:
17372 			return (B_TRUE);
17373 		}
17374 	}
17375 	return (B_FALSE);
17376 }
17377 
17378 /*
17379  * Called when the IRE expiration timer fires.
17380  */
17381 /* ARGSUSED */
17382 void
17383 ip_trash_timer_expire(void *args)
17384 {
17385 	int	flush_flag = 0;
17386 
17387 	/*
17388 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
17389 	 * This lock makes sure that a new invocation of this function
17390 	 * that occurs due to an almost immediate timer firing will not
17391 	 * progress beyond this point until the current invocation is done
17392 	 */
17393 	mutex_enter(&ip_trash_timer_lock);
17394 	ip_ire_expire_id = 0;
17395 	mutex_exit(&ip_trash_timer_lock);
17396 
17397 	/* Periodic timer */
17398 	if (ip_ire_arp_time_elapsed >= ip_ire_arp_interval) {
17399 		/*
17400 		 * Remove all IRE_CACHE entries since they might
17401 		 * contain arp information.
17402 		 */
17403 		flush_flag |= FLUSH_ARP_TIME;
17404 		ip_ire_arp_time_elapsed = 0;
17405 		IP_STAT(ip_ire_arp_timer_expired);
17406 	}
17407 	if (ip_ire_rd_time_elapsed >= ip_ire_redir_interval) {
17408 		/* Remove all redirects */
17409 		flush_flag |= FLUSH_REDIRECT_TIME;
17410 		ip_ire_rd_time_elapsed = 0;
17411 		IP_STAT(ip_ire_redirect_timer_expired);
17412 	}
17413 	if (ip_ire_pmtu_time_elapsed >= ip_ire_pathmtu_interval) {
17414 		/* Increase path mtu */
17415 		flush_flag |= FLUSH_MTU_TIME;
17416 		ip_ire_pmtu_time_elapsed = 0;
17417 		IP_STAT(ip_ire_pmtu_timer_expired);
17418 	}
17419 	if (flush_flag != 0) {
17420 		/* Walk all IPv4 IRE's and update them */
17421 		ire_walk_v4(ire_expire, (char *)(uintptr_t)flush_flag,
17422 		    ALL_ZONES);
17423 	}
17424 	if (flush_flag & FLUSH_MTU_TIME) {
17425 		/*
17426 		 * Walk all IPv6 IRE's and update them
17427 		 * Note that ARP and redirect timers are not
17428 		 * needed since NUD handles stale entries.
17429 		 */
17430 		flush_flag = FLUSH_MTU_TIME;
17431 		ire_walk_v6(ire_expire, (char *)(uintptr_t)flush_flag,
17432 		    ALL_ZONES);
17433 	}
17434 
17435 	ip_ire_arp_time_elapsed += ip_timer_interval;
17436 	ip_ire_rd_time_elapsed += ip_timer_interval;
17437 	ip_ire_pmtu_time_elapsed += ip_timer_interval;
17438 
17439 	/*
17440 	 * Hold the lock to serialize timeout calls and prevent
17441 	 * stale values in ip_ire_expire_id. Otherwise it is possible
17442 	 * for the timer to fire and a new invocation of this function
17443 	 * to start before the return value of timeout has been stored
17444 	 * in ip_ire_expire_id by the current invocation.
17445 	 */
17446 	mutex_enter(&ip_trash_timer_lock);
17447 	ip_ire_expire_id = timeout(ip_trash_timer_expire, NULL,
17448 	    MSEC_TO_TICK(ip_timer_interval));
17449 	mutex_exit(&ip_trash_timer_lock);
17450 }
17451 
17452 /*
17453  * Called by the memory allocator subsystem directly, when the system
17454  * is running low on memory.
17455  */
17456 /* ARGSUSED */
17457 void
17458 ip_trash_ire_reclaim(void *args)
17459 {
17460 	ire_cache_count_t icc;
17461 	ire_cache_reclaim_t icr;
17462 	ncc_cache_count_t ncc;
17463 	nce_cache_reclaim_t ncr;
17464 	uint_t delete_cnt;
17465 	/*
17466 	 * Memory reclaim call back.
17467 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
17468 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
17469 	 * entries, determine what fraction to free for
17470 	 * each category of IRE_CACHE entries giving absolute priority
17471 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
17472 	 * entry will be freed unless all offlink entries are freed).
17473 	 */
17474 	icc.icc_total = 0;
17475 	icc.icc_unused = 0;
17476 	icc.icc_offlink = 0;
17477 	icc.icc_pmtu = 0;
17478 	icc.icc_onlink = 0;
17479 	ire_walk(ire_cache_count, (char *)&icc);
17480 
17481 	/*
17482 	 * Free NCEs for IPv6 like the onlink ires.
17483 	 */
17484 	ncc.ncc_total = 0;
17485 	ncc.ncc_host = 0;
17486 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc);
17487 
17488 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
17489 	    icc.icc_pmtu + icc.icc_onlink);
17490 	delete_cnt = icc.icc_total/ip_ire_reclaim_fraction;
17491 	IP_STAT(ip_trash_ire_reclaim_calls);
17492 	if (delete_cnt == 0)
17493 		return;
17494 	IP_STAT(ip_trash_ire_reclaim_success);
17495 	/* Always delete all unused offlink entries */
17496 	icr.icr_unused = 1;
17497 	if (delete_cnt <= icc.icc_unused) {
17498 		/*
17499 		 * Only need to free unused entries.  In other words,
17500 		 * there are enough unused entries to free to meet our
17501 		 * target number of freed ire cache entries.
17502 		 */
17503 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
17504 		ncr.ncr_host = 0;
17505 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
17506 		/*
17507 		 * Only need to free unused entries, plus a fraction of offlink
17508 		 * entries.  It follows from the first if statement that
17509 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
17510 		 */
17511 		delete_cnt -= icc.icc_unused;
17512 		/* Round up # deleted by truncating fraction */
17513 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
17514 		icr.icr_pmtu = icr.icr_onlink = 0;
17515 		ncr.ncr_host = 0;
17516 	} else if (delete_cnt <=
17517 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
17518 		/*
17519 		 * Free all unused and offlink entries, plus a fraction of
17520 		 * pmtu entries.  It follows from the previous if statement
17521 		 * that icc_pmtu is non-zero, and that
17522 		 * delete_cnt != icc_unused + icc_offlink.
17523 		 */
17524 		icr.icr_offlink = 1;
17525 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
17526 		/* Round up # deleted by truncating fraction */
17527 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
17528 		icr.icr_onlink = 0;
17529 		ncr.ncr_host = 0;
17530 	} else {
17531 		/*
17532 		 * Free all unused, offlink, and pmtu entries, plus a fraction
17533 		 * of onlink entries.  If we're here, then we know that
17534 		 * icc_onlink is non-zero, and that
17535 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
17536 		 */
17537 		icr.icr_offlink = icr.icr_pmtu = 1;
17538 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
17539 		    icc.icc_pmtu;
17540 		/* Round up # deleted by truncating fraction */
17541 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
17542 		/* Using the same delete fraction as for onlink IREs */
17543 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
17544 	}
17545 #ifdef DEBUG
17546 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
17547 	    "fractions %d/%d/%d/%d\n",
17548 	    icc.icc_total/ip_ire_reclaim_fraction, icc.icc_total,
17549 	    icc.icc_unused, icc.icc_offlink,
17550 	    icc.icc_pmtu, icc.icc_onlink,
17551 	    icr.icr_unused, icr.icr_offlink,
17552 	    icr.icr_pmtu, icr.icr_onlink));
17553 #endif
17554 	ire_walk(ire_cache_reclaim, (char *)&icr);
17555 	if (ncr.ncr_host != 0)
17556 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
17557 		    (uchar_t *)&ncr);
17558 #ifdef DEBUG
17559 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
17560 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
17561 	ire_walk(ire_cache_count, (char *)&icc);
17562 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
17563 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
17564 	    icc.icc_pmtu, icc.icc_onlink));
17565 #endif
17566 }
17567 
17568 /*
17569  * ip_unbind is called when a copy of an unbind request is received from the
17570  * upper level protocol.  We remove this conn from any fanout hash list it is
17571  * on, and zero out the bind information.  No reply is expected up above.
17572  */
17573 static void
17574 ip_unbind(queue_t *q, mblk_t *mp)
17575 {
17576 	conn_t	*connp = Q_TO_CONN(q);
17577 
17578 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
17579 
17580 	ipcl_hash_remove(connp);
17581 
17582 	ASSERT(mp->b_cont == NULL);
17583 	/*
17584 	 * Convert mp into a T_OK_ACK
17585 	 */
17586 	mp = mi_tpi_ok_ack_alloc(mp);
17587 
17588 	/*
17589 	 * should not happen in practice... T_OK_ACK is smaller than the
17590 	 * original message.
17591 	 */
17592 	if (mp == NULL)
17593 		return;
17594 
17595 	/*
17596 	 * Don't bzero the ports if its TCP since TCP still needs the
17597 	 * lport to remove it from its own bind hash. TCP will do the
17598 	 * cleanup.
17599 	 */
17600 	if (!IPCL_IS_TCP(connp))
17601 		bzero(&connp->u_port, sizeof (connp->u_port));
17602 
17603 	qreply(q, mp);
17604 }
17605 
17606 /*
17607  * Write side put procedure.  Outbound data, IOCTLs, responses from
17608  * resolvers, etc, come down through here.
17609  */
17610 void
17611 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
17612 {
17613 	conn_t		*connp = NULL;
17614 	queue_t		*q = (queue_t *)arg2;
17615 	ipha_t		*ipha;
17616 #define	rptr	((uchar_t *)ipha)
17617 	ire_t		*ire = NULL;
17618 	ire_t		*sctp_ire = NULL;
17619 	uint32_t	v_hlen_tos_len;
17620 	ipaddr_t	dst;
17621 	mblk_t		*first_mp = NULL;
17622 	boolean_t	mctl_present;
17623 	ipsec_out_t	*io;
17624 	int		match_flags;
17625 	ill_t		*attach_ill = NULL;
17626 					/* Bind to IPIF_NOFAILOVER ill etc. */
17627 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
17628 	ipif_t		*dst_ipif;
17629 	boolean_t	multirt_need_resolve = B_FALSE;
17630 	mblk_t		*copy_mp = NULL;
17631 	int		err;
17632 	zoneid_t	zoneid;
17633 	boolean_t	need_decref = B_FALSE;
17634 	boolean_t	ignore_dontroute = B_FALSE;
17635 
17636 #ifdef	_BIG_ENDIAN
17637 #define	V_HLEN	(v_hlen_tos_len >> 24)
17638 #else
17639 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
17640 #endif
17641 
17642 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
17643 	    "ip_wput_start: q %p", q);
17644 
17645 	/*
17646 	 * ip_wput fast path
17647 	 */
17648 
17649 	/* is packet from ARP ? */
17650 	if (q->q_next != NULL)
17651 		goto qnext;
17652 
17653 	connp = (conn_t *)arg;
17654 	zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
17655 
17656 	/* is queue flow controlled? */
17657 	if ((q->q_first != NULL || connp->conn_draining) &&
17658 	    (caller == IP_WPUT)) {
17659 		goto doputq;
17660 	}
17661 
17662 	/* Multidata transmit? */
17663 	if (DB_TYPE(mp) == M_MULTIDATA) {
17664 		/*
17665 		 * We should never get here, since all Multidata messages
17666 		 * originating from tcp should have been directed over to
17667 		 * tcp_multisend() in the first place.
17668 		 */
17669 		BUMP_MIB(&ip_mib, ipOutDiscards);
17670 		freemsg(mp);
17671 		return;
17672 	} else if (DB_TYPE(mp) != M_DATA)
17673 		goto notdata;
17674 	if (mp->b_flag & MSGHASREF) {
17675 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
17676 		mp->b_flag &= ~MSGHASREF;
17677 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
17678 		need_decref = B_TRUE;
17679 	}
17680 	ipha = (ipha_t *)mp->b_rptr;
17681 
17682 	/* is IP header non-aligned or mblk smaller than basic IP header */
17683 #ifndef SAFETY_BEFORE_SPEED
17684 	if (!OK_32PTR(rptr) ||
17685 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
17686 		goto hdrtoosmall;
17687 #endif
17688 
17689 	/*
17690 	 * If there is a policy, try to attach an ipsec_out in
17691 	 * the front. At the end, first_mp either points to a
17692 	 * M_DATA message or IPSEC_OUT message linked to a
17693 	 * M_DATA message. We have to do it now as we might
17694 	 * lose the "conn" if we go through ip_newroute.
17695 	 */
17696 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
17697 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
17698 		    ipha->ipha_protocol)) == NULL)) {
17699 			if (need_decref)
17700 				CONN_DEC_REF(connp);
17701 			return;
17702 		} else {
17703 			ASSERT(mp->b_datap->db_type == M_CTL);
17704 			first_mp = mp;
17705 			mp = mp->b_cont;
17706 			mctl_present = B_TRUE;
17707 		}
17708 	} else {
17709 		first_mp = mp;
17710 		mctl_present = B_FALSE;
17711 	}
17712 
17713 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
17714 
17715 	/* is wrong version or IP options present */
17716 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
17717 		goto version_hdrlen_check;
17718 	dst = ipha->ipha_dst;
17719 
17720 	if (connp->conn_nofailover_ill != NULL) {
17721 		attach_ill = conn_get_held_ill(connp,
17722 		    &connp->conn_nofailover_ill, &err);
17723 		if (err == ILL_LOOKUP_FAILED) {
17724 			if (need_decref)
17725 				CONN_DEC_REF(connp);
17726 			freemsg(first_mp);
17727 			return;
17728 		}
17729 	}
17730 
17731 	/* is packet multicast? */
17732 	if (CLASSD(dst))
17733 		goto multicast;
17734 
17735 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL)) {
17736 		/*
17737 		 * If the destination is a broadcast or a loopback
17738 		 * address, both SO_DONTROUTE and IP_XMIT_IF go
17739 		 * through the standard path. But in the case of local
17740 		 * destination only SO_DONTROUTE goes through the
17741 		 * standard path not IP_XMIT_IF.
17742 		 */
17743 		ire = ire_cache_lookup(dst, zoneid);
17744 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
17745 		    (ire->ire_type != IRE_LOOPBACK))) {
17746 
17747 			if ((connp->conn_dontroute) && (ire != NULL) &&
17748 				(ire->ire_type == IRE_LOCAL))
17749 				goto standard_path;
17750 
17751 			if (ire != NULL) {
17752 				ire_refrele(ire);
17753 				/* No more access to ire */
17754 				ire = NULL;
17755 			}
17756 			/*
17757 			 * bypass routing checks and go directly to
17758 			 * interface.
17759 			 */
17760 			if (connp->conn_dontroute)
17761 				goto dontroute;
17762 
17763 			/*
17764 			 * If IP_XMIT_IF socket option is set,
17765 			 * then we allow unicast and multicast
17766 			 * packets to go through the ill. It is
17767 			 * quite possible that the destination
17768 			 * is not in the ire cache table and we
17769 			 * do not want to go to ip_newroute()
17770 			 * instead we call ip_newroute_ipif.
17771 			 */
17772 			xmit_ill = conn_get_held_ill(connp,
17773 			    &connp->conn_xmit_if_ill, &err);
17774 			if (err == ILL_LOOKUP_FAILED) {
17775 				if (attach_ill != NULL)
17776 					ill_refrele(attach_ill);
17777 				if (need_decref)
17778 					CONN_DEC_REF(connp);
17779 				freemsg(first_mp);
17780 				return;
17781 			}
17782 			goto send_from_ill;
17783 		}
17784 standard_path:
17785 		/* Must be a broadcast, a loopback or a local ire */
17786 		if (ire != NULL) {
17787 			ire_refrele(ire);
17788 			/* No more access to ire */
17789 			ire = NULL;
17790 		}
17791 	}
17792 
17793 	if (attach_ill != NULL)
17794 		goto send_from_ill;
17795 
17796 	/*
17797 	 * We cache IRE_CACHEs to avoid lookups. We don't do
17798 	 * this for the tcp global queue and listen end point
17799 	 * as it does not really have a real destination to
17800 	 * talk to.  This is also true for SCTP.
17801 	 */
17802 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
17803 	    !connp->conn_fully_bound) {
17804 		ire = ire_cache_lookup(dst, zoneid);
17805 		if (ire == NULL)
17806 			goto noirefound;
17807 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
17808 		    "ip_wput_end: q %p (%S)", q, "end");
17809 
17810 		/*
17811 		 * Check if the ire has the RTF_MULTIRT flag, inherited
17812 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
17813 		 */
17814 		if (ire->ire_flags & RTF_MULTIRT) {
17815 
17816 			/*
17817 			 * Force the TTL of multirouted packets if required.
17818 			 * The TTL of such packets is bounded by the
17819 			 * ip_multirt_ttl ndd variable.
17820 			 */
17821 			if ((ip_multirt_ttl > 0) &&
17822 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
17823 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
17824 				    "(was %d), dst 0x%08x\n",
17825 				    ip_multirt_ttl, ipha->ipha_ttl,
17826 				    ntohl(ire->ire_addr)));
17827 				ipha->ipha_ttl = ip_multirt_ttl;
17828 			}
17829 			/*
17830 			 * We look at this point if there are pending
17831 			 * unresolved routes. ire_multirt_resolvable()
17832 			 * checks in O(n) that all IRE_OFFSUBNET ire
17833 			 * entries for the packet's destination and
17834 			 * flagged RTF_MULTIRT are currently resolved.
17835 			 * If some remain unresolved, we make a copy
17836 			 * of the current message. It will be used
17837 			 * to initiate additional route resolutions.
17838 			 */
17839 			multirt_need_resolve =
17840 			    ire_multirt_need_resolve(ire->ire_addr);
17841 			ip2dbg(("ip_wput[TCP]: ire %p, "
17842 			    "multirt_need_resolve %d, first_mp %p\n",
17843 			    (void *)ire, multirt_need_resolve,
17844 			    (void *)first_mp));
17845 			if (multirt_need_resolve) {
17846 				copy_mp = copymsg(first_mp);
17847 				if (copy_mp != NULL) {
17848 					MULTIRT_DEBUG_TAG(copy_mp);
17849 				}
17850 			}
17851 		}
17852 
17853 		ip_wput_ire(q, first_mp, ire, connp, caller);
17854 
17855 		/*
17856 		 * Try to resolve another multiroute if
17857 		 * ire_multirt_need_resolve() deemed it necessary.
17858 		 */
17859 		if (copy_mp != NULL) {
17860 			ip_newroute(q, copy_mp, dst, NULL, connp);
17861 		}
17862 		if (need_decref)
17863 			CONN_DEC_REF(connp);
17864 		return;
17865 	}
17866 
17867 	/*
17868 	 * Access to conn_ire_cache. (protected by conn_lock)
17869 	 *
17870 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
17871 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
17872 	 * send a packet or two with the IRE_CACHE that is going away.
17873 	 * Access to the ire requires an ire refhold on the ire prior to
17874 	 * its use since an interface unplumb thread may delete the cached
17875 	 * ire and release the refhold at any time.
17876 	 *
17877 	 * Caching an ire in the conn_ire_cache
17878 	 *
17879 	 * o Caching an ire pointer in the conn requires a strict check for
17880 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
17881 	 * ires  before cleaning up the conns. So the caching of an ire pointer
17882 	 * in the conn is done after making sure under the bucket lock that the
17883 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
17884 	 * caching an ire after the unplumb thread has cleaned up the conn.
17885 	 * If the conn does not send a packet subsequently the unplumb thread
17886 	 * will be hanging waiting for the ire count to drop to zero.
17887 	 *
17888 	 * o We also need to atomically test for a null conn_ire_cache and
17889 	 * set the conn_ire_cache under the the protection of the conn_lock
17890 	 * to avoid races among concurrent threads trying to simultaneously
17891 	 * cache an ire in the conn_ire_cache.
17892 	 */
17893 	mutex_enter(&connp->conn_lock);
17894 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
17895 
17896 	if (ire != NULL && ire->ire_addr == dst &&
17897 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
17898 
17899 		IRE_REFHOLD(ire);
17900 		mutex_exit(&connp->conn_lock);
17901 
17902 	} else {
17903 		boolean_t cached = B_FALSE;
17904 		connp->conn_ire_cache = NULL;
17905 		mutex_exit(&connp->conn_lock);
17906 		/* Release the old ire */
17907 		if (ire != NULL && sctp_ire == NULL)
17908 			IRE_REFRELE_NOTR(ire);
17909 
17910 		ire = (ire_t *)ire_cache_lookup(dst, zoneid);
17911 		if (ire == NULL)
17912 			goto noirefound;
17913 		IRE_REFHOLD_NOTR(ire);
17914 
17915 		mutex_enter(&connp->conn_lock);
17916 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
17917 		    connp->conn_ire_cache == NULL) {
17918 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
17919 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
17920 				connp->conn_ire_cache = ire;
17921 				cached = B_TRUE;
17922 			}
17923 			rw_exit(&ire->ire_bucket->irb_lock);
17924 		}
17925 		mutex_exit(&connp->conn_lock);
17926 
17927 		/*
17928 		 * We can continue to use the ire but since it was
17929 		 * not cached, we should drop the extra reference.
17930 		 */
17931 		if (!cached)
17932 			IRE_REFRELE_NOTR(ire);
17933 	}
17934 
17935 
17936 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
17937 	    "ip_wput_end: q %p (%S)", q, "end");
17938 
17939 	/*
17940 	 * Check if the ire has the RTF_MULTIRT flag, inherited
17941 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
17942 	 */
17943 	if (ire->ire_flags & RTF_MULTIRT) {
17944 
17945 		/*
17946 		 * Force the TTL of multirouted packets if required.
17947 		 * The TTL of such packets is bounded by the
17948 		 * ip_multirt_ttl ndd variable.
17949 		 */
17950 		if ((ip_multirt_ttl > 0) &&
17951 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
17952 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
17953 			    "(was %d), dst 0x%08x\n",
17954 			    ip_multirt_ttl, ipha->ipha_ttl,
17955 			    ntohl(ire->ire_addr)));
17956 			ipha->ipha_ttl = ip_multirt_ttl;
17957 		}
17958 
17959 		/*
17960 		 * At this point, we check to see if there are any pending
17961 		 * unresolved routes. ire_multirt_resolvable()
17962 		 * checks in O(n) that all IRE_OFFSUBNET ire
17963 		 * entries for the packet's destination and
17964 		 * flagged RTF_MULTIRT are currently resolved.
17965 		 * If some remain unresolved, we make a copy
17966 		 * of the current message. It will be used
17967 		 * to initiate additional route resolutions.
17968 		 */
17969 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr);
17970 		ip2dbg(("ip_wput[not TCP]: ire %p, "
17971 		    "multirt_need_resolve %d, first_mp %p\n",
17972 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
17973 		if (multirt_need_resolve) {
17974 			copy_mp = copymsg(first_mp);
17975 			if (copy_mp != NULL) {
17976 				MULTIRT_DEBUG_TAG(copy_mp);
17977 			}
17978 		}
17979 	}
17980 
17981 	ip_wput_ire(q, first_mp, ire, connp, caller);
17982 
17983 	/*
17984 	 * Try to resolve another multiroute if
17985 	 * ire_multirt_resolvable() deemed it necessary
17986 	 */
17987 	if (copy_mp != NULL) {
17988 		ip_newroute(q, copy_mp, dst, NULL, connp);
17989 	}
17990 	if (need_decref)
17991 		CONN_DEC_REF(connp);
17992 	return;
17993 
17994 doputq:
17995 	ASSERT(!need_decref);
17996 	(void) putq(q, mp);
17997 	return;
17998 
17999 qnext:
18000 	/*
18001 	 * Upper Level Protocols pass down complete IP datagrams
18002 	 * as M_DATA messages.	Everything else is a sideshow.
18003 	 *
18004 	 * 1) We could be re-entering ip_wput because of ip_neworute
18005 	 *    in which case we could have a IPSEC_OUT message. We
18006 	 *    need to pass through ip_wput like other datagrams and
18007 	 *    hence cannot branch to ip_wput_nondata.
18008 	 *
18009 	 * 2) ARP, AH, ESP, and other clients who are on the module
18010 	 *    instance of IP stream, give us something to deal with.
18011 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
18012 	 *
18013 	 * 3) ICMP replies also could come here.
18014 	 */
18015 	if (DB_TYPE(mp) != M_DATA) {
18016 	    notdata:
18017 		if (DB_TYPE(mp) == M_CTL) {
18018 			/*
18019 			 * M_CTL messages are used by ARP, AH and ESP to
18020 			 * communicate with IP. We deal with IPSEC_IN and
18021 			 * IPSEC_OUT here. ip_wput_nondata handles other
18022 			 * cases.
18023 			 */
18024 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
18025 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
18026 				first_mp = mp->b_cont;
18027 				first_mp->b_flag &= ~MSGHASREF;
18028 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
18029 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
18030 				CONN_DEC_REF(connp);
18031 				connp = NULL;
18032 			}
18033 			if (ii->ipsec_info_type == IPSEC_IN) {
18034 				/*
18035 				 * Either this message goes back to
18036 				 * IPSEC for further processing or to
18037 				 * ULP after policy checks.
18038 				 */
18039 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
18040 				return;
18041 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
18042 				io = (ipsec_out_t *)ii;
18043 				if (io->ipsec_out_proc_begin) {
18044 					/*
18045 					 * IPSEC processing has already started.
18046 					 * Complete it.
18047 					 * IPQoS notes: We don't care what is
18048 					 * in ipsec_out_ill_index since this
18049 					 * won't be processed for IPQoS policies
18050 					 * in ipsec_out_process.
18051 					 */
18052 					ipsec_out_process(q, mp, NULL,
18053 					    io->ipsec_out_ill_index);
18054 					return;
18055 				} else {
18056 					connp = (q->q_next != NULL) ?
18057 					    NULL : Q_TO_CONN(q);
18058 					first_mp = mp;
18059 					mp = mp->b_cont;
18060 					mctl_present = B_TRUE;
18061 				}
18062 				zoneid = io->ipsec_out_zoneid;
18063 				ASSERT(zoneid != ALL_ZONES);
18064 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
18065 				/*
18066 				 * It's an IPsec control message requesting
18067 				 * an SADB update to be sent to the IPsec
18068 				 * hardware acceleration capable ills.
18069 				 */
18070 				ipsec_ctl_t *ipsec_ctl =
18071 				    (ipsec_ctl_t *)mp->b_rptr;
18072 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
18073 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
18074 				mblk_t *cmp = mp->b_cont;
18075 
18076 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
18077 				ASSERT(cmp != NULL);
18078 
18079 				freeb(mp);
18080 				ill_ipsec_capab_send_all(satype, cmp, sa);
18081 				return;
18082 			} else {
18083 				/*
18084 				 * This must be ARP.
18085 				 */
18086 				ip_wput_nondata(NULL, q, mp, NULL);
18087 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18088 				    "ip_wput_end: q %p (%S)", q, "nondata");
18089 				return;
18090 			}
18091 		} else {
18092 			/*
18093 			 * This must be non-(ARP/AH/ESP) messages.
18094 			 */
18095 			ASSERT(!need_decref);
18096 			ip_wput_nondata(NULL, q, mp, NULL);
18097 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18098 			    "ip_wput_end: q %p (%S)", q, "nondata");
18099 			return;
18100 		}
18101 	} else {
18102 		first_mp = mp;
18103 		mctl_present = B_FALSE;
18104 	}
18105 
18106 	ASSERT(first_mp != NULL);
18107 	/*
18108 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
18109 	 * to make sure that this packet goes out on the same interface it
18110 	 * came in. We handle that here.
18111 	 */
18112 	if (mctl_present) {
18113 		uint_t ifindex;
18114 
18115 		io = (ipsec_out_t *)first_mp->b_rptr;
18116 		if (io->ipsec_out_attach_if ||
18117 		    io->ipsec_out_xmit_if) {
18118 			ill_t	*ill;
18119 
18120 			ASSERT(io->ipsec_out_ill_index != 0);
18121 			ifindex = io->ipsec_out_ill_index;
18122 			ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
18123 			    NULL, NULL, NULL, NULL);
18124 			/*
18125 			 * ipsec_out_xmit_if bit is used to tell
18126 			 * ip_wput to use the ill to send outgoing data
18127 			 * as we have no conn when data comes from ICMP
18128 			 * error msg routines. Currently this feature is
18129 			 * only used by ip_mrtun_forward routine.
18130 			 */
18131 			if (io->ipsec_out_xmit_if) {
18132 				xmit_ill = ill;
18133 				if (xmit_ill == NULL) {
18134 					ip1dbg(("ip_wput: bad ifindex for"
18135 					    "xmit_ill %d\n", ifindex));
18136 					freemsg(first_mp);
18137 					BUMP_MIB(&ip_mib, ipOutDiscards);
18138 					ASSERT(!need_decref);
18139 					return;
18140 				}
18141 				/* Free up the ipsec_out_t mblk */
18142 				ASSERT(first_mp->b_cont == mp);
18143 				first_mp->b_cont = NULL;
18144 				freeb(first_mp);
18145 				/* Just send the IP header+ICMP+data */
18146 				first_mp = mp;
18147 				ipha = (ipha_t *)mp->b_rptr;
18148 				dst = ipha->ipha_dst;
18149 				goto send_from_ill;
18150 
18151 			} else {
18152 				attach_ill = ill;
18153 			}
18154 
18155 			if (attach_ill == NULL) {
18156 				ASSERT(xmit_ill == NULL);
18157 				ip1dbg(("ip_wput : bad ifindex for "
18158 				    "(BIND TO IPIF_NOFAILOVER) %d\n", ifindex));
18159 				freemsg(first_mp);
18160 				BUMP_MIB(&ip_mib, ipOutDiscards);
18161 				ASSERT(!need_decref);
18162 				return;
18163 			}
18164 		}
18165 	}
18166 
18167 	ASSERT(xmit_ill == NULL);
18168 
18169 	/* We have a complete IP datagram heading outbound. */
18170 	ipha = (ipha_t *)mp->b_rptr;
18171 
18172 #ifndef SPEED_BEFORE_SAFETY
18173 	/*
18174 	 * Make sure we have a full-word aligned message and that at least
18175 	 * a simple IP header is accessible in the first message.  If not,
18176 	 * try a pullup.
18177 	 */
18178 	if (!OK_32PTR(rptr) ||
18179 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
18180 	    hdrtoosmall:
18181 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
18182 			BUMP_MIB(&ip_mib, ipOutDiscards);
18183 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18184 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
18185 			if (first_mp == NULL)
18186 				first_mp = mp;
18187 			goto drop_pkt;
18188 		}
18189 		ipha = (ipha_t *)mp->b_rptr;
18190 		if (first_mp == NULL) {
18191 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
18192 			/*
18193 			 * If we got here because of "goto hdrtoosmall"
18194 			 * We need to attach a IPSEC_OUT.
18195 			 */
18196 			if (connp->conn_out_enforce_policy) {
18197 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
18198 				    NULL, ipha->ipha_protocol)) == NULL)) {
18199 					if (need_decref)
18200 						CONN_DEC_REF(connp);
18201 					return;
18202 				} else {
18203 					ASSERT(mp->b_datap->db_type == M_CTL);
18204 					first_mp = mp;
18205 					mp = mp->b_cont;
18206 					mctl_present = B_TRUE;
18207 				}
18208 			} else {
18209 				first_mp = mp;
18210 				mctl_present = B_FALSE;
18211 			}
18212 		}
18213 	}
18214 #endif
18215 
18216 	/* Most of the code below is written for speed, not readability */
18217 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
18218 
18219 	/*
18220 	 * If ip_newroute() fails, we're going to need a full
18221 	 * header for the icmp wraparound.
18222 	 */
18223 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
18224 		uint_t	v_hlen;
18225 	    version_hdrlen_check:
18226 		ASSERT(first_mp != NULL);
18227 		v_hlen = V_HLEN;
18228 		/*
18229 		 * siphon off IPv6 packets coming down from transport
18230 		 * layer modules here.
18231 		 * Note: high-order bit carries NUD reachability confirmation
18232 		 */
18233 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
18234 			/*
18235 			 * XXX implement a IPv4 and IPv6 packet counter per
18236 			 * conn and switch when ratio exceeds e.g. 10:1
18237 			 */
18238 #ifdef notyet
18239 			if (q->q_next == NULL) /* Avoid ill queue */
18240 				ip_setqinfo(RD(q), B_TRUE, B_TRUE);
18241 #endif
18242 			BUMP_MIB(&ip_mib, ipOutIPv6);
18243 			ASSERT(xmit_ill == NULL);
18244 			if (attach_ill != NULL)
18245 				ill_refrele(attach_ill);
18246 			if (need_decref)
18247 				mp->b_flag |= MSGHASREF;
18248 			(void) ip_output_v6(connp, first_mp, q, caller);
18249 			return;
18250 		}
18251 
18252 		if ((v_hlen >> 4) != IP_VERSION) {
18253 			BUMP_MIB(&ip_mib, ipOutDiscards);
18254 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18255 			    "ip_wput_end: q %p (%S)", q, "badvers");
18256 			goto drop_pkt;
18257 		}
18258 		/*
18259 		 * Is the header length at least 20 bytes?
18260 		 *
18261 		 * Are there enough bytes accessible in the header?  If
18262 		 * not, try a pullup.
18263 		 */
18264 		v_hlen &= 0xF;
18265 		v_hlen <<= 2;
18266 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
18267 			BUMP_MIB(&ip_mib, ipOutDiscards);
18268 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18269 			    "ip_wput_end: q %p (%S)", q, "badlen");
18270 			goto drop_pkt;
18271 		}
18272 		if (v_hlen > (mp->b_wptr - rptr)) {
18273 			if (!pullupmsg(mp, v_hlen)) {
18274 				BUMP_MIB(&ip_mib, ipOutDiscards);
18275 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18276 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
18277 				goto drop_pkt;
18278 			}
18279 			ipha = (ipha_t *)mp->b_rptr;
18280 		}
18281 		/*
18282 		 * Move first entry from any source route into ipha_dst and
18283 		 * verify the options
18284 		 */
18285 		if (ip_wput_options(q, first_mp, ipha, mctl_present, zoneid)) {
18286 			ASSERT(xmit_ill == NULL);
18287 			if (attach_ill != NULL)
18288 				ill_refrele(attach_ill);
18289 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18290 			    "ip_wput_end: q %p (%S)", q, "badopts");
18291 			if (need_decref)
18292 				CONN_DEC_REF(connp);
18293 			return;
18294 		}
18295 	}
18296 	dst = ipha->ipha_dst;
18297 
18298 	/*
18299 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
18300 	 * we have to run the packet through ip_newroute which will take
18301 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
18302 	 * a resolver, or assigning a default gateway, etc.
18303 	 */
18304 	if (CLASSD(dst)) {
18305 		ipif_t	*ipif;
18306 		uint32_t setsrc = 0;
18307 
18308 	    multicast:
18309 		ASSERT(first_mp != NULL);
18310 		ASSERT(xmit_ill == NULL);
18311 		ip2dbg(("ip_wput: CLASSD\n"));
18312 		if (connp == NULL) {
18313 			/*
18314 			 * Use the first good ipif on the ill.
18315 			 * XXX Should this ever happen? (Appears
18316 			 * to show up with just ppp and no ethernet due
18317 			 * to in.rdisc.)
18318 			 * However, ire_send should be able to
18319 			 * call ip_wput_ire directly.
18320 			 *
18321 			 * XXX Also, this can happen for ICMP and other packets
18322 			 * with multicast source addresses.  Perhaps we should
18323 			 * fix things so that we drop the packet in question,
18324 			 * but for now, just run with it.
18325 			 */
18326 			ill_t *ill = (ill_t *)q->q_ptr;
18327 
18328 			/*
18329 			 * Don't honor attach_if for this case. If ill
18330 			 * is part of the group, ipif could belong to
18331 			 * any ill and we cannot maintain attach_ill
18332 			 * and ipif_ill same anymore and the assert
18333 			 * below would fail.
18334 			 */
18335 			if (mctl_present) {
18336 				io->ipsec_out_ill_index = 0;
18337 				io->ipsec_out_attach_if = B_FALSE;
18338 				ASSERT(attach_ill != NULL);
18339 				ill_refrele(attach_ill);
18340 				attach_ill = NULL;
18341 			}
18342 
18343 			ASSERT(attach_ill == NULL);
18344 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
18345 			if (ipif == NULL) {
18346 				if (need_decref)
18347 					CONN_DEC_REF(connp);
18348 				freemsg(first_mp);
18349 				return;
18350 			}
18351 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
18352 			    ntohl(dst), ill->ill_name));
18353 		} else {
18354 			/*
18355 			 * If both IP_MULTICAST_IF and IP_XMIT_IF are set,
18356 			 * IP_XMIT_IF is honoured.
18357 			 * Block comment above this function explains the
18358 			 * locking mechanism used here
18359 			 */
18360 			xmit_ill = conn_get_held_ill(connp,
18361 			    &connp->conn_xmit_if_ill, &err);
18362 			if (err == ILL_LOOKUP_FAILED) {
18363 				ip1dbg(("ip_wput: No ill for IP_XMIT_IF\n"));
18364 				goto drop_pkt;
18365 			}
18366 			if (xmit_ill == NULL) {
18367 				ipif = conn_get_held_ipif(connp,
18368 				    &connp->conn_multicast_ipif, &err);
18369 				if (err == IPIF_LOOKUP_FAILED) {
18370 					ip1dbg(("ip_wput: No ipif for "
18371 					    "multicast\n"));
18372 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18373 					goto drop_pkt;
18374 				}
18375 			}
18376 			if (xmit_ill != NULL) {
18377 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
18378 				if (ipif == NULL) {
18379 					ip1dbg(("ip_wput: No ipif for "
18380 					    "IP_XMIT_IF\n"));
18381 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18382 					goto drop_pkt;
18383 				}
18384 			} else if (ipif == NULL || ipif->ipif_isv6) {
18385 				/*
18386 				 * We must do this ipif determination here
18387 				 * else we could pass through ip_newroute
18388 				 * and come back here without the conn context.
18389 				 *
18390 				 * Note: we do late binding i.e. we bind to
18391 				 * the interface when the first packet is sent.
18392 				 * For performance reasons we do not rebind on
18393 				 * each packet but keep the binding until the
18394 				 * next IP_MULTICAST_IF option.
18395 				 *
18396 				 * conn_multicast_{ipif,ill} are shared between
18397 				 * IPv4 and IPv6 and AF_INET6 sockets can
18398 				 * send both IPv4 and IPv6 packets. Hence
18399 				 * we have to check that "isv6" matches above.
18400 				 */
18401 				if (ipif != NULL)
18402 					ipif_refrele(ipif);
18403 				ipif = ipif_lookup_group(dst, zoneid);
18404 				if (ipif == NULL) {
18405 					ip1dbg(("ip_wput: No ipif for "
18406 					    "multicast\n"));
18407 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18408 					goto drop_pkt;
18409 				}
18410 				err = conn_set_held_ipif(connp,
18411 				    &connp->conn_multicast_ipif, ipif);
18412 				if (err == IPIF_LOOKUP_FAILED) {
18413 					ipif_refrele(ipif);
18414 					ip1dbg(("ip_wput: No ipif for "
18415 					    "multicast\n"));
18416 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18417 					goto drop_pkt;
18418 				}
18419 			}
18420 		}
18421 		ASSERT(!ipif->ipif_isv6);
18422 		/*
18423 		 * As we may lose the conn by the time we reach ip_wput_ire,
18424 		 * we copy conn_multicast_loop and conn_dontroute on to an
18425 		 * ipsec_out. In case if this datagram goes out secure,
18426 		 * we need the ill_index also. Copy that also into the
18427 		 * ipsec_out.
18428 		 */
18429 		if (mctl_present) {
18430 			io = (ipsec_out_t *)first_mp->b_rptr;
18431 			ASSERT(first_mp->b_datap->db_type == M_CTL);
18432 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
18433 		} else {
18434 			ASSERT(mp == first_mp);
18435 			if ((first_mp = allocb(sizeof (ipsec_info_t),
18436 			    BPRI_HI)) == NULL) {
18437 				ipif_refrele(ipif);
18438 				first_mp = mp;
18439 				goto drop_pkt;
18440 			}
18441 			first_mp->b_datap->db_type = M_CTL;
18442 			first_mp->b_wptr += sizeof (ipsec_info_t);
18443 			/* ipsec_out_secure is B_FALSE now */
18444 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
18445 			io = (ipsec_out_t *)first_mp->b_rptr;
18446 			io->ipsec_out_type = IPSEC_OUT;
18447 			io->ipsec_out_len = sizeof (ipsec_out_t);
18448 			io->ipsec_out_use_global_policy = B_TRUE;
18449 			first_mp->b_cont = mp;
18450 			mctl_present = B_TRUE;
18451 		}
18452 		if (attach_ill != NULL) {
18453 			ASSERT(attach_ill == ipif->ipif_ill);
18454 			match_flags = MATCH_IRE_ILL;
18455 
18456 			/*
18457 			 * Check if we need an ire that will not be
18458 			 * looked up by anybody else i.e. HIDDEN.
18459 			 */
18460 			if (ill_is_probeonly(attach_ill)) {
18461 				match_flags |= MATCH_IRE_MARK_HIDDEN;
18462 			}
18463 			io->ipsec_out_ill_index =
18464 			    attach_ill->ill_phyint->phyint_ifindex;
18465 			io->ipsec_out_attach_if = B_TRUE;
18466 		} else {
18467 			match_flags = MATCH_IRE_ILL_GROUP;
18468 			io->ipsec_out_ill_index =
18469 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
18470 		}
18471 		if (connp != NULL) {
18472 			io->ipsec_out_multicast_loop =
18473 			    connp->conn_multicast_loop;
18474 			io->ipsec_out_dontroute = connp->conn_dontroute;
18475 			io->ipsec_out_zoneid = connp->conn_zoneid;
18476 		}
18477 		/*
18478 		 * If the application uses IP_MULTICAST_IF with
18479 		 * different logical addresses of the same ILL, we
18480 		 * need to make sure that the soruce address of
18481 		 * the packet matches the logical IP address used
18482 		 * in the option. We do it by initializing ipha_src
18483 		 * here. This should keep IPSEC also happy as
18484 		 * when we return from IPSEC processing, we don't
18485 		 * have to worry about getting the right address on
18486 		 * the packet. Thus it is sufficient to look for
18487 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
18488 		 * MATCH_IRE_IPIF.
18489 		 *
18490 		 * NOTE : We need to do it for non-secure case also as
18491 		 * this might go out secure if there is a global policy
18492 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
18493 		 * address, the source should be initialized already and
18494 		 * hence we won't be initializing here.
18495 		 *
18496 		 * As we do not have the ire yet, it is possible that
18497 		 * we set the source address here and then later discover
18498 		 * that the ire implies the source address to be assigned
18499 		 * through the RTF_SETSRC flag.
18500 		 * In that case, the setsrc variable will remind us
18501 		 * that overwritting the source address by the one
18502 		 * of the RTF_SETSRC-flagged ire is allowed.
18503 		 */
18504 		if (ipha->ipha_src == INADDR_ANY &&
18505 		    (connp == NULL || !connp->conn_unspec_src)) {
18506 			ipha->ipha_src = ipif->ipif_src_addr;
18507 			setsrc = RTF_SETSRC;
18508 		}
18509 		/*
18510 		 * Find an IRE which matches the destination and the outgoing
18511 		 * queue (i.e. the outgoing interface.)
18512 		 * For loopback use a unicast IP address for
18513 		 * the ire lookup.
18514 		 */
18515 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
18516 		    PHYI_LOOPBACK) {
18517 			dst = ipif->ipif_lcl_addr;
18518 		}
18519 		/*
18520 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
18521 		 * We don't need to lookup ire in ctable as the packet
18522 		 * needs to be sent to the destination through the specified
18523 		 * ill irrespective of ires in the cache table.
18524 		 */
18525 		ire = NULL;
18526 		if (xmit_ill == NULL) {
18527 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
18528 			    zoneid, match_flags);
18529 		}
18530 
18531 		/*
18532 		 * refrele attach_ill as its not needed anymore.
18533 		 */
18534 		if (attach_ill != NULL) {
18535 			ill_refrele(attach_ill);
18536 			attach_ill = NULL;
18537 		}
18538 
18539 		if (ire == NULL) {
18540 			/*
18541 			 * Multicast loopback and multicast forwarding is
18542 			 * done in ip_wput_ire.
18543 			 *
18544 			 * Mark this packet to make it be delivered to
18545 			 * ip_wput_ire after the new ire has been
18546 			 * created.
18547 			 *
18548 			 * The call to ip_newroute_ipif takes into account
18549 			 * the setsrc reminder. In any case, we take care
18550 			 * of the RTF_MULTIRT flag.
18551 			 */
18552 			mp->b_prev = mp->b_next = NULL;
18553 			if (xmit_ill == NULL ||
18554 			    xmit_ill->ill_ipif_up_count > 0) {
18555 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
18556 				    setsrc | RTF_MULTIRT);
18557 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18558 				    "ip_wput_end: q %p (%S)", q, "noire");
18559 			} else {
18560 				freemsg(first_mp);
18561 			}
18562 			ipif_refrele(ipif);
18563 			if (xmit_ill != NULL)
18564 				ill_refrele(xmit_ill);
18565 			if (need_decref)
18566 				CONN_DEC_REF(connp);
18567 			return;
18568 		}
18569 
18570 		ipif_refrele(ipif);
18571 		ipif = NULL;
18572 		ASSERT(xmit_ill == NULL);
18573 
18574 		/*
18575 		 * Honor the RTF_SETSRC flag for multicast packets,
18576 		 * if allowed by the setsrc reminder.
18577 		 */
18578 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
18579 			ipha->ipha_src = ire->ire_src_addr;
18580 		}
18581 
18582 		/*
18583 		 * Unconditionally force the TTL to 1 for
18584 		 * multirouted multicast packets:
18585 		 * multirouted multicast should not cross
18586 		 * multicast routers.
18587 		 */
18588 		if (ire->ire_flags & RTF_MULTIRT) {
18589 			if (ipha->ipha_ttl > 1) {
18590 				ip2dbg(("ip_wput: forcing multicast "
18591 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
18592 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
18593 				ipha->ipha_ttl = 1;
18594 			}
18595 		}
18596 	} else {
18597 		ire = ire_cache_lookup(dst, zoneid);
18598 		if ((ire != NULL) && (ire->ire_type &
18599 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
18600 			ignore_dontroute = B_TRUE;
18601 		}
18602 		if (ire != NULL) {
18603 			ire_refrele(ire);
18604 			ire = NULL;
18605 		}
18606 		/*
18607 		 * Guard against coming in from arp in which case conn is NULL.
18608 		 * Also guard against non M_DATA with dontroute set but
18609 		 * destined to local, loopback or broadcast addresses.
18610 		 */
18611 		if (connp != NULL && connp->conn_dontroute &&
18612 		    !ignore_dontroute) {
18613 dontroute:
18614 			/*
18615 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
18616 			 * routing protocols from seeing false direct
18617 			 * connectivity.
18618 			 */
18619 			ipha->ipha_ttl = 1;
18620 			/*
18621 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
18622 			 * along with SO_DONTROUTE, higher precedence is
18623 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
18624 			 */
18625 			if (connp->conn_xmit_if_ill == NULL) {
18626 				/* If suitable ipif not found, drop packet */
18627 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid);
18628 				if (dst_ipif == NULL) {
18629 					ip1dbg(("ip_wput: no route for "
18630 					    "dst using SO_DONTROUTE\n"));
18631 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18632 					mp->b_prev = mp->b_next = NULL;
18633 					if (first_mp == NULL)
18634 						first_mp = mp;
18635 					goto drop_pkt;
18636 				} else {
18637 					/*
18638 					 * If suitable ipif has been found, set
18639 					 * xmit_ill to the corresponding
18640 					 * ipif_ill because we'll be following
18641 					 * the IP_XMIT_IF logic.
18642 					 */
18643 					ASSERT(xmit_ill == NULL);
18644 					xmit_ill = dst_ipif->ipif_ill;
18645 					mutex_enter(&xmit_ill->ill_lock);
18646 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
18647 						mutex_exit(&xmit_ill->ill_lock);
18648 						xmit_ill = NULL;
18649 						ipif_refrele(dst_ipif);
18650 						ip1dbg(("ip_wput: no route for"
18651 						    " dst using"
18652 						    " SO_DONTROUTE\n"));
18653 						BUMP_MIB(&ip_mib,
18654 						    ipOutNoRoutes);
18655 						mp->b_prev = mp->b_next = NULL;
18656 						if (first_mp == NULL)
18657 							first_mp = mp;
18658 						goto drop_pkt;
18659 					}
18660 					ill_refhold_locked(xmit_ill);
18661 					mutex_exit(&xmit_ill->ill_lock);
18662 					ipif_refrele(dst_ipif);
18663 				}
18664 			}
18665 
18666 		}
18667 		/*
18668 		 * If we are bound to IPIF_NOFAILOVER address, look for
18669 		 * an IRE_CACHE matching the ill.
18670 		 */
18671 send_from_ill:
18672 		if (attach_ill != NULL) {
18673 			ipif_t	*attach_ipif;
18674 
18675 			match_flags = MATCH_IRE_ILL;
18676 
18677 			/*
18678 			 * Check if we need an ire that will not be
18679 			 * looked up by anybody else i.e. HIDDEN.
18680 			 */
18681 			if (ill_is_probeonly(attach_ill)) {
18682 				match_flags |= MATCH_IRE_MARK_HIDDEN;
18683 			}
18684 
18685 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
18686 			if (attach_ipif == NULL) {
18687 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
18688 				goto drop_pkt;
18689 			}
18690 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
18691 			    zoneid, match_flags);
18692 			ipif_refrele(attach_ipif);
18693 		} else if (xmit_ill != NULL || (connp != NULL &&
18694 			    connp->conn_xmit_if_ill != NULL)) {
18695 			/*
18696 			 * Mark this packet as originated locally
18697 			 */
18698 			mp->b_prev = mp->b_next = NULL;
18699 			/*
18700 			 * xmit_ill could be NULL if SO_DONTROUTE
18701 			 * is also set.
18702 			 */
18703 			if (xmit_ill == NULL) {
18704 				xmit_ill = conn_get_held_ill(connp,
18705 				    &connp->conn_xmit_if_ill, &err);
18706 				if (err == ILL_LOOKUP_FAILED) {
18707 					if (need_decref)
18708 						CONN_DEC_REF(connp);
18709 					freemsg(first_mp);
18710 					return;
18711 				}
18712 				if (xmit_ill == NULL) {
18713 					if (connp->conn_dontroute)
18714 						goto dontroute;
18715 					goto send_from_ill;
18716 				}
18717 			}
18718 			/*
18719 			 * could be SO_DONTROUTE case also.
18720 			 * check at least one interface is UP as
18721 			 * spcified by this ILL, and then call
18722 			 * ip_newroute_ipif()
18723 			 */
18724 			if (xmit_ill->ill_ipif_up_count > 0) {
18725 				ipif_t *ipif;
18726 
18727 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
18728 				if (ipif != NULL) {
18729 					ip_newroute_ipif(q, first_mp, ipif,
18730 					    dst, connp, 0);
18731 					ipif_refrele(ipif);
18732 					ip1dbg(("ip_wput: ip_unicast_if\n"));
18733 				}
18734 			} else {
18735 				freemsg(first_mp);
18736 			}
18737 			ill_refrele(xmit_ill);
18738 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18739 			    "ip_wput_end: q %p (%S)", q, "unicast_if");
18740 			if (need_decref)
18741 				CONN_DEC_REF(connp);
18742 			return;
18743 		} else {
18744 			ire = ire_cache_lookup(dst, zoneid);
18745 		}
18746 		if (!ire) {
18747 			/*
18748 			 * Make sure we don't load spread if this
18749 			 * is IPIF_NOFAILOVER case.
18750 			 */
18751 			if (attach_ill != NULL) {
18752 				if (mctl_present) {
18753 					io = (ipsec_out_t *)first_mp->b_rptr;
18754 					ASSERT(first_mp->b_datap->db_type ==
18755 					    M_CTL);
18756 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
18757 				} else {
18758 					ASSERT(mp == first_mp);
18759 					first_mp = allocb(
18760 					    sizeof (ipsec_info_t), BPRI_HI);
18761 					if (first_mp == NULL) {
18762 						first_mp = mp;
18763 						goto drop_pkt;
18764 					}
18765 					first_mp->b_datap->db_type = M_CTL;
18766 					first_mp->b_wptr +=
18767 					    sizeof (ipsec_info_t);
18768 					/* ipsec_out_secure is B_FALSE now */
18769 					bzero(first_mp->b_rptr,
18770 					    sizeof (ipsec_info_t));
18771 					io = (ipsec_out_t *)first_mp->b_rptr;
18772 					io->ipsec_out_type = IPSEC_OUT;
18773 					io->ipsec_out_len =
18774 					    sizeof (ipsec_out_t);
18775 					io->ipsec_out_use_global_policy =
18776 					    B_TRUE;
18777 					first_mp->b_cont = mp;
18778 					mctl_present = B_TRUE;
18779 				}
18780 				io->ipsec_out_ill_index = attach_ill->
18781 				    ill_phyint->phyint_ifindex;
18782 				io->ipsec_out_attach_if = B_TRUE;
18783 			}
18784 noirefound:
18785 			/*
18786 			 * Mark this packet as having originated on
18787 			 * this machine.  This will be noted in
18788 			 * ire_add_then_send, which needs to know
18789 			 * whether to run it back through ip_wput or
18790 			 * ip_rput following successful resolution.
18791 			 */
18792 			mp->b_prev = NULL;
18793 			mp->b_next = NULL;
18794 			ip_newroute(q, first_mp, dst, NULL, connp);
18795 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18796 			    "ip_wput_end: q %p (%S)", q, "newroute");
18797 			if (attach_ill != NULL)
18798 				ill_refrele(attach_ill);
18799 			if (xmit_ill != NULL)
18800 				ill_refrele(xmit_ill);
18801 			if (need_decref)
18802 				CONN_DEC_REF(connp);
18803 			return;
18804 		}
18805 	}
18806 
18807 	/* We now know where we are going with it. */
18808 
18809 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18810 	    "ip_wput_end: q %p (%S)", q, "end");
18811 
18812 	/*
18813 	 * Check if the ire has the RTF_MULTIRT flag, inherited
18814 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
18815 	 */
18816 	if (ire->ire_flags & RTF_MULTIRT) {
18817 		/*
18818 		 * Force the TTL of multirouted packets if required.
18819 		 * The TTL of such packets is bounded by the
18820 		 * ip_multirt_ttl ndd variable.
18821 		 */
18822 		if ((ip_multirt_ttl > 0) &&
18823 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
18824 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
18825 			    "(was %d), dst 0x%08x\n",
18826 			    ip_multirt_ttl, ipha->ipha_ttl,
18827 			    ntohl(ire->ire_addr)));
18828 			ipha->ipha_ttl = ip_multirt_ttl;
18829 		}
18830 		/*
18831 		 * At this point, we check to see if there are any pending
18832 		 * unresolved routes. ire_multirt_resolvable()
18833 		 * checks in O(n) that all IRE_OFFSUBNET ire
18834 		 * entries for the packet's destination and
18835 		 * flagged RTF_MULTIRT are currently resolved.
18836 		 * If some remain unresolved, we make a copy
18837 		 * of the current message. It will be used
18838 		 * to initiate additional route resolutions.
18839 		 */
18840 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr);
18841 		ip2dbg(("ip_wput[noirefound]: ire %p, "
18842 		    "multirt_need_resolve %d, first_mp %p\n",
18843 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
18844 		if (multirt_need_resolve) {
18845 			copy_mp = copymsg(first_mp);
18846 			if (copy_mp != NULL) {
18847 				MULTIRT_DEBUG_TAG(copy_mp);
18848 			}
18849 		}
18850 	}
18851 
18852 	ip_wput_ire(q, first_mp, ire, connp, caller);
18853 	/*
18854 	 * Try to resolve another multiroute if
18855 	 * ire_multirt_resolvable() deemed it necessary.
18856 	 * At this point, we need to distinguish
18857 	 * multicasts from other packets. For multicasts,
18858 	 * we call ip_newroute_ipif() and request that both
18859 	 * multirouting and setsrc flags are checked.
18860 	 */
18861 	if (copy_mp != NULL) {
18862 		if (CLASSD(dst)) {
18863 			ipif_t *ipif = ipif_lookup_group(dst, zoneid);
18864 			if (ipif) {
18865 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
18866 				    RTF_SETSRC | RTF_MULTIRT);
18867 				ipif_refrele(ipif);
18868 			} else {
18869 				MULTIRT_DEBUG_UNTAG(copy_mp);
18870 				freemsg(copy_mp);
18871 				copy_mp = NULL;
18872 			}
18873 		} else {
18874 			ip_newroute(q, copy_mp, dst, NULL, connp);
18875 		}
18876 	}
18877 	if (attach_ill != NULL)
18878 		ill_refrele(attach_ill);
18879 	if (xmit_ill != NULL)
18880 		ill_refrele(xmit_ill);
18881 	if (need_decref)
18882 		CONN_DEC_REF(connp);
18883 	return;
18884 
18885 drop_pkt:
18886 	ip1dbg(("ip_wput: dropped packet\n"));
18887 	if (ire != NULL)
18888 		ire_refrele(ire);
18889 	if (need_decref)
18890 		CONN_DEC_REF(connp);
18891 	freemsg(first_mp);
18892 	if (attach_ill != NULL)
18893 		ill_refrele(attach_ill);
18894 	if (xmit_ill != NULL)
18895 		ill_refrele(xmit_ill);
18896 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18897 	    "ip_wput_end: q %p (%S)", q, "droppkt");
18898 }
18899 
18900 void
18901 ip_wput(queue_t *q, mblk_t *mp)
18902 {
18903 	ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
18904 }
18905 
18906 /*
18907  *
18908  * The following rules must be observed when accessing any ipif or ill
18909  * that has been cached in the conn. Typically conn_nofailover_ill,
18910  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
18911  *
18912  * Access: The ipif or ill pointed to from the conn can be accessed under
18913  * the protection of the conn_lock or after it has been refheld under the
18914  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
18915  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
18916  * The reason for this is that a concurrent unplumb could actually be
18917  * cleaning up these cached pointers by walking the conns and might have
18918  * finished cleaning up the conn in question. The macros check that an
18919  * unplumb has not yet started on the ipif or ill.
18920  *
18921  * Caching: An ipif or ill pointer may be cached in the conn only after
18922  * making sure that an unplumb has not started. So the caching is done
18923  * while holding both the conn_lock and the ill_lock and after using the
18924  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
18925  * flag before starting the cleanup of conns.
18926  *
18927  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
18928  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
18929  * or a reference to the ipif or a reference to an ire that references the
18930  * ipif. An ipif does not change its ill except for failover/failback. Since
18931  * failover/failback happens only after bringing down the ipif and making sure
18932  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
18933  * the above holds.
18934  */
18935 static ipif_t *
18936 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
18937 {
18938 	ipif_t	*ipif;
18939 	ill_t	*ill;
18940 
18941 	*err = 0;
18942 	rw_enter(&ill_g_lock, RW_READER);
18943 	mutex_enter(&connp->conn_lock);
18944 	ipif = *ipifp;
18945 	if (ipif != NULL) {
18946 		ill = ipif->ipif_ill;
18947 		mutex_enter(&ill->ill_lock);
18948 		if (IPIF_CAN_LOOKUP(ipif)) {
18949 			ipif_refhold_locked(ipif);
18950 			mutex_exit(&ill->ill_lock);
18951 			mutex_exit(&connp->conn_lock);
18952 			rw_exit(&ill_g_lock);
18953 			return (ipif);
18954 		} else {
18955 			*err = IPIF_LOOKUP_FAILED;
18956 		}
18957 		mutex_exit(&ill->ill_lock);
18958 	}
18959 	mutex_exit(&connp->conn_lock);
18960 	rw_exit(&ill_g_lock);
18961 	return (NULL);
18962 }
18963 
18964 ill_t *
18965 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
18966 {
18967 	ill_t	*ill;
18968 
18969 	*err = 0;
18970 	mutex_enter(&connp->conn_lock);
18971 	ill = *illp;
18972 	if (ill != NULL) {
18973 		mutex_enter(&ill->ill_lock);
18974 		if (ILL_CAN_LOOKUP(ill)) {
18975 			ill_refhold_locked(ill);
18976 			mutex_exit(&ill->ill_lock);
18977 			mutex_exit(&connp->conn_lock);
18978 			return (ill);
18979 		} else {
18980 			*err = ILL_LOOKUP_FAILED;
18981 		}
18982 		mutex_exit(&ill->ill_lock);
18983 	}
18984 	mutex_exit(&connp->conn_lock);
18985 	return (NULL);
18986 }
18987 
18988 static int
18989 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
18990 {
18991 	ill_t	*ill;
18992 
18993 	ill = ipif->ipif_ill;
18994 	mutex_enter(&connp->conn_lock);
18995 	mutex_enter(&ill->ill_lock);
18996 	if (IPIF_CAN_LOOKUP(ipif)) {
18997 		*ipifp = ipif;
18998 		mutex_exit(&ill->ill_lock);
18999 		mutex_exit(&connp->conn_lock);
19000 		return (0);
19001 	}
19002 	mutex_exit(&ill->ill_lock);
19003 	mutex_exit(&connp->conn_lock);
19004 	return (IPIF_LOOKUP_FAILED);
19005 }
19006 
19007 /*
19008  * This is called if the outbound datagram needs fragmentation.
19009  *
19010  * NOTE : This function does not ire_refrele the ire argument passed in.
19011  */
19012 static void
19013 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire)
19014 {
19015 	ipha_t		*ipha;
19016 	mblk_t		*mp;
19017 	uint32_t	v_hlen_tos_len;
19018 	uint32_t	max_frag;
19019 	uint32_t	frag_flag;
19020 	boolean_t	dont_use;
19021 
19022 	if (ipsec_mp->b_datap->db_type == M_CTL) {
19023 		mp = ipsec_mp->b_cont;
19024 	} else {
19025 		mp = ipsec_mp;
19026 	}
19027 
19028 	ipha = (ipha_t *)mp->b_rptr;
19029 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19030 
19031 #ifdef	_BIG_ENDIAN
19032 #define	V_HLEN	(v_hlen_tos_len >> 24)
19033 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
19034 #else
19035 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19036 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
19037 #endif
19038 
19039 #ifndef SPEED_BEFORE_SAFETY
19040 	/*
19041 	 * Check that ipha_length is consistent with
19042 	 * the mblk length
19043 	 */
19044 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
19045 		ip0dbg(("Packet length mismatch: %d, %ld\n",
19046 		    LENGTH, msgdsize(mp)));
19047 		freemsg(ipsec_mp);
19048 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
19049 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
19050 		    "packet length mismatch");
19051 		return;
19052 	}
19053 #endif
19054 	/*
19055 	 * Don't use frag_flag if pre-built packet or source
19056 	 * routed or if multicast (since multicast packets do not solicit
19057 	 * ICMP "packet too big" messages). Get the values of
19058 	 * max_frag and frag_flag atomically by acquiring the
19059 	 * ire_lock.
19060 	 */
19061 	mutex_enter(&ire->ire_lock);
19062 	max_frag = ire->ire_max_frag;
19063 	frag_flag = ire->ire_frag_flag;
19064 	mutex_exit(&ire->ire_lock);
19065 
19066 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
19067 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
19068 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
19069 
19070 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
19071 	    (dont_use ? 0 : frag_flag));
19072 }
19073 
19074 /*
19075  * Used for deciding the MSS size for the upper layer. Thus
19076  * we need to check the outbound policy values in the conn.
19077  */
19078 int
19079 conn_ipsec_length(conn_t *connp)
19080 {
19081 	ipsec_latch_t *ipl;
19082 
19083 	ipl = connp->conn_latch;
19084 	if (ipl == NULL)
19085 		return (0);
19086 
19087 	if (ipl->ipl_out_policy == NULL)
19088 		return (0);
19089 
19090 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
19091 }
19092 
19093 /*
19094  * Returns an estimate of the IPSEC headers size. This is used if
19095  * we don't want to call into IPSEC to get the exact size.
19096  */
19097 int
19098 ipsec_out_extra_length(mblk_t *ipsec_mp)
19099 {
19100 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
19101 	ipsec_action_t *a;
19102 
19103 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
19104 	if (!io->ipsec_out_secure)
19105 		return (0);
19106 
19107 	a = io->ipsec_out_act;
19108 
19109 	if (a == NULL) {
19110 		ASSERT(io->ipsec_out_policy != NULL);
19111 		a = io->ipsec_out_policy->ipsp_act;
19112 	}
19113 	ASSERT(a != NULL);
19114 
19115 	return (a->ipa_ovhd);
19116 }
19117 
19118 /*
19119  * Returns an estimate of the IPSEC headers size. This is used if
19120  * we don't want to call into IPSEC to get the exact size.
19121  */
19122 int
19123 ipsec_in_extra_length(mblk_t *ipsec_mp)
19124 {
19125 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
19126 	ipsec_action_t *a;
19127 
19128 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
19129 
19130 	a = ii->ipsec_in_action;
19131 	return (a == NULL ? 0 : a->ipa_ovhd);
19132 }
19133 
19134 /*
19135  * If there are any source route options, return the true final
19136  * destination. Otherwise, return the destination.
19137  */
19138 ipaddr_t
19139 ip_get_dst(ipha_t *ipha)
19140 {
19141 	ipoptp_t	opts;
19142 	uchar_t		*opt;
19143 	uint8_t		optval;
19144 	uint8_t		optlen;
19145 	ipaddr_t	dst;
19146 	uint32_t off;
19147 
19148 	dst = ipha->ipha_dst;
19149 
19150 	if (IS_SIMPLE_IPH(ipha))
19151 		return (dst);
19152 
19153 	for (optval = ipoptp_first(&opts, ipha);
19154 	    optval != IPOPT_EOL;
19155 	    optval = ipoptp_next(&opts)) {
19156 		opt = opts.ipoptp_cur;
19157 		optlen = opts.ipoptp_len;
19158 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19159 		switch (optval) {
19160 		case IPOPT_SSRR:
19161 		case IPOPT_LSRR:
19162 			off = opt[IPOPT_OFFSET];
19163 			/*
19164 			 * If one of the conditions is true, it means
19165 			 * end of options and dst already has the right
19166 			 * value.
19167 			 */
19168 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
19169 				off = optlen - IP_ADDR_LEN;
19170 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
19171 			}
19172 			return (dst);
19173 		default:
19174 			break;
19175 		}
19176 	}
19177 
19178 	return (dst);
19179 }
19180 
19181 mblk_t *
19182 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
19183     conn_t *connp, boolean_t unspec_src)
19184 {
19185 	ipsec_out_t	*io;
19186 	mblk_t		*first_mp;
19187 	boolean_t policy_present;
19188 
19189 	first_mp = mp;
19190 	if (mp->b_datap->db_type == M_CTL) {
19191 		io = (ipsec_out_t *)first_mp->b_rptr;
19192 		/*
19193 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
19194 		 *
19195 		 * 1) There is per-socket policy (including cached global
19196 		 *    policy).
19197 		 * 2) There is no per-socket policy, but it is
19198 		 *    a multicast packet that needs to go out
19199 		 *    on a specific interface. This is the case
19200 		 *    where (ip_wput and ip_wput_multicast) attaches
19201 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
19202 		 *
19203 		 * In case (2) we check with global policy to
19204 		 * see if there is a match and set the ill_index
19205 		 * appropriately so that we can lookup the ire
19206 		 * properly in ip_wput_ipsec_out.
19207 		 */
19208 
19209 		/*
19210 		 * ipsec_out_use_global_policy is set to B_FALSE
19211 		 * in ipsec_in_to_out(). Refer to that function for
19212 		 * details.
19213 		 */
19214 		if ((io->ipsec_out_latch == NULL) &&
19215 		    (io->ipsec_out_use_global_policy)) {
19216 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
19217 			    ire, connp, unspec_src));
19218 		}
19219 		if (!io->ipsec_out_secure) {
19220 			/*
19221 			 * If this is not a secure packet, drop
19222 			 * the IPSEC_OUT mp and treat it as a clear
19223 			 * packet. This happens when we are sending
19224 			 * a ICMP reply back to a clear packet. See
19225 			 * ipsec_in_to_out() for details.
19226 			 */
19227 			mp = first_mp->b_cont;
19228 			freeb(first_mp);
19229 		}
19230 		return (mp);
19231 	}
19232 	/*
19233 	 * See whether we need to attach a global policy here. We
19234 	 * don't depend on the conn (as it could be null) for deciding
19235 	 * what policy this datagram should go through because it
19236 	 * should have happened in ip_wput if there was some
19237 	 * policy. This normally happens for connections which are not
19238 	 * fully bound preventing us from caching policies in
19239 	 * ip_bind. Packets coming from the TCP listener/global queue
19240 	 * - which are non-hard_bound - could also be affected by
19241 	 * applying policy here.
19242 	 *
19243 	 * If this packet is coming from tcp global queue or listener,
19244 	 * we will be applying policy here.  This may not be *right*
19245 	 * if these packets are coming from the detached connection as
19246 	 * it could have gone in clear before. This happens only if a
19247 	 * TCP connection started when there is no policy and somebody
19248 	 * added policy before it became detached. Thus packets of the
19249 	 * detached connection could go out secure and the other end
19250 	 * would drop it because it will be expecting in clear. The
19251 	 * converse is not true i.e if somebody starts a TCP
19252 	 * connection and deletes the policy, all the packets will
19253 	 * still go out with the policy that existed before deleting
19254 	 * because ip_unbind sends up policy information which is used
19255 	 * by TCP on subsequent ip_wputs. The right solution is to fix
19256 	 * TCP to attach a dummy IPSEC_OUT and set
19257 	 * ipsec_out_use_global_policy to B_FALSE. As this might
19258 	 * affect performance for normal cases, we are not doing it.
19259 	 * Thus, set policy before starting any TCP connections.
19260 	 *
19261 	 * NOTE - We might apply policy even for a hard bound connection
19262 	 * - for which we cached policy in ip_bind - if somebody added
19263 	 * global policy after we inherited the policy in ip_bind.
19264 	 * This means that the packets that were going out in clear
19265 	 * previously would start going secure and hence get dropped
19266 	 * on the other side. To fix this, TCP attaches a dummy
19267 	 * ipsec_out and make sure that we don't apply global policy.
19268 	 */
19269 	if (ipha != NULL)
19270 		policy_present = ipsec_outbound_v4_policy_present;
19271 	else
19272 		policy_present = ipsec_outbound_v6_policy_present;
19273 	if (!policy_present)
19274 		return (mp);
19275 
19276 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src));
19277 }
19278 
19279 ire_t *
19280 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
19281 {
19282 	ipaddr_t addr;
19283 	ire_t *save_ire;
19284 	irb_t *irb;
19285 	ill_group_t *illgrp;
19286 	int	err;
19287 
19288 	save_ire = ire;
19289 	addr = ire->ire_addr;
19290 
19291 	ASSERT(ire->ire_type == IRE_BROADCAST);
19292 
19293 	illgrp = connp->conn_outgoing_ill->ill_group;
19294 	if (illgrp == NULL) {
19295 		*conn_outgoing_ill = conn_get_held_ill(connp,
19296 		    &connp->conn_outgoing_ill, &err);
19297 		if (err == ILL_LOOKUP_FAILED) {
19298 			ire_refrele(save_ire);
19299 			return (NULL);
19300 		}
19301 		return (save_ire);
19302 	}
19303 	/*
19304 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
19305 	 * If it is part of the group, we need to send on the ire
19306 	 * that has been cleared of IRE_MARK_NORECV and that belongs
19307 	 * to this group. This is okay as IP_BOUND_IF really means
19308 	 * any ill in the group. We depend on the fact that the
19309 	 * first ire in the group is always cleared of IRE_MARK_NORECV
19310 	 * if such an ire exists. This is possible only if you have
19311 	 * at least one ill in the group that has not failed.
19312 	 *
19313 	 * First get to the ire that matches the address and group.
19314 	 *
19315 	 * We don't look for an ire with a matching zoneid because a given zone
19316 	 * won't always have broadcast ires on all ills in the group.
19317 	 */
19318 	irb = ire->ire_bucket;
19319 	rw_enter(&irb->irb_lock, RW_READER);
19320 	if (ire->ire_marks & IRE_MARK_NORECV) {
19321 		/*
19322 		 * If the current zone only has an ire broadcast for this
19323 		 * address marked NORECV, the ire we want is ahead in the
19324 		 * bucket, so we look it up deliberately ignoring the zoneid.
19325 		 */
19326 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
19327 			if (ire->ire_addr != addr)
19328 				continue;
19329 			/* skip over deleted ires */
19330 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
19331 				continue;
19332 		}
19333 	}
19334 	while (ire != NULL) {
19335 		/*
19336 		 * If a new interface is coming up, we could end up
19337 		 * seeing the loopback ire and the non-loopback ire
19338 		 * may not have been added yet. So check for ire_stq
19339 		 */
19340 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
19341 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
19342 			break;
19343 		}
19344 		ire = ire->ire_next;
19345 	}
19346 	if (ire != NULL && ire->ire_addr == addr &&
19347 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
19348 		IRE_REFHOLD(ire);
19349 		rw_exit(&irb->irb_lock);
19350 		ire_refrele(save_ire);
19351 		*conn_outgoing_ill = ire_to_ill(ire);
19352 		/*
19353 		 * Refhold the ill to make the conn_outgoing_ill
19354 		 * independent of the ire. ip_wput_ire goes in a loop
19355 		 * and may refrele the ire. Since we have an ire at this
19356 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
19357 		 */
19358 		ill_refhold(*conn_outgoing_ill);
19359 		return (ire);
19360 	}
19361 	rw_exit(&irb->irb_lock);
19362 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
19363 	/*
19364 	 * If we can't find a suitable ire, return the original ire.
19365 	 */
19366 	return (save_ire);
19367 }
19368 
19369 /*
19370  * This function does the ire_refrele of the ire passed in as the
19371  * argument. As this function looks up more ires i.e broadcast ires,
19372  * it needs to REFRELE them. Currently, for simplicity we don't
19373  * differentiate the one passed in and looked up here. We always
19374  * REFRELE.
19375  * IPQoS Notes:
19376  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
19377  * IPSec packets are done in ipsec_out_process.
19378  *
19379  */
19380 void
19381 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller)
19382 {
19383 	ipha_t		*ipha;
19384 #define	rptr	((uchar_t *)ipha)
19385 	mblk_t		*mp1;
19386 	queue_t		*stq;
19387 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
19388 	uint32_t	v_hlen_tos_len;
19389 	uint32_t	ttl_protocol;
19390 	ipaddr_t	src;
19391 	ipaddr_t	dst;
19392 	uint32_t	cksum;
19393 	ipaddr_t	orig_src;
19394 	ire_t		*ire1;
19395 	mblk_t		*next_mp;
19396 	uint_t		hlen;
19397 	uint16_t	*up;
19398 	uint32_t	max_frag = ire->ire_max_frag;
19399 	ill_t		*ill = ire_to_ill(ire);
19400 	int		clusterwide;
19401 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
19402 	int		ipsec_len;
19403 	mblk_t		*first_mp;
19404 	ipsec_out_t	*io;
19405 	boolean_t	conn_dontroute;		/* conn value for multicast */
19406 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
19407 	boolean_t	multicast_forward;	/* Should we forward ? */
19408 	boolean_t	unspec_src;
19409 	ill_t		*conn_outgoing_ill = NULL;
19410 	ill_t		*ire_ill;
19411 	ill_t		*ire1_ill;
19412 	uint32_t 	ill_index = 0;
19413 	boolean_t	multirt_send = B_FALSE;
19414 	int		err;
19415 	zoneid_t	zoneid;
19416 	boolean_t	iphdrhwcksum = B_FALSE;
19417 
19418 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
19419 	    "ip_wput_ire_start: q %p", q);
19420 
19421 	multicast_forward = B_FALSE;
19422 	unspec_src = (connp != NULL && connp->conn_unspec_src);
19423 
19424 	if (ire->ire_flags & RTF_MULTIRT) {
19425 		/*
19426 		 * Multirouting case. The bucket where ire is stored
19427 		 * probably holds other RTF_MULTIRT flagged ire
19428 		 * to the destination. In this call to ip_wput_ire,
19429 		 * we attempt to send the packet through all
19430 		 * those ires. Thus, we first ensure that ire is the
19431 		 * first RTF_MULTIRT ire in the bucket,
19432 		 * before walking the ire list.
19433 		 */
19434 		ire_t *first_ire;
19435 		irb_t *irb = ire->ire_bucket;
19436 		ASSERT(irb != NULL);
19437 
19438 		/* Make sure we do not omit any multiroute ire. */
19439 		IRB_REFHOLD(irb);
19440 		for (first_ire = irb->irb_ire;
19441 		    first_ire != NULL;
19442 		    first_ire = first_ire->ire_next) {
19443 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
19444 			    (first_ire->ire_addr == ire->ire_addr) &&
19445 			    !(first_ire->ire_marks &
19446 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
19447 				break;
19448 		}
19449 
19450 		if ((first_ire != NULL) && (first_ire != ire)) {
19451 			IRE_REFHOLD(first_ire);
19452 			ire_refrele(ire);
19453 			ire = first_ire;
19454 			ill = ire_to_ill(ire);
19455 		}
19456 		IRB_REFRELE(irb);
19457 	}
19458 
19459 	/*
19460 	 * conn_outgoing_ill is used only in the broadcast loop.
19461 	 * for performance we don't grab the mutexs in the fastpath
19462 	 */
19463 	if ((connp != NULL) &&
19464 	    (connp->conn_xmit_if_ill == NULL) &&
19465 	    (ire->ire_type == IRE_BROADCAST) &&
19466 	    ((connp->conn_nofailover_ill != NULL) ||
19467 	    (connp->conn_outgoing_ill != NULL))) {
19468 		/*
19469 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
19470 		 * option. So, see if this endpoint is bound to a
19471 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
19472 		 * that if the interface is failed, we will still send
19473 		 * the packet on the same ill which is what we want.
19474 		 */
19475 		conn_outgoing_ill = conn_get_held_ill(connp,
19476 		    &connp->conn_nofailover_ill, &err);
19477 		if (err == ILL_LOOKUP_FAILED) {
19478 			ire_refrele(ire);
19479 			freemsg(mp);
19480 			return;
19481 		}
19482 		if (conn_outgoing_ill == NULL) {
19483 			/*
19484 			 * Choose a good ill in the group to send the
19485 			 * packets on.
19486 			 */
19487 			ire = conn_set_outgoing_ill(connp, ire,
19488 			    &conn_outgoing_ill);
19489 			if (ire == NULL) {
19490 				freemsg(mp);
19491 				return;
19492 			}
19493 		}
19494 	}
19495 
19496 	if (mp->b_datap->db_type != M_CTL) {
19497 		ipha = (ipha_t *)mp->b_rptr;
19498 		zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
19499 	} else {
19500 		io = (ipsec_out_t *)mp->b_rptr;
19501 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
19502 		zoneid = io->ipsec_out_zoneid;
19503 		ASSERT(zoneid != ALL_ZONES);
19504 		ipha = (ipha_t *)mp->b_cont->b_rptr;
19505 		dst = ipha->ipha_dst;
19506 		/*
19507 		 * For the multicast case, ipsec_out carries conn_dontroute and
19508 		 * conn_multicast_loop as conn may not be available here. We
19509 		 * need this for multicast loopback and forwarding which is done
19510 		 * later in the code.
19511 		 */
19512 		if (CLASSD(dst)) {
19513 			conn_dontroute = io->ipsec_out_dontroute;
19514 			conn_multicast_loop = io->ipsec_out_multicast_loop;
19515 			/*
19516 			 * If conn_dontroute is not set or conn_multicast_loop
19517 			 * is set, we need to do forwarding/loopback. For
19518 			 * datagrams from ip_wput_multicast, conn_dontroute is
19519 			 * set to B_TRUE and conn_multicast_loop is set to
19520 			 * B_FALSE so that we neither do forwarding nor
19521 			 * loopback.
19522 			 */
19523 			if (!conn_dontroute || conn_multicast_loop)
19524 				multicast_forward = B_TRUE;
19525 		}
19526 	}
19527 
19528 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid) {
19529 		/*
19530 		 * When a zone sends a packet to another zone, we try to deliver
19531 		 * the packet under the same conditions as if the destination
19532 		 * was a real node on the network. To do so, we look for a
19533 		 * matching route in the forwarding table.
19534 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
19535 		 * ip_newroute() does.
19536 		 */
19537 		ire_t *src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
19538 		    NULL, NULL, zoneid, 0, (MATCH_IRE_RECURSIVE |
19539 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE));
19540 		if (src_ire != NULL &&
19541 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))) {
19542 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
19543 				ipha->ipha_src = src_ire->ire_src_addr;
19544 			ire_refrele(src_ire);
19545 		} else {
19546 			ire_refrele(ire);
19547 			if (conn_outgoing_ill != NULL)
19548 				ill_refrele(conn_outgoing_ill);
19549 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
19550 			if (src_ire != NULL) {
19551 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
19552 					ire_refrele(src_ire);
19553 					freemsg(mp);
19554 					return;
19555 				}
19556 				ire_refrele(src_ire);
19557 			}
19558 			if (ip_hdr_complete(ipha, zoneid)) {
19559 				/* Failed */
19560 				freemsg(mp);
19561 				return;
19562 			}
19563 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE);
19564 			return;
19565 		}
19566 	}
19567 
19568 	if (mp->b_datap->db_type == M_CTL ||
19569 	    ipsec_outbound_v4_policy_present) {
19570 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
19571 		    unspec_src);
19572 		if (mp == NULL) {
19573 			ire_refrele(ire);
19574 			if (conn_outgoing_ill != NULL)
19575 				ill_refrele(conn_outgoing_ill);
19576 			return;
19577 		}
19578 	}
19579 
19580 	first_mp = mp;
19581 	ipsec_len = 0;
19582 
19583 	if (first_mp->b_datap->db_type == M_CTL) {
19584 		io = (ipsec_out_t *)first_mp->b_rptr;
19585 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
19586 		mp = first_mp->b_cont;
19587 		ipsec_len = ipsec_out_extra_length(first_mp);
19588 		ASSERT(ipsec_len >= 0);
19589 		zoneid = io->ipsec_out_zoneid;
19590 		ASSERT(zoneid != ALL_ZONES);
19591 
19592 		/*
19593 		 * Drop M_CTL here if IPsec processing is not needed.
19594 		 * (Non-IPsec use of M_CTL extracted any information it
19595 		 * needed above).
19596 		 */
19597 		if (ipsec_len == 0) {
19598 			freeb(first_mp);
19599 			first_mp = mp;
19600 		}
19601 	}
19602 
19603 	/*
19604 	 * Fast path for ip_wput_ire
19605 	 */
19606 
19607 	ipha = (ipha_t *)mp->b_rptr;
19608 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19609 	dst = ipha->ipha_dst;
19610 
19611 	/*
19612 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
19613 	 * if the socket is a SOCK_RAW type. The transport checksum should
19614 	 * be provided in the pre-built packet, so we don't need to compute it.
19615 	 * Also, other application set flags, like DF, should not be altered.
19616 	 * Other transport MUST pass down zero.
19617 	 */
19618 	ip_hdr_included = ipha->ipha_ident;
19619 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
19620 
19621 	if (CLASSD(dst)) {
19622 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
19623 		    ntohl(dst),
19624 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
19625 		    ntohl(ire->ire_addr)));
19626 	}
19627 
19628 /* Macros to extract header fields from data already in registers */
19629 #ifdef	_BIG_ENDIAN
19630 #define	V_HLEN	(v_hlen_tos_len >> 24)
19631 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
19632 #define	PROTO	(ttl_protocol & 0xFF)
19633 #else
19634 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19635 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
19636 #define	PROTO	(ttl_protocol >> 8)
19637 #endif
19638 
19639 
19640 	orig_src = src = ipha->ipha_src;
19641 	/* (The loop back to "another" is explained down below.) */
19642 another:;
19643 	/*
19644 	 * Assign an ident value for this packet.  We assign idents on
19645 	 * a per destination basis out of the IRE.  There could be
19646 	 * other threads targeting the same destination, so we have to
19647 	 * arrange for a atomic increment.  Note that we use a 32-bit
19648 	 * atomic add because it has better performance than its
19649 	 * 16-bit sibling.
19650 	 *
19651 	 * If running in cluster mode and if the source address
19652 	 * belongs to a replicated service then vector through
19653 	 * cl_inet_ipident vector to allocate ip identifier
19654 	 * NOTE: This is a contract private interface with the
19655 	 * clustering group.
19656 	 */
19657 	clusterwide = 0;
19658 	if (cl_inet_ipident) {
19659 		ASSERT(cl_inet_isclusterwide);
19660 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
19661 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
19662 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
19663 			    AF_INET, (uint8_t *)(uintptr_t)src,
19664 			    (uint8_t *)(uintptr_t)dst);
19665 			clusterwide = 1;
19666 		}
19667 	}
19668 	if (!clusterwide) {
19669 		ipha->ipha_ident =
19670 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
19671 	}
19672 
19673 #ifndef _BIG_ENDIAN
19674 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
19675 #endif
19676 
19677 	/*
19678 	 * Set source address unless sent on an ill or conn_unspec_src is set.
19679 	 * This is needed to obey conn_unspec_src when packets go through
19680 	 * ip_newroute + arp.
19681 	 * Assumes ip_newroute{,_multi} sets the source address as well.
19682 	 */
19683 	if (src == INADDR_ANY && !unspec_src) {
19684 		/*
19685 		 * Assign the appropriate source address from the IRE if none
19686 		 * was specified.
19687 		 */
19688 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
19689 
19690 		/*
19691 		 * With IP multipathing, broadcast packets are sent on the ire
19692 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
19693 		 * the group. However, this ire might not be in the same zone so
19694 		 * we can't always use its source address. We look for a
19695 		 * broadcast ire in the same group and in the right zone.
19696 		 */
19697 		if (ire->ire_type == IRE_BROADCAST &&
19698 		    ire->ire_zoneid != zoneid) {
19699 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
19700 			    IRE_BROADCAST, ire->ire_ipif, zoneid,
19701 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
19702 			if (src_ire != NULL) {
19703 				src = src_ire->ire_src_addr;
19704 				ire_refrele(src_ire);
19705 			} else {
19706 				ire_refrele(ire);
19707 				if (conn_outgoing_ill != NULL)
19708 					ill_refrele(conn_outgoing_ill);
19709 				freemsg(first_mp);
19710 				BUMP_MIB(&ip_mib, ipOutDiscards);
19711 				return;
19712 			}
19713 		} else {
19714 			src = ire->ire_src_addr;
19715 		}
19716 
19717 		if (connp == NULL) {
19718 			ip1dbg(("ip_wput_ire: no connp and no src "
19719 			    "address for dst 0x%x, using src 0x%x\n",
19720 			    ntohl(dst),
19721 			    ntohl(src)));
19722 		}
19723 		ipha->ipha_src = src;
19724 	}
19725 	stq = ire->ire_stq;
19726 
19727 	/*
19728 	 * We only allow ire chains for broadcasts since there will
19729 	 * be multiple IRE_CACHE entries for the same multicast
19730 	 * address (one per ipif).
19731 	 */
19732 	next_mp = NULL;
19733 
19734 	/* broadcast packet */
19735 	if (ire->ire_type == IRE_BROADCAST)
19736 		goto broadcast;
19737 
19738 	/* loopback ? */
19739 	if (stq == NULL)
19740 		goto nullstq;
19741 
19742 	/* The ill_index for outbound ILL */
19743 	ill_index = Q_TO_INDEX(stq);
19744 
19745 	BUMP_MIB(&ip_mib, ipOutRequests);
19746 	ttl_protocol = ((uint16_t *)ipha)[4];
19747 
19748 	/* pseudo checksum (do it in parts for IP header checksum) */
19749 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
19750 
19751 #define	FRAGMENT_NEEDED(mtu, size)	\
19752 	(((mtu) < (unsigned int)(size)) ? B_TRUE : B_FALSE)
19753 
19754 #define	IS_FASTPATH(ire, bp) 					\
19755 	((ire)->ire_fp_mp != NULL &&				\
19756 	(MBLKHEAD((bp)) >= (MBLKL((ire)->ire_fp_mp))))		\
19757 
19758 #define	IPH_UDPH_CHECKSUMP(ipha, hlen) \
19759 	((uint16_t *)(((uchar_t *)ipha)+(hlen + UDP_CHECKSUM_OFFSET)))
19760 #define	IPH_TCPH_CHECKSUMP(ipha, hlen) \
19761 	    ((uint16_t *)(((uchar_t *)ipha)+(hlen+TCP_CHECKSUM_OFFSET)))
19762 
19763 #define	IP_CKSUM_XMIT(ill, ire, mp, up, proto, hlen, max_frag,		\
19764 	    ipsec_len) { 						\
19765 	uint32_t	sum;						\
19766 	uint32_t	xmit_capab = HCKSUM_INET_FULL_V4 |		\
19767 			    HCKSUM_INET_PARTIAL | HCKSUM_IPHDRCKSUM;	\
19768 	boolean_t	cksum_offload = B_FALSE;			\
19769 									\
19770 	/*								\
19771 	 * The ire fp mp can change due to the arrival of a		\
19772 	 * DL_NOTE_FASTPATH_FLUSH in the case of IRE_BROADCAST		\
19773 	 * and IRE_MIPRTUN. Hence the ire_fp_mp has to be accessed	\
19774 	 * only under the ire_lock in such cases.			\
19775 	 */								\
19776 	LOCK_IRE_FP_MP(ire);						\
19777 	if ((ill) && (ill->ill_capabilities & ILL_CAPAB_HCKSUM) &&	\
19778 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &		\
19779 	    xmit_capab) && (!FRAGMENT_NEEDED(max_frag, 			\
19780 	    (LENGTH + ipsec_len))) && (!(ire->ire_flags & 		\
19781 	    RTF_MULTIRT)) && (ipsec_len == 0) && 			\
19782 	    IS_FASTPATH((ire), (mp)) &&	(dohwcksum)) { 			\
19783 		/*							\
19784 		 * Underlying interface supports hardware checksumming.	\
19785 		 * So postpone the checksum to the interface driver	\
19786 		 */							\
19787 									\
19788 		if ((hlen) == IP_SIMPLE_HDR_LENGTH) {			       \
19789 			if (ill->ill_hcksum_capab->ill_hcksum_txflags &        \
19790 			    HCKSUM_IPHDRCKSUM) {			       \
19791 				mp->b_datap->db_struioun.cksum.flags |=	       \
19792 				    HCK_IPV4_HDRCKSUM;			       \
19793 				/* seed the cksum field to 0 */		       \
19794 				ipha->ipha_hdr_checksum = 0;		       \
19795 				iphdrhwcksum = B_TRUE;			       \
19796 			}						       \
19797 			/*						       \
19798 			 * If underlying h/w supports full h/w checksumming    \
19799 			 * and no IP options are present, then offload	       \
19800 			 * full checksumming to the hardware.		       \
19801 			 *						       \
19802 			 * If h/w can do partial checksumming then offload     \
19803 			 * unless the startpoint offset, including mac-header, \
19804 			 * is too big for the interface to some of our	       \
19805 			 * hardware (CE and ERI) which have 6 bit fields.      \
19806 			 * Sigh.					       \
19807 			 * Unhappily we don't have the mac-header size here    \
19808 			 * so punt for any options.			       \
19809 			 */						       \
19810 			if (ill->ill_hcksum_capab->ill_hcksum_txflags &        \
19811 			    HCKSUM_INET_FULL_V4) {			       \
19812 				UNLOCK_IRE_FP_MP(ire);			       \
19813 				/* Seed the checksum field to 0 */	       \
19814 				*up = 0;				       \
19815 				mp->b_datap->db_struioun.cksum.flags |=	       \
19816 				    HCK_FULLCKSUM;			       \
19817 				cksum_offload = B_TRUE;			       \
19818 			} else if (ill->ill_hcksum_capab->ill_hcksum_txflags & \
19819 			    HCKSUM_INET_PARTIAL) {			       \
19820 				UNLOCK_IRE_FP_MP(ire);			       \
19821 				sum = *up + cksum + proto;		       \
19822 				sum = (sum & 0xFFFF) + (sum >> 16);	       \
19823 				*up = (sum & 0xFFFF) + (sum >> 16);	       \
19824 				/*					       \
19825 				 * All offsets are relative to the beginning   \
19826 				 * of the IP header.			       \
19827 				 */					       \
19828 				mp->b_datap->db_cksumstart = hlen;	       \
19829 				mp->b_datap->db_cksumstuff = 		       \
19830 				    (PROTO == IPPROTO_UDP) ?		       \
19831 				    (hlen) + UDP_CHECKSUM_OFFSET :	       \
19832 				    (hlen) + TCP_CHECKSUM_OFFSET;	       \
19833 				mp->b_datap->db_cksumend = ipha->ipha_length;  \
19834 				mp->b_datap->db_struioun.cksum.flags |=	       \
19835 				    HCK_PARTIALCKSUM;			       \
19836 				cksum_offload = B_TRUE;			       \
19837 			}						       \
19838 		}							\
19839 	} 								\
19840 	if (!cksum_offload) {						\
19841 		UNLOCK_IRE_FP_MP(ire);					\
19842 		IP_STAT(ip_out_sw_cksum);				\
19843 		(sum) = IP_CSUM((mp), (hlen), cksum + proto);		\
19844 		*(up) = (uint16_t)((sum) ? (sum) : ~(sum));		\
19845 	}								\
19846 }
19847 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
19848 		queue_t *dev_q = stq->q_next;
19849 
19850 		/* flow controlled */
19851 		if ((dev_q->q_next || dev_q->q_first) &&
19852 		    !canput(dev_q))
19853 			goto blocked;
19854 		if ((PROTO == IPPROTO_UDP) &&
19855 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
19856 			hlen = (V_HLEN & 0xF) << 2;
19857 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
19858 			if (*up) {
19859 				IP_CKSUM_XMIT(ill, ire, mp, up,
19860 				    IP_UDP_CSUM_COMP, hlen, max_frag,
19861 				    ipsec_len);
19862 			}
19863 		}
19864 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
19865 		hlen = (V_HLEN & 0xF) << 2;
19866 		if (PROTO == IPPROTO_TCP) {
19867 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
19868 			/*
19869 			 * The packet header is processed once and for all, even
19870 			 * in the multirouting case. We disable hardware
19871 			 * checksum if the packet is multirouted, as it will be
19872 			 * replicated via several interfaces, and not all of
19873 			 * them may have this capability.
19874 			 */
19875 			IP_CKSUM_XMIT(ill, ire, mp, up,
19876 			    IP_TCP_CSUM_COMP, hlen, max_frag, ipsec_len);
19877 		} else {
19878 			sctp_hdr_t	*sctph;
19879 
19880 			ASSERT(PROTO == IPPROTO_SCTP);
19881 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
19882 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
19883 			/*
19884 			 * Zero out the checksum field to ensure proper
19885 			 * checksum calculation.
19886 			 */
19887 			sctph->sh_chksum = 0;
19888 #ifdef	DEBUG
19889 			if (!skip_sctp_cksum)
19890 #endif
19891 				sctph->sh_chksum = sctp_cksum(mp, hlen);
19892 		}
19893 	}
19894 
19895 	/*
19896 	 * If this is a multicast packet and originated from ip_wput
19897 	 * we need to do loopback and forwarding checks. If it comes
19898 	 * from ip_wput_multicast, we SHOULD not do this.
19899 	 */
19900 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
19901 
19902 	/* checksum */
19903 	cksum += ttl_protocol;
19904 
19905 	/* fragment the packet */
19906 	if (FRAGMENT_NEEDED(max_frag, (LENGTH + ipsec_len)))
19907 		goto fragmentit;
19908 	/*
19909 	 * Don't use frag_flag if packet is pre-built or source
19910 	 * routed or if multicast (since multicast packets do
19911 	 * not solicit ICMP "packet too big" messages).
19912 	 */
19913 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
19914 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
19915 	    !ip_source_route_included(ipha)) &&
19916 	    !CLASSD(ipha->ipha_dst))
19917 		ipha->ipha_fragment_offset_and_flags |=
19918 		    htons(ire->ire_frag_flag);
19919 
19920 	if (!iphdrhwcksum) {
19921 		/* checksum */
19922 		cksum += ipha->ipha_ident;
19923 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
19924 		cksum += ipha->ipha_fragment_offset_and_flags;
19925 
19926 		/* IP options present */
19927 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
19928 		if (hlen)
19929 			goto checksumoptions;
19930 
19931 		/* calculate hdr checksum */
19932 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
19933 		cksum = ~(cksum + (cksum >> 16));
19934 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
19935 	}
19936 	if (ipsec_len != 0) {
19937 		/*
19938 		 * We will do the rest of the processing after
19939 		 * we come back from IPSEC in ip_wput_ipsec_out().
19940 		 */
19941 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
19942 
19943 		io = (ipsec_out_t *)first_mp->b_rptr;
19944 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
19945 				ill_phyint->phyint_ifindex;
19946 
19947 		ipsec_out_process(q, first_mp, ire, ill_index);
19948 		ire_refrele(ire);
19949 		if (conn_outgoing_ill != NULL)
19950 			ill_refrele(conn_outgoing_ill);
19951 		return;
19952 	}
19953 
19954 	/*
19955 	 * In most cases, the emission loop below is entered only
19956 	 * once. Only in the case where the ire holds the
19957 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
19958 	 * flagged ires in the bucket, and send the packet
19959 	 * through all crossed RTF_MULTIRT routes.
19960 	 */
19961 	if (ire->ire_flags & RTF_MULTIRT) {
19962 		multirt_send = B_TRUE;
19963 	}
19964 	do {
19965 		if (multirt_send) {
19966 			irb_t *irb;
19967 			/*
19968 			 * We are in a multiple send case, need to get
19969 			 * the next ire and make a duplicate of the packet.
19970 			 * ire1 holds here the next ire to process in the
19971 			 * bucket. If multirouting is expected,
19972 			 * any non-RTF_MULTIRT ire that has the
19973 			 * right destination address is ignored.
19974 			 */
19975 			irb = ire->ire_bucket;
19976 			ASSERT(irb != NULL);
19977 
19978 			IRB_REFHOLD(irb);
19979 			for (ire1 = ire->ire_next;
19980 			    ire1 != NULL;
19981 			    ire1 = ire1->ire_next) {
19982 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
19983 					continue;
19984 				if (ire1->ire_addr != ire->ire_addr)
19985 					continue;
19986 				if (ire1->ire_marks &
19987 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
19988 					continue;
19989 
19990 				/* Got one */
19991 				IRE_REFHOLD(ire1);
19992 				break;
19993 			}
19994 			IRB_REFRELE(irb);
19995 
19996 			if (ire1 != NULL) {
19997 				next_mp = copyb(mp);
19998 				if ((next_mp == NULL) ||
19999 				    ((mp->b_cont != NULL) &&
20000 				    ((next_mp->b_cont =
20001 				    dupmsg(mp->b_cont)) == NULL))) {
20002 					freemsg(next_mp);
20003 					next_mp = NULL;
20004 					ire_refrele(ire1);
20005 					ire1 = NULL;
20006 				}
20007 			}
20008 
20009 			/* Last multiroute ire; don't loop anymore. */
20010 			if (ire1 == NULL) {
20011 				multirt_send = B_FALSE;
20012 			}
20013 		}
20014 		mp = ip_wput_attach_llhdr(mp, ire, IPP_LOCAL_OUT, ill_index);
20015 		if (mp == NULL) {
20016 			BUMP_MIB(&ip_mib, ipOutDiscards);
20017 			ip2dbg(("ip_wput_ire: fastpath wput pkt dropped "\
20018 			    "during IPPF processing\n"));
20019 			ire_refrele(ire);
20020 			if (next_mp != NULL) {
20021 				freemsg(next_mp);
20022 				ire_refrele(ire1);
20023 			}
20024 			if (conn_outgoing_ill != NULL)
20025 				ill_refrele(conn_outgoing_ill);
20026 			return;
20027 		}
20028 		UPDATE_OB_PKT_COUNT(ire);
20029 		ire->ire_last_used_time = lbolt;
20030 
20031 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20032 		    "ip_wput_ire_end: q %p (%S)",
20033 		    q, "last copy out");
20034 		putnext(stq, mp);
20035 		IRE_REFRELE(ire);
20036 
20037 		if (multirt_send) {
20038 			ASSERT(ire1);
20039 			/*
20040 			 * Proceed with the next RTF_MULTIRT ire,
20041 			 * Also set up the send-to queue accordingly.
20042 			 */
20043 			ire = ire1;
20044 			ire1 = NULL;
20045 			stq = ire->ire_stq;
20046 			mp = next_mp;
20047 			next_mp = NULL;
20048 			ipha = (ipha_t *)mp->b_rptr;
20049 			ill_index = Q_TO_INDEX(stq);
20050 		}
20051 	} while (multirt_send);
20052 	if (conn_outgoing_ill != NULL)
20053 		ill_refrele(conn_outgoing_ill);
20054 	return;
20055 
20056 	/*
20057 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
20058 	 */
20059 broadcast:
20060 	{
20061 		/*
20062 		 * Avoid broadcast storms by setting the ttl to 1
20063 		 * for broadcasts. This parameter can be set
20064 		 * via ndd, so make sure that for the SO_DONTROUTE
20065 		 * case that ipha_ttl is always set to 1.
20066 		 * In the event that we are replying to incoming
20067 		 * ICMP packets, conn could be NULL.
20068 		 */
20069 		if ((connp != NULL) && connp->conn_dontroute)
20070 			ipha->ipha_ttl = 1;
20071 		else
20072 			ipha->ipha_ttl = ip_broadcast_ttl;
20073 
20074 		/*
20075 		 * Note that we are not doing a IRB_REFHOLD here.
20076 		 * Actually we don't care if the list changes i.e
20077 		 * if somebody deletes an IRE from the list while
20078 		 * we drop the lock, the next time we come around
20079 		 * ire_next will be NULL and hence we won't send
20080 		 * out multiple copies which is fine.
20081 		 */
20082 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20083 		ire1 = ire->ire_next;
20084 		if (conn_outgoing_ill != NULL) {
20085 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
20086 				ASSERT(ire1 == ire->ire_next);
20087 				if (ire1 != NULL && ire1->ire_addr == dst) {
20088 					ire_refrele(ire);
20089 					ire = ire1;
20090 					IRE_REFHOLD(ire);
20091 					ire1 = ire->ire_next;
20092 					continue;
20093 				}
20094 				rw_exit(&ire->ire_bucket->irb_lock);
20095 				/* Did not find a matching ill */
20096 				ip1dbg(("ip_wput_ire: broadcast with no "
20097 				    "matching IP_BOUND_IF ill %s\n",
20098 				    conn_outgoing_ill->ill_name));
20099 				freemsg(first_mp);
20100 				if (ire != NULL)
20101 					ire_refrele(ire);
20102 				ill_refrele(conn_outgoing_ill);
20103 				return;
20104 			}
20105 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
20106 			/*
20107 			 * If the next IRE has the same address and is not one
20108 			 * of the two copies that we need to send, try to see
20109 			 * whether this copy should be sent at all. This
20110 			 * assumes that we insert loopbacks first and then
20111 			 * non-loopbacks. This is acheived by inserting the
20112 			 * loopback always before non-loopback.
20113 			 * This is used to send a single copy of a broadcast
20114 			 * packet out all physical interfaces that have an
20115 			 * matching IRE_BROADCAST while also looping
20116 			 * back one copy (to ip_wput_local) for each
20117 			 * matching physical interface. However, we avoid
20118 			 * sending packets out different logical that match by
20119 			 * having ipif_up/ipif_down supress duplicate
20120 			 * IRE_BROADCASTS.
20121 			 *
20122 			 * This feature is currently used to get broadcasts
20123 			 * sent to multiple interfaces, when the broadcast
20124 			 * address being used applies to multiple interfaces.
20125 			 * For example, a whole net broadcast will be
20126 			 * replicated on every connected subnet of
20127 			 * the target net.
20128 			 *
20129 			 * Each zone has its own set of IRE_BROADCASTs, so that
20130 			 * we're able to distribute inbound packets to multiple
20131 			 * zones who share a broadcast address. We avoid looping
20132 			 * back outbound packets in different zones but on the
20133 			 * same ill, as the application would see duplicates.
20134 			 *
20135 			 * If the interfaces are part of the same group,
20136 			 * we would want to send only one copy out for
20137 			 * whole group.
20138 			 *
20139 			 * This logic assumes that ire_add_v4() groups the
20140 			 * IRE_BROADCAST entries so that those with the same
20141 			 * ire_addr and ill_group are kept together.
20142 			 */
20143 			ire_ill = ire->ire_ipif->ipif_ill;
20144 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
20145 				if (ire_ill->ill_group != NULL &&
20146 				    (ire->ire_marks & IRE_MARK_NORECV)) {
20147 					/*
20148 					 * If the current zone only has an ire
20149 					 * broadcast for this address marked
20150 					 * NORECV, the ire we want is ahead in
20151 					 * the bucket, so we look it up
20152 					 * deliberately ignoring the zoneid.
20153 					 */
20154 					for (ire1 = ire->ire_bucket->irb_ire;
20155 					    ire1 != NULL;
20156 					    ire1 = ire1->ire_next) {
20157 						ire1_ill =
20158 						    ire1->ire_ipif->ipif_ill;
20159 						if (ire1->ire_addr != dst)
20160 							continue;
20161 						/* skip over the current ire */
20162 						if (ire1 == ire)
20163 							continue;
20164 						/* skip over deleted ires */
20165 						if (ire1->ire_marks &
20166 						    IRE_MARK_CONDEMNED)
20167 							continue;
20168 						/*
20169 						 * non-loopback ire in our
20170 						 * group: use it for the next
20171 						 * pass in the loop
20172 						 */
20173 						if (ire1->ire_stq != NULL &&
20174 						    ire1_ill->ill_group ==
20175 						    ire_ill->ill_group)
20176 							break;
20177 					}
20178 				}
20179 			} else {
20180 				while (ire1 != NULL && ire1->ire_addr == dst) {
20181 					ire1_ill = ire1->ire_ipif->ipif_ill;
20182 					/*
20183 					 * We can have two broadcast ires on the
20184 					 * same ill in different zones; here
20185 					 * we'll send a copy of the packet on
20186 					 * each ill and the fanout code will
20187 					 * call conn_wantpacket() to check that
20188 					 * the zone has the broadcast address
20189 					 * configured on the ill. If the two
20190 					 * ires are in the same group we only
20191 					 * send one copy up.
20192 					 */
20193 					if (ire1_ill != ire_ill &&
20194 					    (ire1_ill->ill_group == NULL ||
20195 					    ire_ill->ill_group == NULL ||
20196 					    ire1_ill->ill_group !=
20197 					    ire_ill->ill_group)) {
20198 						break;
20199 					}
20200 					ire1 = ire1->ire_next;
20201 				}
20202 			}
20203 		}
20204 		ASSERT(multirt_send == B_FALSE);
20205 		if (ire1 != NULL && ire1->ire_addr == dst) {
20206 			if ((ire->ire_flags & RTF_MULTIRT) &&
20207 			    (ire1->ire_flags & RTF_MULTIRT)) {
20208 				/*
20209 				 * We are in the multirouting case.
20210 				 * The message must be sent at least
20211 				 * on both ires. These ires have been
20212 				 * inserted AFTER the standard ones
20213 				 * in ip_rt_add(). There are thus no
20214 				 * other ire entries for the destination
20215 				 * address in the rest of the bucket
20216 				 * that do not have the RTF_MULTIRT
20217 				 * flag. We don't process a copy
20218 				 * of the message here. This will be
20219 				 * done in the final sending loop.
20220 				 */
20221 				multirt_send = B_TRUE;
20222 			} else {
20223 				next_mp = ip_copymsg(first_mp);
20224 				if (next_mp != NULL)
20225 					IRE_REFHOLD(ire1);
20226 			}
20227 		}
20228 		rw_exit(&ire->ire_bucket->irb_lock);
20229 	}
20230 
20231 	if (stq) {
20232 		/*
20233 		 * A non-NULL send-to queue means this packet is going
20234 		 * out of this machine.
20235 		 */
20236 
20237 		BUMP_MIB(&ip_mib, ipOutRequests);
20238 		ttl_protocol = ((uint16_t *)ipha)[4];
20239 		/*
20240 		 * We accumulate the pseudo header checksum in cksum.
20241 		 * This is pretty hairy code, so watch close.  One
20242 		 * thing to keep in mind is that UDP and TCP have
20243 		 * stored their respective datagram lengths in their
20244 		 * checksum fields.  This lines things up real nice.
20245 		 */
20246 		cksum = (dst >> 16) + (dst & 0xFFFF) +
20247 		    (src >> 16) + (src & 0xFFFF);
20248 		/*
20249 		 * We assume the udp checksum field contains the
20250 		 * length, so to compute the pseudo header checksum,
20251 		 * all we need is the protocol number and src/dst.
20252 		 */
20253 		/* Provide the checksums for UDP and TCP. */
20254 		if ((PROTO == IPPROTO_TCP) &&
20255 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
20256 			/* hlen gets the number of uchar_ts in the IP header */
20257 			hlen = (V_HLEN & 0xF) << 2;
20258 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
20259 			IP_STAT(ip_out_sw_cksum);
20260 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
20261 		} else if (PROTO == IPPROTO_SCTP &&
20262 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
20263 			sctp_hdr_t	*sctph;
20264 
20265 			hlen = (V_HLEN & 0xF) << 2;
20266 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
20267 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
20268 			sctph->sh_chksum = 0;
20269 #ifdef	DEBUG
20270 			if (!skip_sctp_cksum)
20271 #endif
20272 				sctph->sh_chksum = sctp_cksum(mp, hlen);
20273 		} else {
20274 			queue_t *dev_q = stq->q_next;
20275 
20276 			if ((dev_q->q_next || dev_q->q_first) &&
20277 			    !canput(dev_q)) {
20278 			    blocked:
20279 				ipha->ipha_ident = ip_hdr_included;
20280 				/*
20281 				 * If we don't have a conn to apply
20282 				 * backpressure, free the message.
20283 				 * In the ire_send path, we don't know
20284 				 * the position to requeue the packet. Rather
20285 				 * than reorder packets, we just drop this
20286 				 * packet.
20287 				 */
20288 				if (ip_output_queue && connp != NULL &&
20289 				    caller != IRE_SEND) {
20290 					if (caller == IP_WSRV) {
20291 						connp->conn_did_putbq = 1;
20292 						(void) putbq(connp->conn_wq,
20293 						    first_mp);
20294 						conn_drain_insert(connp);
20295 						/*
20296 						 * This is the service thread,
20297 						 * and the queue is already
20298 						 * noenabled. The check for
20299 						 * canput and the putbq is not
20300 						 * atomic. So we need to check
20301 						 * again.
20302 						 */
20303 						if (canput(stq->q_next))
20304 							connp->conn_did_putbq
20305 							    = 0;
20306 						IP_STAT(ip_conn_flputbq);
20307 					} else {
20308 						/*
20309 						 * We are not the service proc.
20310 						 * ip_wsrv will be scheduled or
20311 						 * is already running.
20312 						 */
20313 						(void) putq(connp->conn_wq,
20314 						    first_mp);
20315 					}
20316 				} else {
20317 					BUMP_MIB(&ip_mib, ipOutDiscards);
20318 					freemsg(first_mp);
20319 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20320 					    "ip_wput_ire_end: q %p (%S)",
20321 					    q, "discard");
20322 				}
20323 				ire_refrele(ire);
20324 				if (next_mp) {
20325 					ire_refrele(ire1);
20326 					freemsg(next_mp);
20327 				}
20328 				if (conn_outgoing_ill != NULL)
20329 					ill_refrele(conn_outgoing_ill);
20330 				return;
20331 			}
20332 			if ((PROTO == IPPROTO_UDP) &&
20333 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
20334 				/*
20335 				 * hlen gets the number of uchar_ts in the
20336 				 * IP header
20337 				 */
20338 				hlen = (V_HLEN & 0xF) << 2;
20339 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
20340 				if (*up) {
20341 					uint_t	sum;
20342 
20343 					/*
20344 					 * NOTE: watch out for compiler high
20345 					 * bits
20346 					 */
20347 					IP_STAT(ip_out_sw_cksum);
20348 					sum = IP_CSUM(mp, hlen,
20349 					    cksum + IP_UDP_CSUM_COMP);
20350 					*up = (uint16_t)(sum ? sum : ~sum);
20351 				}
20352 			}
20353 		}
20354 		/*
20355 		 * Need to do this even when fragmenting. The local
20356 		 * loopback can be done without computing checksums
20357 		 * but forwarding out other interface must be done
20358 		 * after the IP checksum (and ULP checksums) have been
20359 		 * computed.
20360 		 *
20361 		 * NOTE : multicast_forward is set only if this packet
20362 		 * originated from ip_wput. For packets originating from
20363 		 * ip_wput_multicast, it is not set.
20364 		 */
20365 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
20366 		    multi_loopback:
20367 			ip2dbg(("ip_wput: multicast, loop %d\n",
20368 			    conn_multicast_loop));
20369 
20370 			/*  Forget header checksum offload */
20371 			mp->b_datap->db_struioun.cksum.flags &=
20372 			    ~HCK_IPV4_HDRCKSUM;
20373 			iphdrhwcksum = B_FALSE;
20374 
20375 			/*
20376 			 * Local loopback of multicasts?  Check the
20377 			 * ill.
20378 			 *
20379 			 * Note that the loopback function will not come
20380 			 * in through ip_rput - it will only do the
20381 			 * client fanout thus we need to do an mforward
20382 			 * as well.  The is different from the BSD
20383 			 * logic.
20384 			 */
20385 			if (ill != NULL) {
20386 				ilm_t	*ilm;
20387 
20388 				ILM_WALKER_HOLD(ill);
20389 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
20390 				    ALL_ZONES);
20391 				ILM_WALKER_RELE(ill);
20392 				if (ilm != NULL) {
20393 					/*
20394 					 * Pass along the virtual output q.
20395 					 * ip_wput_local() will distribute the
20396 					 * packet to all the matching zones,
20397 					 * except the sending zone when
20398 					 * IP_MULTICAST_LOOP is false.
20399 					 */
20400 					ip_multicast_loopback(q, ill, first_mp,
20401 					    conn_multicast_loop ? 0 :
20402 					    IP_FF_NO_MCAST_LOOP, zoneid);
20403 				}
20404 			}
20405 			if (ipha->ipha_ttl == 0) {
20406 				/*
20407 				 * 0 => only to this host i.e. we are
20408 				 * done. We are also done if this was the
20409 				 * loopback interface since it is sufficient
20410 				 * to loopback one copy of a multicast packet.
20411 				 */
20412 				freemsg(first_mp);
20413 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20414 				    "ip_wput_ire_end: q %p (%S)",
20415 				    q, "loopback");
20416 				ire_refrele(ire);
20417 				if (conn_outgoing_ill != NULL)
20418 					ill_refrele(conn_outgoing_ill);
20419 				return;
20420 			}
20421 			/*
20422 			 * ILLF_MULTICAST is checked in ip_newroute
20423 			 * i.e. we don't need to check it here since
20424 			 * all IRE_CACHEs come from ip_newroute.
20425 			 * For multicast traffic, SO_DONTROUTE is interpreted
20426 			 * to mean only send the packet out the interface
20427 			 * (optionally specified with IP_MULTICAST_IF)
20428 			 * and do not forward it out additional interfaces.
20429 			 * RSVP and the rsvp daemon is an example of a
20430 			 * protocol and user level process that
20431 			 * handles it's own routing. Hence, it uses the
20432 			 * SO_DONTROUTE option to accomplish this.
20433 			 */
20434 
20435 			if (ip_g_mrouter && !conn_dontroute && ill != NULL) {
20436 				/* Unconditionally redo the checksum */
20437 				ipha->ipha_hdr_checksum = 0;
20438 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
20439 
20440 				/*
20441 				 * If this needs to go out secure, we need
20442 				 * to wait till we finish the IPSEC
20443 				 * processing.
20444 				 */
20445 				if (ipsec_len == 0 &&
20446 				    ip_mforward(ill, ipha, mp)) {
20447 					freemsg(first_mp);
20448 					ip1dbg(("ip_wput: mforward failed\n"));
20449 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20450 					    "ip_wput_ire_end: q %p (%S)",
20451 					    q, "mforward failed");
20452 					ire_refrele(ire);
20453 					if (conn_outgoing_ill != NULL)
20454 						ill_refrele(conn_outgoing_ill);
20455 					return;
20456 				}
20457 			}
20458 		}
20459 		max_frag = ire->ire_max_frag;
20460 		cksum += ttl_protocol;
20461 		if (!FRAGMENT_NEEDED(max_frag, (LENGTH + ipsec_len))) {
20462 			/* No fragmentation required for this one. */
20463 			/* Complete the IP header checksum. */
20464 			cksum += ipha->ipha_ident;
20465 			/*
20466 			 * Don't use frag_flag if packet is pre-built or source
20467 			 * routed or if multicast (since multicast packets do
20468 			 * not solicit ICMP "packet too big" messages).
20469 			 */
20470 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
20471 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
20472 			    !ip_source_route_included(ipha)) &&
20473 			    !CLASSD(ipha->ipha_dst))
20474 				ipha->ipha_fragment_offset_and_flags |=
20475 				    htons(ire->ire_frag_flag);
20476 
20477 			cksum += (v_hlen_tos_len >> 16)+
20478 			    (v_hlen_tos_len & 0xFFFF);
20479 			cksum += ipha->ipha_fragment_offset_and_flags;
20480 			hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
20481 			if (hlen) {
20482 			    checksumoptions:
20483 				/*
20484 				 * Account for the IP Options in the IP
20485 				 * header checksum.
20486 				 */
20487 				up = (uint16_t *)(rptr+IP_SIMPLE_HDR_LENGTH);
20488 				do {
20489 					cksum += up[0];
20490 					cksum += up[1];
20491 					up += 2;
20492 				} while (--hlen);
20493 			}
20494 			cksum = ((cksum & 0xFFFF) + (cksum >> 16));
20495 			cksum = ~(cksum + (cksum >> 16));
20496 			ipha->ipha_hdr_checksum = (uint16_t)cksum;
20497 			if (ipsec_len != 0) {
20498 				ipsec_out_process(q, first_mp, ire, ill_index);
20499 				if (!next_mp) {
20500 					ire_refrele(ire);
20501 					if (conn_outgoing_ill != NULL)
20502 						ill_refrele(conn_outgoing_ill);
20503 					return;
20504 				}
20505 				goto next;
20506 			}
20507 
20508 			/*
20509 			 * multirt_send has already been handled
20510 			 * for broadcast, but not yet for multicast
20511 			 * or IP options.
20512 			 */
20513 			if (next_mp == NULL) {
20514 				if (ire->ire_flags & RTF_MULTIRT) {
20515 					multirt_send = B_TRUE;
20516 				}
20517 			}
20518 
20519 			/*
20520 			 * In most cases, the emission loop below is
20521 			 * entered only once. Only in the case where
20522 			 * the ire holds the RTF_MULTIRT flag, do we loop
20523 			 * to process all RTF_MULTIRT ires in the bucket,
20524 			 * and send the packet through all crossed
20525 			 * RTF_MULTIRT routes.
20526 			 */
20527 			do {
20528 				if (multirt_send) {
20529 					irb_t *irb;
20530 
20531 					irb = ire->ire_bucket;
20532 					ASSERT(irb != NULL);
20533 					/*
20534 					 * We are in a multiple send case,
20535 					 * need to get the next IRE and make
20536 					 * a duplicate of the packet.
20537 					 */
20538 					IRB_REFHOLD(irb);
20539 					for (ire1 = ire->ire_next;
20540 					    ire1 != NULL;
20541 					    ire1 = ire1->ire_next) {
20542 						if (!(ire1->ire_flags &
20543 						    RTF_MULTIRT))
20544 							continue;
20545 						if (ire1->ire_addr !=
20546 						    ire->ire_addr)
20547 							continue;
20548 						if (ire1->ire_marks &
20549 						    (IRE_MARK_CONDEMNED|
20550 							IRE_MARK_HIDDEN))
20551 							continue;
20552 
20553 						/* Got one */
20554 						IRE_REFHOLD(ire1);
20555 						break;
20556 					}
20557 					IRB_REFRELE(irb);
20558 
20559 					if (ire1 != NULL) {
20560 						next_mp = copyb(mp);
20561 						if ((next_mp == NULL) ||
20562 						    ((mp->b_cont != NULL) &&
20563 						    ((next_mp->b_cont =
20564 						    dupmsg(mp->b_cont))
20565 						    == NULL))) {
20566 							freemsg(next_mp);
20567 							next_mp = NULL;
20568 							ire_refrele(ire1);
20569 							ire1 = NULL;
20570 						}
20571 					}
20572 
20573 					/*
20574 					 * Last multiroute ire; don't loop
20575 					 * anymore. The emission is over
20576 					 * and next_mp is NULL.
20577 					 */
20578 					if (ire1 == NULL) {
20579 						multirt_send = B_FALSE;
20580 					}
20581 				}
20582 
20583 			noprepend:
20584 				ASSERT(ipsec_len == 0);
20585 				mp1 = ip_wput_attach_llhdr(mp, ire,
20586 				    IPP_LOCAL_OUT, ill_index);
20587 				if (mp1 == NULL) {
20588 					BUMP_MIB(&ip_mib, ipOutDiscards);
20589 					if (next_mp) {
20590 						freemsg(next_mp);
20591 						ire_refrele(ire1);
20592 					}
20593 					ire_refrele(ire);
20594 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20595 					    "ip_wput_ire_end: q %p (%S)",
20596 					    q, "discard MDATA");
20597 					if (conn_outgoing_ill != NULL)
20598 						ill_refrele(conn_outgoing_ill);
20599 					return;
20600 				}
20601 				UPDATE_OB_PKT_COUNT(ire);
20602 				ire->ire_last_used_time = lbolt;
20603 
20604 				if (multirt_send) {
20605 					/*
20606 					 * We are in a multiple send case,
20607 					 * need to re-enter the sending loop
20608 					 * using the next ire.
20609 					 */
20610 					putnext(stq, mp1);
20611 					ire_refrele(ire);
20612 					ire = ire1;
20613 					stq = ire->ire_stq;
20614 					mp = next_mp;
20615 					next_mp = NULL;
20616 					ipha = (ipha_t *)mp->b_rptr;
20617 					ill_index = Q_TO_INDEX(stq);
20618 				}
20619 			} while (multirt_send);
20620 
20621 			if (!next_mp) {
20622 				/*
20623 				 * Last copy going out (the ultra-common
20624 				 * case).  Note that we intentionally replicate
20625 				 * the putnext rather than calling it before
20626 				 * the next_mp check in hopes of a little
20627 				 * tail-call action out of the compiler.
20628 				 */
20629 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20630 				    "ip_wput_ire_end: q %p (%S)",
20631 				    q, "last copy out(1)");
20632 				putnext(stq, mp1);
20633 				ire_refrele(ire);
20634 				if (conn_outgoing_ill != NULL)
20635 					ill_refrele(conn_outgoing_ill);
20636 				return;
20637 			}
20638 			/* More copies going out below. */
20639 			putnext(stq, mp1);
20640 		} else {
20641 			int offset;
20642 		    fragmentit:
20643 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
20644 			/*
20645 			 * If this would generate a icmp_frag_needed message,
20646 			 * we need to handle it before we do the IPSEC
20647 			 * processing. Otherwise, we need to strip the IPSEC
20648 			 * headers before we send up the message to the ULPs
20649 			 * which becomes messy and difficult.
20650 			 */
20651 			if (ipsec_len != 0) {
20652 				if ((max_frag < (unsigned int)(LENGTH +
20653 				    ipsec_len)) && (offset & IPH_DF)) {
20654 
20655 					BUMP_MIB(&ip_mib, ipFragFails);
20656 					ipha->ipha_hdr_checksum = 0;
20657 					ipha->ipha_hdr_checksum =
20658 					    (uint16_t)ip_csum_hdr(ipha);
20659 					icmp_frag_needed(ire->ire_stq, first_mp,
20660 					    max_frag);
20661 					if (!next_mp) {
20662 						ire_refrele(ire);
20663 						if (conn_outgoing_ill != NULL) {
20664 							ill_refrele(
20665 							    conn_outgoing_ill);
20666 						}
20667 						return;
20668 					}
20669 				} else {
20670 					/*
20671 					 * This won't cause a icmp_frag_needed
20672 					 * message. to be gnerated. Send it on
20673 					 * the wire. Note that this could still
20674 					 * cause fragmentation and all we
20675 					 * do is the generation of the message
20676 					 * to the ULP if needed before IPSEC.
20677 					 */
20678 					if (!next_mp) {
20679 						ipsec_out_process(q, first_mp,
20680 						    ire, ill_index);
20681 						TRACE_2(TR_FAC_IP,
20682 						    TR_IP_WPUT_IRE_END,
20683 						    "ip_wput_ire_end: q %p "
20684 						    "(%S)", q,
20685 						    "last ipsec_out_process");
20686 						ire_refrele(ire);
20687 						if (conn_outgoing_ill != NULL) {
20688 							ill_refrele(
20689 							    conn_outgoing_ill);
20690 						}
20691 						return;
20692 					}
20693 					ipsec_out_process(q, first_mp,
20694 					    ire, ill_index);
20695 				}
20696 			} else {
20697 				/* Initiate IPPF processing */
20698 				if (IPP_ENABLED(IPP_LOCAL_OUT)) {
20699 					ip_process(IPP_LOCAL_OUT, &mp,
20700 					    ill_index);
20701 					if (mp == NULL) {
20702 						BUMP_MIB(&ip_mib,
20703 						    ipOutDiscards);
20704 						if (next_mp != NULL) {
20705 							freemsg(next_mp);
20706 							ire_refrele(ire1);
20707 						}
20708 						ire_refrele(ire);
20709 						TRACE_2(TR_FAC_IP,
20710 						    TR_IP_WPUT_IRE_END,
20711 						    "ip_wput_ire: q %p (%S)",
20712 						    q, "discard MDATA");
20713 						if (conn_outgoing_ill != NULL) {
20714 							ill_refrele(
20715 							    conn_outgoing_ill);
20716 						}
20717 						return;
20718 					}
20719 				}
20720 				if (!next_mp) {
20721 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20722 					    "ip_wput_ire_end: q %p (%S)",
20723 					    q, "last fragmentation");
20724 					ip_wput_ire_fragmentit(mp, ire);
20725 					ire_refrele(ire);
20726 					if (conn_outgoing_ill != NULL)
20727 						ill_refrele(conn_outgoing_ill);
20728 					return;
20729 				}
20730 				ip_wput_ire_fragmentit(mp, ire);
20731 			}
20732 		}
20733 	} else {
20734 	    nullstq:
20735 		/* A NULL stq means the destination address is local. */
20736 		UPDATE_OB_PKT_COUNT(ire);
20737 		ire->ire_last_used_time = lbolt;
20738 		ASSERT(ire->ire_ipif != NULL);
20739 		if (!next_mp) {
20740 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20741 			    "ip_wput_ire_end: q %p (%S)",
20742 			    q, "local address");
20743 			ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha,
20744 			    first_mp, ire, 0, ire->ire_zoneid);
20745 			ire_refrele(ire);
20746 			if (conn_outgoing_ill != NULL)
20747 				ill_refrele(conn_outgoing_ill);
20748 			return;
20749 		}
20750 		ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha, first_mp,
20751 		    ire, 0, ire->ire_zoneid);
20752 	}
20753 next:
20754 	/*
20755 	 * More copies going out to additional interfaces.
20756 	 * ire1 has already been held. We don't need the
20757 	 * "ire" anymore.
20758 	 */
20759 	ire_refrele(ire);
20760 	ire = ire1;
20761 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
20762 	mp = next_mp;
20763 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
20764 	ill = ire_to_ill(ire);
20765 	first_mp = mp;
20766 	if (ipsec_len != 0) {
20767 		ASSERT(first_mp->b_datap->db_type == M_CTL);
20768 		mp = mp->b_cont;
20769 	}
20770 	dst = ire->ire_addr;
20771 	ipha = (ipha_t *)mp->b_rptr;
20772 	/*
20773 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
20774 	 * Restore ipha_ident "no checksum" flag.
20775 	 */
20776 	src = orig_src;
20777 	ipha->ipha_ident = ip_hdr_included;
20778 	goto another;
20779 
20780 #undef	rptr
20781 #undef	Q_TO_INDEX
20782 }
20783 
20784 /*
20785  * Routine to allocate a message that is used to notify the ULP about MDT.
20786  * The caller may provide a pointer to the link-layer MDT capabilities,
20787  * or NULL if MDT is to be disabled on the stream.
20788  */
20789 mblk_t *
20790 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
20791 {
20792 	mblk_t *mp;
20793 	ip_mdt_info_t *mdti;
20794 	ill_mdt_capab_t *idst;
20795 
20796 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
20797 		DB_TYPE(mp) = M_CTL;
20798 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
20799 		mdti = (ip_mdt_info_t *)mp->b_rptr;
20800 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
20801 		idst = &(mdti->mdt_capab);
20802 
20803 		/*
20804 		 * If the caller provides us with the capability, copy
20805 		 * it over into our notification message; otherwise
20806 		 * we zero out the capability portion.
20807 		 */
20808 		if (isrc != NULL)
20809 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
20810 		else
20811 			bzero((caddr_t)idst, sizeof (*idst));
20812 	}
20813 	return (mp);
20814 }
20815 
20816 /*
20817  * Routine which determines whether MDT can be enabled on the destination
20818  * IRE and IPC combination, and if so, allocates and returns the MDT
20819  * notification mblk that may be used by ULP.  We also check if we need to
20820  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
20821  * MDT usage in the past have been lifted.  This gets called during IP
20822  * and ULP binding.
20823  */
20824 mblk_t *
20825 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
20826     ill_mdt_capab_t *mdt_cap)
20827 {
20828 	mblk_t *mp;
20829 	boolean_t rc = B_FALSE;
20830 
20831 	ASSERT(dst_ire != NULL);
20832 	ASSERT(connp != NULL);
20833 	ASSERT(mdt_cap != NULL);
20834 
20835 	/*
20836 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
20837 	 * Multidata, which is handled in tcp_multisend().  This
20838 	 * is the reason why we do all these checks here, to ensure
20839 	 * that we don't enable Multidata for the cases which we
20840 	 * can't handle at the moment.
20841 	 */
20842 	do {
20843 		/* Only do TCP at the moment */
20844 		if (connp->conn_ulp != IPPROTO_TCP)
20845 			break;
20846 
20847 		/*
20848 		 * IPSEC outbound policy present?  Note that we get here
20849 		 * after calling ipsec_conn_cache_policy() where the global
20850 		 * policy checking is performed.  conn_latch will be
20851 		 * non-NULL as long as there's a policy defined,
20852 		 * i.e. conn_out_enforce_policy may be NULL in such case
20853 		 * when the connection is non-secure, and hence we check
20854 		 * further if the latch refers to an outbound policy.
20855 		 */
20856 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
20857 			break;
20858 
20859 		/* CGTP (multiroute) is enabled? */
20860 		if (dst_ire->ire_flags & RTF_MULTIRT)
20861 			break;
20862 
20863 		/* Outbound IPQoS enabled? */
20864 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
20865 			/*
20866 			 * In this case, we disable MDT for this and all
20867 			 * future connections going over the interface.
20868 			 */
20869 			mdt_cap->ill_mdt_on = 0;
20870 			break;
20871 		}
20872 
20873 		/* socket option(s) present? */
20874 		if (!CONN_IS_MD_FASTPATH(connp))
20875 			break;
20876 
20877 		rc = B_TRUE;
20878 	/* CONSTCOND */
20879 	} while (0);
20880 
20881 	/* Remember the result */
20882 	connp->conn_mdt_ok = rc;
20883 
20884 	if (!rc)
20885 		return (NULL);
20886 	else if (!mdt_cap->ill_mdt_on) {
20887 		/*
20888 		 * If MDT has been previously turned off in the past, and we
20889 		 * currently can do MDT (due to IPQoS policy removal, etc.)
20890 		 * then enable it for this interface.
20891 		 */
20892 		mdt_cap->ill_mdt_on = 1;
20893 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
20894 		    "interface %s\n", ill_name));
20895 	}
20896 
20897 	/* Allocate the MDT info mblk */
20898 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
20899 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
20900 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
20901 		return (NULL);
20902 	}
20903 	return (mp);
20904 }
20905 
20906 /*
20907  * Create destination address attribute, and fill it with the physical
20908  * destination address and SAP taken from the template DL_UNITDATA_REQ
20909  * message block.
20910  */
20911 boolean_t
20912 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
20913 {
20914 	dl_unitdata_req_t *dlurp;
20915 	pattr_t *pa;
20916 	pattrinfo_t pa_info;
20917 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
20918 	uint_t das_len, das_off;
20919 
20920 	ASSERT(dlmp != NULL);
20921 
20922 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
20923 	das_len = dlurp->dl_dest_addr_length;
20924 	das_off = dlurp->dl_dest_addr_offset;
20925 
20926 	pa_info.type = PATTR_DSTADDRSAP;
20927 	pa_info.len = sizeof (**das) + das_len - 1;
20928 
20929 	/* create and associate the attribute */
20930 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
20931 	if (pa != NULL) {
20932 		ASSERT(*das != NULL);
20933 		(*das)->addr_is_group = 0;
20934 		(*das)->addr_len = (uint8_t)das_len;
20935 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
20936 	}
20937 
20938 	return (pa != NULL);
20939 }
20940 
20941 /*
20942  * Create hardware checksum attribute and fill it with the values passed.
20943  */
20944 boolean_t
20945 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
20946     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
20947 {
20948 	pattr_t *pa;
20949 	pattrinfo_t pa_info;
20950 
20951 	ASSERT(mmd != NULL);
20952 
20953 	pa_info.type = PATTR_HCKSUM;
20954 	pa_info.len = sizeof (pattr_hcksum_t);
20955 
20956 	/* create and associate the attribute */
20957 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
20958 	if (pa != NULL) {
20959 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
20960 
20961 		hck->hcksum_start_offset = start_offset;
20962 		hck->hcksum_stuff_offset = stuff_offset;
20963 		hck->hcksum_end_offset = end_offset;
20964 		hck->hcksum_flags = flags;
20965 	}
20966 	return (pa != NULL);
20967 }
20968 
20969 /*
20970  * Create zerocopy attribute and fill it with the specified flags
20971  */
20972 boolean_t
20973 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
20974 {
20975 	pattr_t *pa;
20976 	pattrinfo_t pa_info;
20977 
20978 	ASSERT(mmd != NULL);
20979 	pa_info.type = PATTR_ZCOPY;
20980 	pa_info.len = sizeof (pattr_zcopy_t);
20981 
20982 	/* create and associate the attribute */
20983 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
20984 	if (pa != NULL) {
20985 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
20986 
20987 		zcopy->zcopy_flags = flags;
20988 	}
20989 	return (pa != NULL);
20990 }
20991 
20992 /*
20993  * Outbound IP fragmentation routine.
20994  *
20995  * NOTE : This routine does not ire_refrele the ire that is passed in
20996  * as the argument.
20997  */
20998 static void
20999 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
21000     uint32_t frag_flag)
21001 {
21002 	int	i1;
21003 	mblk_t	*ll_hdr_mp;
21004 	int 	ll_hdr_len;
21005 	int	hdr_len;
21006 	mblk_t	*hdr_mp;
21007 	ipha_t	*ipha;
21008 	int	ip_data_end;
21009 	int	len;
21010 	mblk_t	*mp = mp_orig;
21011 	int	offset;
21012 	queue_t	*q;
21013 	uint32_t	v_hlen_tos_len;
21014 	mblk_t	*first_mp;
21015 	boolean_t mctl_present;
21016 	mblk_t	*xmit_mp;
21017 	mblk_t	*carve_mp;
21018 	ire_t   *ire1 = NULL;
21019 	ire_t   *save_ire = NULL;
21020 	mblk_t  *next_mp = NULL;
21021 	boolean_t last_frag = B_FALSE;
21022 	boolean_t multirt_send = B_FALSE;
21023 	ire_t *first_ire = NULL;
21024 	irb_t *irb = NULL;
21025 
21026 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
21027 	    "ip_wput_frag_start:");
21028 
21029 	if (mp->b_datap->db_type == M_CTL) {
21030 		first_mp = mp;
21031 		mp_orig = mp = mp->b_cont;
21032 		mctl_present = B_TRUE;
21033 	} else {
21034 		first_mp = mp;
21035 		mctl_present = B_FALSE;
21036 	}
21037 
21038 	ipha = (ipha_t *)mp->b_rptr;
21039 
21040 	/*
21041 	 * If the Don't Fragment flag is on, generate an ICMP destination
21042 	 * unreachable, fragmentation needed.
21043 	 */
21044 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
21045 	if (offset & IPH_DF) {
21046 		BUMP_MIB(&ip_mib, ipFragFails);
21047 		/*
21048 		 * Need to compute hdr checksum if called from ip_wput_ire.
21049 		 * Note that ip_rput_forward verifies the checksum before
21050 		 * calling this routine so in that case this is a noop.
21051 		 */
21052 		ipha->ipha_hdr_checksum = 0;
21053 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21054 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag);
21055 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21056 		    "ip_wput_frag_end:(%S)",
21057 		    "don't fragment");
21058 		return;
21059 	}
21060 	if (mctl_present)
21061 		freeb(first_mp);
21062 	/*
21063 	 * Establish the starting offset.  May not be zero if we are fragging
21064 	 * a fragment that is being forwarded.
21065 	 */
21066 	offset = offset & IPH_OFFSET;
21067 
21068 	/* TODO why is this test needed? */
21069 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21070 	if (((max_frag - LENGTH) & ~7) < 8) {
21071 		/* TODO: notify ulp somehow */
21072 		BUMP_MIB(&ip_mib, ipFragFails);
21073 		freemsg(mp);
21074 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21075 		    "ip_wput_frag_end:(%S)",
21076 		    "len < 8");
21077 		return;
21078 	}
21079 
21080 	hdr_len = (V_HLEN & 0xF) << 2;
21081 	ipha->ipha_hdr_checksum = 0;
21082 
21083 	/* Get a copy of the header for the trailing frags */
21084 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset);
21085 	if (!hdr_mp) {
21086 		BUMP_MIB(&ip_mib, ipOutDiscards);
21087 		freemsg(mp);
21088 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21089 		    "ip_wput_frag_end:(%S)",
21090 		    "couldn't copy hdr");
21091 		return;
21092 	}
21093 
21094 	/* Store the starting offset, with the MoreFrags flag. */
21095 	i1 = offset | IPH_MF | frag_flag;
21096 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
21097 
21098 	/* Establish the ending byte offset, based on the starting offset. */
21099 	offset <<= 3;
21100 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
21101 
21102 	/*
21103 	 * Establish the number of bytes maximum per frag, after putting
21104 	 * in the header.
21105 	 */
21106 	len = (max_frag - hdr_len) & ~7;
21107 
21108 	/* Store the length of the first fragment in the IP header. */
21109 	i1 = len + hdr_len;
21110 	ASSERT(i1 <= IP_MAXPACKET);
21111 	ipha->ipha_length = htons((uint16_t)i1);
21112 
21113 	/*
21114 	 * Compute the IP header checksum for the first frag.  We have to
21115 	 * watch out that we stop at the end of the header.
21116 	 */
21117 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21118 
21119 	/*
21120 	 * Now carve off the first frag.  Note that this will include the
21121 	 * original IP header.
21122 	 */
21123 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
21124 		BUMP_MIB(&ip_mib, ipOutDiscards);
21125 		freeb(hdr_mp);
21126 		freemsg(mp_orig);
21127 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21128 		    "ip_wput_frag_end:(%S)",
21129 		    "couldn't carve first");
21130 		return;
21131 	}
21132 
21133 	/*
21134 	 * Multirouting case. Each fragment is replicated
21135 	 * via all non-condemned RTF_MULTIRT routes
21136 	 * currently resolved.
21137 	 * We ensure that first_ire is the first RTF_MULTIRT
21138 	 * ire in the bucket.
21139 	 */
21140 	if (ire->ire_flags & RTF_MULTIRT) {
21141 		irb = ire->ire_bucket;
21142 		ASSERT(irb != NULL);
21143 
21144 		multirt_send = B_TRUE;
21145 
21146 		/* Make sure we do not omit any multiroute ire. */
21147 		IRB_REFHOLD(irb);
21148 		for (first_ire = irb->irb_ire;
21149 		    first_ire != NULL;
21150 		    first_ire = first_ire->ire_next) {
21151 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
21152 			    (first_ire->ire_addr == ire->ire_addr) &&
21153 			    !(first_ire->ire_marks &
21154 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
21155 				break;
21156 		}
21157 
21158 		if (first_ire != NULL) {
21159 			if (first_ire != ire) {
21160 				IRE_REFHOLD(first_ire);
21161 				/*
21162 				 * Do not release the ire passed in
21163 				 * as the argument.
21164 				 */
21165 				ire = first_ire;
21166 			} else {
21167 				first_ire = NULL;
21168 			}
21169 		}
21170 		IRB_REFRELE(irb);
21171 
21172 		/*
21173 		 * Save the first ire; we will need to restore it
21174 		 * for the trailing frags.
21175 		 * We REFHOLD save_ire, as each iterated ire will be
21176 		 * REFRELEd.
21177 		 */
21178 		save_ire = ire;
21179 		IRE_REFHOLD(save_ire);
21180 	}
21181 
21182 	/*
21183 	 * First fragment emission loop.
21184 	 * In most cases, the emission loop below is entered only
21185 	 * once. Only in the case where the ire holds the RTF_MULTIRT
21186 	 * flag, do we loop to process all RTF_MULTIRT ires in the
21187 	 * bucket, and send the fragment through all crossed
21188 	 * RTF_MULTIRT routes.
21189 	 */
21190 	do {
21191 		if (ire->ire_flags & RTF_MULTIRT) {
21192 			/*
21193 			 * We are in a multiple send case, need to get
21194 			 * the next ire and make a copy of the packet.
21195 			 * ire1 holds here the next ire to process in the
21196 			 * bucket. If multirouting is expected,
21197 			 * any non-RTF_MULTIRT ire that has the
21198 			 * right destination address is ignored.
21199 			 *
21200 			 * We have to take into account the MTU of
21201 			 * each walked ire. max_frag is set by the
21202 			 * the caller and generally refers to
21203 			 * the primary ire entry. Here we ensure that
21204 			 * no route with a lower MTU will be used, as
21205 			 * fragments are carved once for all ires,
21206 			 * then replicated.
21207 			 */
21208 			ASSERT(irb != NULL);
21209 			IRB_REFHOLD(irb);
21210 			for (ire1 = ire->ire_next;
21211 			    ire1 != NULL;
21212 			    ire1 = ire1->ire_next) {
21213 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
21214 					continue;
21215 				if (ire1->ire_addr != ire->ire_addr)
21216 					continue;
21217 				if (ire1->ire_marks &
21218 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
21219 					continue;
21220 				/*
21221 				 * Ensure we do not exceed the MTU
21222 				 * of the next route.
21223 				 */
21224 				if (ire1->ire_max_frag < max_frag) {
21225 					ip_multirt_bad_mtu(ire1, max_frag);
21226 					continue;
21227 				}
21228 
21229 				/* Got one. */
21230 				IRE_REFHOLD(ire1);
21231 				break;
21232 			}
21233 			IRB_REFRELE(irb);
21234 
21235 			if (ire1 != NULL) {
21236 				next_mp = copyb(mp);
21237 				if ((next_mp == NULL) ||
21238 				    ((mp->b_cont != NULL) &&
21239 				    ((next_mp->b_cont =
21240 				    dupmsg(mp->b_cont)) == NULL))) {
21241 					freemsg(next_mp);
21242 					next_mp = NULL;
21243 					ire_refrele(ire1);
21244 					ire1 = NULL;
21245 				}
21246 			}
21247 
21248 			/* Last multiroute ire; don't loop anymore. */
21249 			if (ire1 == NULL) {
21250 				multirt_send = B_FALSE;
21251 			}
21252 		}
21253 
21254 		ll_hdr_len = 0;
21255 		LOCK_IRE_FP_MP(ire);
21256 		ll_hdr_mp = ire->ire_fp_mp;
21257 		if (ll_hdr_mp != NULL) {
21258 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
21259 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
21260 		} else {
21261 			ll_hdr_mp = ire->ire_dlureq_mp;
21262 		}
21263 
21264 		/* If there is a transmit header, get a copy for this frag. */
21265 		/*
21266 		 * TODO: should check db_ref before calling ip_carve_mp since
21267 		 * it might give us a dup.
21268 		 */
21269 		if (!ll_hdr_mp) {
21270 			/* No xmit header. */
21271 			xmit_mp = mp;
21272 		} else if (mp->b_datap->db_ref == 1 &&
21273 		    ll_hdr_len != 0 &&
21274 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
21275 			/* M_DATA fastpath */
21276 			mp->b_rptr -= ll_hdr_len;
21277 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
21278 			xmit_mp = mp;
21279 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
21280 			UNLOCK_IRE_FP_MP(ire);
21281 			BUMP_MIB(&ip_mib, ipOutDiscards);
21282 			freeb(hdr_mp);
21283 			freemsg(mp);
21284 			freemsg(mp_orig);
21285 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21286 			    "ip_wput_frag_end:(%S)",
21287 			    "discard");
21288 
21289 			if (multirt_send) {
21290 				ASSERT(ire1);
21291 				ASSERT(next_mp);
21292 
21293 				freemsg(next_mp);
21294 				ire_refrele(ire1);
21295 			}
21296 			if (save_ire != NULL)
21297 				IRE_REFRELE(save_ire);
21298 
21299 			if (first_ire != NULL)
21300 				ire_refrele(first_ire);
21301 			return;
21302 		} else {
21303 			xmit_mp->b_cont = mp;
21304 			/* Get priority marking, if any. */
21305 			if (DB_TYPE(xmit_mp) == M_DATA)
21306 				xmit_mp->b_band = mp->b_band;
21307 		}
21308 		UNLOCK_IRE_FP_MP(ire);
21309 		q = ire->ire_stq;
21310 		BUMP_MIB(&ip_mib, ipFragCreates);
21311 		putnext(q, xmit_mp);
21312 		if (pkt_type != OB_PKT) {
21313 			/*
21314 			 * Update the packet count of trailing
21315 			 * RTF_MULTIRT ires.
21316 			 */
21317 			UPDATE_OB_PKT_COUNT(ire);
21318 		}
21319 
21320 		if (multirt_send) {
21321 			/*
21322 			 * We are in a multiple send case; look for
21323 			 * the next ire and re-enter the loop.
21324 			 */
21325 			ASSERT(ire1);
21326 			ASSERT(next_mp);
21327 			/* REFRELE the current ire before looping */
21328 			ire_refrele(ire);
21329 			ire = ire1;
21330 			ire1 = NULL;
21331 			mp = next_mp;
21332 			next_mp = NULL;
21333 		}
21334 	} while (multirt_send);
21335 
21336 	ASSERT(ire1 == NULL);
21337 
21338 	/* Restore the original ire; we need it for the trailing frags */
21339 	if (save_ire != NULL) {
21340 		/* REFRELE the last iterated ire */
21341 		ire_refrele(ire);
21342 		/* save_ire has been REFHOLDed */
21343 		ire = save_ire;
21344 		save_ire = NULL;
21345 		q = ire->ire_stq;
21346 	}
21347 
21348 	if (pkt_type == OB_PKT) {
21349 		UPDATE_OB_PKT_COUNT(ire);
21350 	} else {
21351 		UPDATE_IB_PKT_COUNT(ire);
21352 	}
21353 
21354 	/* Advance the offset to the second frag starting point. */
21355 	offset += len;
21356 	/*
21357 	 * Update hdr_len from the copied header - there might be less options
21358 	 * in the later fragments.
21359 	 */
21360 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
21361 	/* Loop until done. */
21362 	for (;;) {
21363 		uint16_t	offset_and_flags;
21364 		uint16_t	ip_len;
21365 
21366 		if (ip_data_end - offset > len) {
21367 			/*
21368 			 * Carve off the appropriate amount from the original
21369 			 * datagram.
21370 			 */
21371 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
21372 				mp = NULL;
21373 				break;
21374 			}
21375 			/*
21376 			 * More frags after this one.  Get another copy
21377 			 * of the header.
21378 			 */
21379 			if (carve_mp->b_datap->db_ref == 1 &&
21380 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
21381 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
21382 				/* Inline IP header */
21383 				carve_mp->b_rptr -= hdr_mp->b_wptr -
21384 				    hdr_mp->b_rptr;
21385 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
21386 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
21387 				mp = carve_mp;
21388 			} else {
21389 				if (!(mp = copyb(hdr_mp))) {
21390 					freemsg(carve_mp);
21391 					break;
21392 				}
21393 				/* Get priority marking, if any. */
21394 				mp->b_band = carve_mp->b_band;
21395 				mp->b_cont = carve_mp;
21396 			}
21397 			ipha = (ipha_t *)mp->b_rptr;
21398 			offset_and_flags = IPH_MF;
21399 		} else {
21400 			/*
21401 			 * Last frag.  Consume the header. Set len to
21402 			 * the length of this last piece.
21403 			 */
21404 			len = ip_data_end - offset;
21405 
21406 			/*
21407 			 * Carve off the appropriate amount from the original
21408 			 * datagram.
21409 			 */
21410 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
21411 				mp = NULL;
21412 				break;
21413 			}
21414 			if (carve_mp->b_datap->db_ref == 1 &&
21415 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
21416 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
21417 				/* Inline IP header */
21418 				carve_mp->b_rptr -= hdr_mp->b_wptr -
21419 				    hdr_mp->b_rptr;
21420 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
21421 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
21422 				mp = carve_mp;
21423 				freeb(hdr_mp);
21424 				hdr_mp = mp;
21425 			} else {
21426 				mp = hdr_mp;
21427 				/* Get priority marking, if any. */
21428 				mp->b_band = carve_mp->b_band;
21429 				mp->b_cont = carve_mp;
21430 			}
21431 			ipha = (ipha_t *)mp->b_rptr;
21432 			/* A frag of a frag might have IPH_MF non-zero */
21433 			offset_and_flags =
21434 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
21435 			    IPH_MF;
21436 		}
21437 		offset_and_flags |= (uint16_t)(offset >> 3);
21438 		offset_and_flags |= (uint16_t)frag_flag;
21439 		/* Store the offset and flags in the IP header. */
21440 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
21441 
21442 		/* Store the length in the IP header. */
21443 		ip_len = (uint16_t)(len + hdr_len);
21444 		ipha->ipha_length = htons(ip_len);
21445 
21446 		/*
21447 		 * Set the IP header checksum.	Note that mp is just
21448 		 * the header, so this is easy to pass to ip_csum.
21449 		 */
21450 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21451 
21452 		/* Attach a transmit header, if any, and ship it. */
21453 		if (pkt_type == OB_PKT) {
21454 			UPDATE_OB_PKT_COUNT(ire);
21455 		} else {
21456 			UPDATE_IB_PKT_COUNT(ire);
21457 		}
21458 
21459 		if (ire->ire_flags & RTF_MULTIRT) {
21460 			irb = ire->ire_bucket;
21461 			ASSERT(irb != NULL);
21462 
21463 			multirt_send = B_TRUE;
21464 
21465 			/*
21466 			 * Save the original ire; we will need to restore it
21467 			 * for the tailing frags.
21468 			 */
21469 			save_ire = ire;
21470 			IRE_REFHOLD(save_ire);
21471 		}
21472 		/*
21473 		 * Emission loop for this fragment, similar
21474 		 * to what is done for the first fragment.
21475 		 */
21476 		do {
21477 			if (multirt_send) {
21478 				/*
21479 				 * We are in a multiple send case, need to get
21480 				 * the next ire and make a copy of the packet.
21481 				 */
21482 				ASSERT(irb != NULL);
21483 				IRB_REFHOLD(irb);
21484 				for (ire1 = ire->ire_next;
21485 				    ire1 != NULL;
21486 				    ire1 = ire1->ire_next) {
21487 					if (!(ire1->ire_flags & RTF_MULTIRT))
21488 						continue;
21489 					if (ire1->ire_addr != ire->ire_addr)
21490 						continue;
21491 					if (ire1->ire_marks &
21492 					    (IRE_MARK_CONDEMNED|
21493 						IRE_MARK_HIDDEN))
21494 						continue;
21495 					/*
21496 					 * Ensure we do not exceed the MTU
21497 					 * of the next route.
21498 					 */
21499 					if (ire1->ire_max_frag < max_frag) {
21500 						ip_multirt_bad_mtu(ire1,
21501 						    max_frag);
21502 						continue;
21503 					}
21504 
21505 					/* Got one. */
21506 					IRE_REFHOLD(ire1);
21507 					break;
21508 				}
21509 				IRB_REFRELE(irb);
21510 
21511 				if (ire1 != NULL) {
21512 					next_mp = copyb(mp);
21513 					if ((next_mp == NULL) ||
21514 					    ((mp->b_cont != NULL) &&
21515 					    ((next_mp->b_cont =
21516 					    dupmsg(mp->b_cont)) == NULL))) {
21517 						freemsg(next_mp);
21518 						next_mp = NULL;
21519 						ire_refrele(ire1);
21520 						ire1 = NULL;
21521 					}
21522 				}
21523 
21524 				/* Last multiroute ire; don't loop anymore. */
21525 				if (ire1 == NULL) {
21526 					multirt_send = B_FALSE;
21527 				}
21528 			}
21529 
21530 			/* Update transmit header */
21531 			ll_hdr_len = 0;
21532 			LOCK_IRE_FP_MP(ire);
21533 			ll_hdr_mp = ire->ire_fp_mp;
21534 			if (ll_hdr_mp != NULL) {
21535 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
21536 				ll_hdr_len = MBLKL(ll_hdr_mp);
21537 			} else {
21538 				ll_hdr_mp = ire->ire_dlureq_mp;
21539 			}
21540 
21541 			if (!ll_hdr_mp) {
21542 				xmit_mp = mp;
21543 			} else if (mp->b_datap->db_ref == 1 &&
21544 			    ll_hdr_len != 0 &&
21545 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
21546 				/* M_DATA fastpath */
21547 				mp->b_rptr -= ll_hdr_len;
21548 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
21549 				    ll_hdr_len);
21550 				xmit_mp = mp;
21551 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
21552 				xmit_mp->b_cont = mp;
21553 				/* Get priority marking, if any. */
21554 				if (DB_TYPE(xmit_mp) == M_DATA)
21555 					xmit_mp->b_band = mp->b_band;
21556 			} else {
21557 				/*
21558 				 * Exit both the replication and
21559 				 * fragmentation loops.
21560 				 */
21561 				UNLOCK_IRE_FP_MP(ire);
21562 				goto drop_pkt;
21563 			}
21564 			UNLOCK_IRE_FP_MP(ire);
21565 			BUMP_MIB(&ip_mib, ipFragCreates);
21566 			putnext(q, xmit_mp);
21567 
21568 			if (pkt_type != OB_PKT) {
21569 				/*
21570 				 * Update the packet count of trailing
21571 				 * RTF_MULTIRT ires.
21572 				 */
21573 				UPDATE_OB_PKT_COUNT(ire);
21574 			}
21575 
21576 			/* All done if we just consumed the hdr_mp. */
21577 			if (mp == hdr_mp) {
21578 				last_frag = B_TRUE;
21579 			}
21580 
21581 			if (multirt_send) {
21582 				/*
21583 				 * We are in a multiple send case; look for
21584 				 * the next ire and re-enter the loop.
21585 				 */
21586 				ASSERT(ire1);
21587 				ASSERT(next_mp);
21588 				/* REFRELE the current ire before looping */
21589 				ire_refrele(ire);
21590 				ire = ire1;
21591 				ire1 = NULL;
21592 				q = ire->ire_stq;
21593 				mp = next_mp;
21594 				next_mp = NULL;
21595 			}
21596 		} while (multirt_send);
21597 		/*
21598 		 * Restore the original ire; we need it for the
21599 		 * trailing frags
21600 		 */
21601 		if (save_ire != NULL) {
21602 			ASSERT(ire1 == NULL);
21603 			/* REFRELE the last iterated ire */
21604 			ire_refrele(ire);
21605 			/* save_ire has been REFHOLDed */
21606 			ire = save_ire;
21607 			q = ire->ire_stq;
21608 			save_ire = NULL;
21609 		}
21610 
21611 		if (last_frag) {
21612 			BUMP_MIB(&ip_mib, ipFragOKs);
21613 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21614 			    "ip_wput_frag_end:(%S)",
21615 			    "consumed hdr_mp");
21616 
21617 			if (first_ire != NULL)
21618 				ire_refrele(first_ire);
21619 			return;
21620 		}
21621 		/* Otherwise, advance and loop. */
21622 		offset += len;
21623 	}
21624 
21625 drop_pkt:
21626 	/* Clean up following allocation failure. */
21627 	BUMP_MIB(&ip_mib, ipOutDiscards);
21628 	freemsg(mp);
21629 	if (mp != hdr_mp)
21630 		freeb(hdr_mp);
21631 	if (mp != mp_orig)
21632 		freemsg(mp_orig);
21633 
21634 	if (save_ire != NULL)
21635 		IRE_REFRELE(save_ire);
21636 	if (first_ire != NULL)
21637 		ire_refrele(first_ire);
21638 
21639 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21640 	    "ip_wput_frag_end:(%S)",
21641 	    "end--alloc failure");
21642 }
21643 
21644 /*
21645  * Copy the header plus those options which have the copy bit set
21646  */
21647 static mblk_t *
21648 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset)
21649 {
21650 	mblk_t	*mp;
21651 	uchar_t	*up;
21652 
21653 	/*
21654 	 * Quick check if we need to look for options without the copy bit
21655 	 * set
21656 	 */
21657 	mp = allocb(ip_wroff_extra + hdr_len, BPRI_HI);
21658 	if (!mp)
21659 		return (mp);
21660 	mp->b_rptr += ip_wroff_extra;
21661 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
21662 		bcopy(rptr, mp->b_rptr, hdr_len);
21663 		mp->b_wptr += hdr_len + ip_wroff_extra;
21664 		return (mp);
21665 	}
21666 	up  = mp->b_rptr;
21667 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
21668 	up += IP_SIMPLE_HDR_LENGTH;
21669 	rptr += IP_SIMPLE_HDR_LENGTH;
21670 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
21671 	while (hdr_len > 0) {
21672 		uint32_t optval;
21673 		uint32_t optlen;
21674 
21675 		optval = *rptr;
21676 		if (optval == IPOPT_EOL)
21677 			break;
21678 		if (optval == IPOPT_NOP)
21679 			optlen = 1;
21680 		else
21681 			optlen = rptr[1];
21682 		if (optval & IPOPT_COPY) {
21683 			bcopy(rptr, up, optlen);
21684 			up += optlen;
21685 		}
21686 		rptr += optlen;
21687 		hdr_len -= optlen;
21688 	}
21689 	/*
21690 	 * Make sure that we drop an even number of words by filling
21691 	 * with EOL to the next word boundary.
21692 	 */
21693 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
21694 	    hdr_len & 0x3; hdr_len++)
21695 		*up++ = IPOPT_EOL;
21696 	mp->b_wptr = up;
21697 	/* Update header length */
21698 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
21699 	return (mp);
21700 }
21701 
21702 /*
21703  * Delivery to local recipients including fanout to multiple recipients.
21704  * Does not do checksumming of UDP/TCP.
21705  * Note: q should be the read side queue for either the ill or conn.
21706  * Note: rq should be the read side q for the lower (ill) stream.
21707  * We don't send packets to IPPF processing, thus the last argument
21708  * to all the fanout calls are B_FALSE.
21709  */
21710 void
21711 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
21712     int fanout_flags, zoneid_t zoneid)
21713 {
21714 	uint32_t	protocol;
21715 	mblk_t		*first_mp;
21716 	boolean_t	mctl_present;
21717 	int		ire_type;
21718 #define	rptr	((uchar_t *)ipha)
21719 
21720 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
21721 	    "ip_wput_local_start: q %p", q);
21722 
21723 	if (ire != NULL) {
21724 		ire_type = ire->ire_type;
21725 	} else {
21726 		/*
21727 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
21728 		 * packet is not multicast, we can't tell the ire type.
21729 		 */
21730 		ASSERT(CLASSD(ipha->ipha_dst));
21731 		ire_type = IRE_BROADCAST;
21732 	}
21733 
21734 	first_mp = mp;
21735 	if (first_mp->b_datap->db_type == M_CTL) {
21736 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
21737 		if (!io->ipsec_out_secure) {
21738 			/*
21739 			 * This ipsec_out_t was allocated in ip_wput
21740 			 * for multicast packets to store the ill_index.
21741 			 * As this is being delivered locally, we don't
21742 			 * need this anymore.
21743 			 */
21744 			mp = first_mp->b_cont;
21745 			freeb(first_mp);
21746 			first_mp = mp;
21747 			mctl_present = B_FALSE;
21748 		} else {
21749 			mctl_present = B_TRUE;
21750 			mp = first_mp->b_cont;
21751 			ASSERT(mp != NULL);
21752 			ipsec_out_to_in(first_mp);
21753 		}
21754 	} else {
21755 		mctl_present = B_FALSE;
21756 	}
21757 
21758 	loopback_packets++;
21759 
21760 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
21761 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
21762 	if (!IS_SIMPLE_IPH(ipha)) {
21763 		ip_wput_local_options(ipha);
21764 	}
21765 
21766 	protocol = ipha->ipha_protocol;
21767 	switch (protocol) {
21768 	case IPPROTO_ICMP: {
21769 		ire_t		*ire_zone;
21770 		ilm_t		*ilm;
21771 		mblk_t		*mp1;
21772 		zoneid_t	last_zoneid;
21773 
21774 		if (CLASSD(ipha->ipha_dst) &&
21775 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
21776 			ASSERT(ire_type == IRE_BROADCAST);
21777 			/*
21778 			 * In the multicast case, applications may have joined
21779 			 * the group from different zones, so we need to deliver
21780 			 * the packet to each of them. Loop through the
21781 			 * multicast memberships structures (ilm) on the receive
21782 			 * ill and send a copy of the packet up each matching
21783 			 * one. However, we don't do this for multicasts sent on
21784 			 * the loopback interface (PHYI_LOOPBACK flag set) as
21785 			 * they must stay in the sender's zone.
21786 			 *
21787 			 * ilm_add_v6() ensures that ilms in the same zone are
21788 			 * contiguous in the ill_ilm list. We use this property
21789 			 * to avoid sending duplicates needed when two
21790 			 * applications in the same zone join the same group on
21791 			 * different logical interfaces: we ignore the ilm if
21792 			 * its zoneid is the same as the last matching one.
21793 			 * In addition, the sending of the packet for
21794 			 * ire_zoneid is delayed until all of the other ilms
21795 			 * have been exhausted.
21796 			 */
21797 			last_zoneid = -1;
21798 			ILM_WALKER_HOLD(ill);
21799 			for (ilm = ill->ill_ilm; ilm != NULL;
21800 			    ilm = ilm->ilm_next) {
21801 				if ((ilm->ilm_flags & ILM_DELETED) ||
21802 				    ipha->ipha_dst != ilm->ilm_addr ||
21803 				    ilm->ilm_zoneid == last_zoneid ||
21804 				    ilm->ilm_zoneid == zoneid ||
21805 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
21806 					continue;
21807 				mp1 = ip_copymsg(first_mp);
21808 				if (mp1 == NULL)
21809 					continue;
21810 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
21811 				    mctl_present, B_FALSE, ill,
21812 				    ilm->ilm_zoneid);
21813 				last_zoneid = ilm->ilm_zoneid;
21814 			}
21815 			ILM_WALKER_RELE(ill);
21816 			/*
21817 			 * Loopback case: the sending endpoint has
21818 			 * IP_MULTICAST_LOOP disabled, therefore we don't
21819 			 * dispatch the multicast packet to the sending zone.
21820 			 */
21821 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
21822 				freemsg(first_mp);
21823 				return;
21824 			}
21825 		} else if (ire_type == IRE_BROADCAST) {
21826 			/*
21827 			 * In the broadcast case, there may be many zones
21828 			 * which need a copy of the packet delivered to them.
21829 			 * There is one IRE_BROADCAST per broadcast address
21830 			 * and per zone; we walk those using a helper function.
21831 			 * In addition, the sending of the packet for zoneid is
21832 			 * delayed until all of the other ires have been
21833 			 * processed.
21834 			 */
21835 			IRB_REFHOLD(ire->ire_bucket);
21836 			ire_zone = NULL;
21837 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
21838 			    ire)) != NULL) {
21839 				mp1 = ip_copymsg(first_mp);
21840 				if (mp1 == NULL)
21841 					continue;
21842 
21843 				UPDATE_IB_PKT_COUNT(ire_zone);
21844 				ire_zone->ire_last_used_time = lbolt;
21845 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
21846 				    mctl_present, B_FALSE, ill,
21847 				    ire_zone->ire_zoneid);
21848 			}
21849 			IRB_REFRELE(ire->ire_bucket);
21850 		}
21851 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
21852 		    0, mctl_present, B_FALSE, ill, zoneid);
21853 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
21854 		    "ip_wput_local_end: q %p (%S)",
21855 		    q, "icmp");
21856 		return;
21857 	}
21858 	case IPPROTO_IGMP:
21859 		if (igmp_input(q, mp, ill)) {
21860 			/* Bad packet - discarded by igmp_input */
21861 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
21862 			    "ip_wput_local_end: q %p (%S)",
21863 			    q, "igmp_input--bad packet");
21864 			if (mctl_present)
21865 				freeb(first_mp);
21866 			return;
21867 		}
21868 		/*
21869 		 * igmp_input() may have pulled up the message so ipha needs to
21870 		 * be reinitialized.
21871 		 */
21872 		ipha = (ipha_t *)mp->b_rptr;
21873 		/* deliver to local raw users */
21874 		break;
21875 	case IPPROTO_ENCAP:
21876 		/*
21877 		 * This case is covered by either ip_fanout_proto, or by
21878 		 * the above security processing for self-tunneled packets.
21879 		 */
21880 		break;
21881 	case IPPROTO_UDP: {
21882 		uint16_t	*up;
21883 		uint32_t	ports;
21884 
21885 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
21886 		    UDP_PORTS_OFFSET);
21887 		/* Force a 'valid' checksum. */
21888 		up[3] = 0;
21889 
21890 		ports = *(uint32_t *)up;
21891 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
21892 		    (ire_type == IRE_BROADCAST),
21893 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
21894 		    IP_FF_SEND_SLLA | IP_FF_IP6INFO, mctl_present, B_FALSE,
21895 		    ill, zoneid);
21896 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
21897 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
21898 		return;
21899 	}
21900 	case IPPROTO_TCP: {
21901 
21902 		/*
21903 		 * For TCP, discard broadcast packets.
21904 		 */
21905 		if ((ushort_t)ire_type == IRE_BROADCAST) {
21906 			freemsg(first_mp);
21907 			BUMP_MIB(&ip_mib, ipInDiscards);
21908 			return;
21909 		}
21910 
21911 		if (mp->b_datap->db_type == M_DATA) {
21912 			/*
21913 			 * M_DATA mblk, so init mblk (chain) for no struio().
21914 			 */
21915 			mblk_t	*mp1 = mp;
21916 
21917 			do
21918 				mp1->b_datap->db_struioflag = 0;
21919 			while ((mp1 = mp1->b_cont) != NULL);
21920 		}
21921 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
21922 		    <= mp->b_wptr);
21923 		ip_fanout_tcp(q, first_mp, ill, ipha,
21924 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
21925 		    IP_FF_SYN_ADDIRE | IP_FF_IP6INFO,
21926 		    mctl_present, B_FALSE, zoneid);
21927 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
21928 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
21929 		return;
21930 	}
21931 	case IPPROTO_SCTP:
21932 	{
21933 		uint32_t	ports;
21934 
21935 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
21936 		ip_fanout_sctp(first_mp, ill, ipha, ports,
21937 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
21938 		    IP_FF_IP6INFO,
21939 		    mctl_present, B_FALSE, 0, zoneid);
21940 		return;
21941 	}
21942 
21943 	default:
21944 		break;
21945 	}
21946 	/*
21947 	 * Find a client for some other protocol.  We give
21948 	 * copies to multiple clients, if more than one is
21949 	 * bound.
21950 	 */
21951 	ip_fanout_proto(q, first_mp, ill, ipha,
21952 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
21953 	    mctl_present, B_FALSE, ill, zoneid);
21954 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
21955 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
21956 #undef	rptr
21957 }
21958 
21959 /*
21960  * Update any source route, record route, or timestamp options.
21961  * Check that we are at end of strict source route.
21962  * The options have been sanity checked by ip_wput_options().
21963  */
21964 static void
21965 ip_wput_local_options(ipha_t *ipha)
21966 {
21967 	ipoptp_t	opts;
21968 	uchar_t		*opt;
21969 	uint8_t		optval;
21970 	uint8_t		optlen;
21971 	ipaddr_t	dst;
21972 	uint32_t	ts;
21973 	ire_t		*ire;
21974 	timestruc_t	now;
21975 
21976 	ip2dbg(("ip_wput_local_options\n"));
21977 	for (optval = ipoptp_first(&opts, ipha);
21978 	    optval != IPOPT_EOL;
21979 	    optval = ipoptp_next(&opts)) {
21980 		opt = opts.ipoptp_cur;
21981 		optlen = opts.ipoptp_len;
21982 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21983 		switch (optval) {
21984 			uint32_t off;
21985 		case IPOPT_SSRR:
21986 		case IPOPT_LSRR:
21987 			off = opt[IPOPT_OFFSET];
21988 			off--;
21989 			if (optlen < IP_ADDR_LEN ||
21990 			    off > optlen - IP_ADDR_LEN) {
21991 				/* End of source route */
21992 				break;
21993 			}
21994 			/*
21995 			 * This will only happen if two consecutive entries
21996 			 * in the source route contains our address or if
21997 			 * it is a packet with a loose source route which
21998 			 * reaches us before consuming the whole source route
21999 			 */
22000 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
22001 			if (optval == IPOPT_SSRR) {
22002 				return;
22003 			}
22004 			/*
22005 			 * Hack: instead of dropping the packet truncate the
22006 			 * source route to what has been used by filling the
22007 			 * rest with IPOPT_NOP.
22008 			 */
22009 			opt[IPOPT_OLEN] = (uint8_t)off;
22010 			while (off < optlen) {
22011 				opt[off++] = IPOPT_NOP;
22012 			}
22013 			break;
22014 		case IPOPT_RR:
22015 			off = opt[IPOPT_OFFSET];
22016 			off--;
22017 			if (optlen < IP_ADDR_LEN ||
22018 			    off > optlen - IP_ADDR_LEN) {
22019 				/* No more room - ignore */
22020 				ip1dbg((
22021 				    "ip_wput_forward_options: end of RR\n"));
22022 				break;
22023 			}
22024 			dst = htonl(INADDR_LOOPBACK);
22025 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
22026 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
22027 			break;
22028 		case IPOPT_TS:
22029 			/* Insert timestamp if there is romm */
22030 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
22031 			case IPOPT_TS_TSONLY:
22032 				off = IPOPT_TS_TIMELEN;
22033 				break;
22034 			case IPOPT_TS_PRESPEC:
22035 			case IPOPT_TS_PRESPEC_RFC791:
22036 				/* Verify that the address matched */
22037 				off = opt[IPOPT_OFFSET] - 1;
22038 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
22039 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
22040 				    NULL, ALL_ZONES, MATCH_IRE_TYPE);
22041 				if (ire == NULL) {
22042 					/* Not for us */
22043 					break;
22044 				}
22045 				ire_refrele(ire);
22046 				/* FALLTHRU */
22047 			case IPOPT_TS_TSANDADDR:
22048 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
22049 				break;
22050 			default:
22051 				/*
22052 				 * ip_*put_options should have already
22053 				 * dropped this packet.
22054 				 */
22055 				cmn_err(CE_PANIC, "ip_wput_local_options: "
22056 				    "unknown IT - bug in ip_wput_options?\n");
22057 				return;	/* Keep "lint" happy */
22058 			}
22059 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
22060 				/* Increase overflow counter */
22061 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
22062 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
22063 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
22064 				    (off << 4);
22065 				break;
22066 			}
22067 			off = opt[IPOPT_OFFSET] - 1;
22068 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
22069 			case IPOPT_TS_PRESPEC:
22070 			case IPOPT_TS_PRESPEC_RFC791:
22071 			case IPOPT_TS_TSANDADDR:
22072 				dst = htonl(INADDR_LOOPBACK);
22073 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
22074 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
22075 				/* FALLTHRU */
22076 			case IPOPT_TS_TSONLY:
22077 				off = opt[IPOPT_OFFSET] - 1;
22078 				/* Compute # of milliseconds since midnight */
22079 				gethrestime(&now);
22080 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
22081 				    now.tv_nsec / (NANOSEC / MILLISEC);
22082 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
22083 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
22084 				break;
22085 			}
22086 			break;
22087 		}
22088 	}
22089 }
22090 
22091 /*
22092  * Send out a multicast packet on interface ipif.
22093  * The sender does not have an conn.
22094  * Caller verifies that this isn't a PHYI_LOOPBACK.
22095  */
22096 void
22097 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif)
22098 {
22099 	ipha_t	*ipha;
22100 	ire_t	*ire;
22101 	ipaddr_t	dst;
22102 	mblk_t		*first_mp;
22103 
22104 	/* igmp_sendpkt always allocates a ipsec_out_t */
22105 	ASSERT(mp->b_datap->db_type == M_CTL);
22106 	ASSERT(!ipif->ipif_isv6);
22107 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
22108 
22109 	first_mp = mp;
22110 	mp = first_mp->b_cont;
22111 	ASSERT(mp->b_datap->db_type == M_DATA);
22112 	ipha = (ipha_t *)mp->b_rptr;
22113 
22114 	/*
22115 	 * Find an IRE which matches the destination and the outgoing
22116 	 * queue (i.e. the outgoing interface.)
22117 	 */
22118 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
22119 		dst = ipif->ipif_pp_dst_addr;
22120 	else
22121 		dst = ipha->ipha_dst;
22122 	/*
22123 	 * The source address has already been initialized by the
22124 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
22125 	 * be sufficient rather than MATCH_IRE_IPIF.
22126 	 *
22127 	 * This function is used for sending IGMP packets. We need
22128 	 * to make sure that we send the packet out of the interface
22129 	 * (ipif->ipif_ill) where we joined the group. This is to
22130 	 * prevent from switches doing IGMP snooping to send us multicast
22131 	 * packets for a given group on the interface we have joined.
22132 	 * If we can't find an ire, igmp_sendpkt has already initialized
22133 	 * ipsec_out_attach_if so that this will not be load spread in
22134 	 * ip_newroute_ipif.
22135 	 */
22136 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MATCH_IRE_ILL);
22137 	if (!ire) {
22138 		/*
22139 		 * Mark this packet to make it be delivered to
22140 		 * ip_wput_ire after the new ire has been
22141 		 * created.
22142 		 */
22143 		mp->b_prev = NULL;
22144 		mp->b_next = NULL;
22145 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC);
22146 		return;
22147 	}
22148 
22149 	/*
22150 	 * Honor the RTF_SETSRC flag; this is the only case
22151 	 * where we force this addr whatever the current src addr is,
22152 	 * because this address is set by igmp_sendpkt(), and
22153 	 * cannot be specified by any user.
22154 	 */
22155 	if (ire->ire_flags & RTF_SETSRC) {
22156 		ipha->ipha_src = ire->ire_src_addr;
22157 	}
22158 
22159 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE);
22160 }
22161 
22162 /*
22163  * NOTE : This function does not ire_refrele the ire argument passed in.
22164  *
22165  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
22166  * failure. The ire_fp_mp can vanish any time in the case of IRE_MIPRTUN
22167  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
22168  * the ire_lock to access the ire_fp_mp in this case.
22169  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
22170  * prepending a fastpath message IPQoS processing must precede it, we also set
22171  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
22172  * (IPQoS might have set the b_band for CoS marking).
22173  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
22174  * must follow it so that IPQoS can mark the dl_priority field for CoS
22175  * marking, if needed.
22176  */
22177 static mblk_t *
22178 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
22179 {
22180 	uint_t	hlen;
22181 	ipha_t *ipha;
22182 	mblk_t *mp1;
22183 	boolean_t qos_done = B_FALSE;
22184 	uchar_t	*ll_hdr;
22185 
22186 #define	rptr	((uchar_t *)ipha)
22187 
22188 	ipha = (ipha_t *)mp->b_rptr;
22189 	hlen = 0;
22190 	LOCK_IRE_FP_MP(ire);
22191 	if ((mp1 = ire->ire_fp_mp) != NULL) {
22192 		ASSERT(DB_TYPE(mp1) == M_DATA);
22193 		/* Initiate IPPF processing */
22194 		if ((proc != 0) && IPP_ENABLED(proc)) {
22195 			UNLOCK_IRE_FP_MP(ire);
22196 			ip_process(proc, &mp, ill_index);
22197 			if (mp == NULL)
22198 				return (NULL);
22199 
22200 			ipha = (ipha_t *)mp->b_rptr;
22201 			LOCK_IRE_FP_MP(ire);
22202 			if ((mp1 = ire->ire_fp_mp) == NULL) {
22203 				qos_done = B_TRUE;
22204 				goto no_fp_mp;
22205 			}
22206 			ASSERT(DB_TYPE(mp1) == M_DATA);
22207 		}
22208 		hlen = MBLKL(mp1);
22209 		/*
22210 		 * Check if we have enough room to prepend fastpath
22211 		 * header
22212 		 */
22213 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
22214 			ll_hdr = rptr - hlen;
22215 			bcopy(mp1->b_rptr, ll_hdr, hlen);
22216 			/* XXX ipha is not aligned here */
22217 			ipha = (ipha_t *)(rptr - hlen);
22218 			/*
22219 			 * Set the b_rptr to the start of the link layer
22220 			 * header
22221 			 */
22222 			mp->b_rptr = rptr;
22223 			mp1 = mp;
22224 		} else {
22225 			mp1 = copyb(mp1);
22226 			if (mp1 == NULL)
22227 				goto unlock_err;
22228 			mp1->b_band = mp->b_band;
22229 			mp1->b_cont = mp;
22230 			/*
22231 			 * XXX disable ICK_VALID and compute checksum
22232 			 * here; can happen if ire_fp_mp changes and
22233 			 * it can't be copied now due to insufficient
22234 			 * space. (unlikely, fp mp can change, but it
22235 			 * does not increase in length)
22236 			 */
22237 		}
22238 		UNLOCK_IRE_FP_MP(ire);
22239 	} else {
22240 no_fp_mp:
22241 		mp1 = copyb(ire->ire_dlureq_mp);
22242 		if (mp1 == NULL) {
22243 unlock_err:
22244 			UNLOCK_IRE_FP_MP(ire);
22245 			freemsg(mp);
22246 			return (NULL);
22247 		}
22248 		UNLOCK_IRE_FP_MP(ire);
22249 		mp1->b_cont = mp;
22250 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc)) {
22251 			ip_process(proc, &mp1, ill_index);
22252 			if (mp1 == NULL)
22253 				return (NULL);
22254 		}
22255 	}
22256 	return (mp1);
22257 #undef rptr
22258 }
22259 
22260 /*
22261  * Finish the outbound IPsec processing for an IPv6 packet. This function
22262  * is called from ipsec_out_process() if the IPsec packet was processed
22263  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
22264  * asynchronously.
22265  */
22266 void
22267 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
22268     ire_t *ire_arg)
22269 {
22270 	in6_addr_t *v6dstp;
22271 	ire_t *ire;
22272 	mblk_t *mp;
22273 	uint_t	ill_index;
22274 	ipsec_out_t *io;
22275 	boolean_t attach_if, hwaccel;
22276 	uint32_t flags = IP6_NO_IPPOLICY;
22277 	int match_flags;
22278 	zoneid_t zoneid;
22279 	boolean_t ill_need_rele = B_FALSE;
22280 	boolean_t ire_need_rele = B_FALSE;
22281 
22282 	mp = ipsec_mp->b_cont;
22283 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
22284 	ill_index = io->ipsec_out_ill_index;
22285 	if (io->ipsec_out_reachable) {
22286 		flags |= IPV6_REACHABILITY_CONFIRMATION;
22287 	}
22288 	attach_if = io->ipsec_out_attach_if;
22289 	hwaccel = io->ipsec_out_accelerated;
22290 	zoneid = io->ipsec_out_zoneid;
22291 	ASSERT(zoneid != ALL_ZONES);
22292 	match_flags = MATCH_IRE_ILL_GROUP;
22293 	/* Multicast addresses should have non-zero ill_index. */
22294 	v6dstp = &ip6h->ip6_dst;
22295 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
22296 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
22297 	ASSERT(!attach_if || ill_index != 0);
22298 	if (ill_index != 0) {
22299 		if (ill == NULL) {
22300 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
22301 			    B_TRUE);
22302 
22303 			/* Failure case frees things for us. */
22304 			if (ill == NULL)
22305 				return;
22306 
22307 			ill_need_rele = B_TRUE;
22308 		}
22309 		/*
22310 		 * If this packet needs to go out on a particular interface
22311 		 * honor it.
22312 		 */
22313 		if (attach_if) {
22314 			match_flags = MATCH_IRE_ILL;
22315 
22316 			/*
22317 			 * Check if we need an ire that will not be
22318 			 * looked up by anybody else i.e. HIDDEN.
22319 			 */
22320 			if (ill_is_probeonly(ill)) {
22321 				match_flags |= MATCH_IRE_MARK_HIDDEN;
22322 			}
22323 		}
22324 	}
22325 	ASSERT(mp != NULL);
22326 
22327 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
22328 		boolean_t unspec_src;
22329 		ipif_t	*ipif;
22330 
22331 		/*
22332 		 * Use the ill_index to get the right ill.
22333 		 */
22334 		unspec_src = io->ipsec_out_unspec_src;
22335 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
22336 		if (ipif == NULL) {
22337 			if (ill_need_rele)
22338 				ill_refrele(ill);
22339 			freemsg(ipsec_mp);
22340 			return;
22341 		}
22342 
22343 		if (ire_arg != NULL) {
22344 			ire = ire_arg;
22345 		} else {
22346 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
22347 			    zoneid, match_flags);
22348 			ire_need_rele = B_TRUE;
22349 		}
22350 		if (ire != NULL) {
22351 			ipif_refrele(ipif);
22352 			/*
22353 			 * XXX Do the multicast forwarding now, as the IPSEC
22354 			 * processing has been done.
22355 			 */
22356 			goto send;
22357 		}
22358 
22359 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
22360 		mp->b_prev = NULL;
22361 		mp->b_next = NULL;
22362 
22363 		/*
22364 		 * If the IPsec packet was processed asynchronously,
22365 		 * drop it now.
22366 		 */
22367 		if (q == NULL) {
22368 			if (ill_need_rele)
22369 				ill_refrele(ill);
22370 			freemsg(ipsec_mp);
22371 			return;
22372 		}
22373 
22374 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
22375 		    unspec_src, zoneid);
22376 		ipif_refrele(ipif);
22377 	} else {
22378 		if (attach_if) {
22379 			ipif_t	*ipif;
22380 
22381 			ipif = ipif_get_next_ipif(NULL, ill);
22382 			if (ipif == NULL) {
22383 				if (ill_need_rele)
22384 					ill_refrele(ill);
22385 				freemsg(ipsec_mp);
22386 				return;
22387 			}
22388 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
22389 			    zoneid, match_flags);
22390 			ire_need_rele = B_TRUE;
22391 			ipif_refrele(ipif);
22392 		} else {
22393 			if (ire_arg != NULL) {
22394 				ire = ire_arg;
22395 			} else {
22396 				ire = ire_cache_lookup_v6(v6dstp, zoneid);
22397 				ire_need_rele = B_TRUE;
22398 			}
22399 		}
22400 		if (ire != NULL)
22401 			goto send;
22402 		/*
22403 		 * ire disappeared underneath.
22404 		 *
22405 		 * What we need to do here is the ip_newroute
22406 		 * logic to get the ire without doing the IPSEC
22407 		 * processing. Follow the same old path. But this
22408 		 * time, ip_wput or ire_add_then_send will call us
22409 		 * directly as all the IPSEC operations are done.
22410 		 */
22411 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
22412 		mp->b_prev = NULL;
22413 		mp->b_next = NULL;
22414 
22415 		/*
22416 		 * If the IPsec packet was processed asynchronously,
22417 		 * drop it now.
22418 		 */
22419 		if (q == NULL) {
22420 			if (ill_need_rele)
22421 				ill_refrele(ill);
22422 			freemsg(ipsec_mp);
22423 			return;
22424 		}
22425 
22426 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
22427 		    zoneid);
22428 	}
22429 	if (ill != NULL && ill_need_rele)
22430 		ill_refrele(ill);
22431 	return;
22432 send:
22433 	if (ill != NULL && ill_need_rele)
22434 		ill_refrele(ill);
22435 
22436 	/* Local delivery */
22437 	if (ire->ire_stq == NULL) {
22438 		ASSERT(q != NULL);
22439 		ip_wput_local_v6(RD(q), ire->ire_ipif->ipif_ill, ip6h, ipsec_mp,
22440 		    ire, 0);
22441 		if (ire_need_rele)
22442 			ire_refrele(ire);
22443 		return;
22444 	}
22445 	/*
22446 	 * Everything is done. Send it out on the wire.
22447 	 * We force the insertion of a fragment header using the
22448 	 * IPH_FRAG_HDR flag in two cases:
22449 	 * - after reception of an ICMPv6 "packet too big" message
22450 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
22451 	 * - for multirouted IPv6 packets, so that the receiver can
22452 	 *   discard duplicates according to their fragment identifier
22453 	 */
22454 	/* XXX fix flow control problems. */
22455 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
22456 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
22457 		if (hwaccel) {
22458 			/*
22459 			 * hardware acceleration does not handle these
22460 			 * "slow path" cases.
22461 			 */
22462 			/* IPsec KSTATS: should bump bean counter here. */
22463 			if (ire_need_rele)
22464 				ire_refrele(ire);
22465 			freemsg(ipsec_mp);
22466 			return;
22467 		}
22468 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
22469 		    (mp->b_cont ? msgdsize(mp) :
22470 		    mp->b_wptr - (uchar_t *)ip6h)) {
22471 			/* IPsec KSTATS: should bump bean counter here. */
22472 			ip0dbg(("Packet length mismatch: %d, %ld\n",
22473 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
22474 			    msgdsize(mp)));
22475 			if (ire_need_rele)
22476 				ire_refrele(ire);
22477 			freemsg(ipsec_mp);
22478 			return;
22479 		}
22480 		ASSERT(mp->b_prev == NULL);
22481 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
22482 		    ntohs(ip6h->ip6_plen) +
22483 		    IPV6_HDR_LEN, ire->ire_max_frag));
22484 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
22485 		    ire->ire_max_frag);
22486 	} else {
22487 		UPDATE_OB_PKT_COUNT(ire);
22488 		ire->ire_last_used_time = lbolt;
22489 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
22490 	}
22491 	if (ire_need_rele)
22492 		ire_refrele(ire);
22493 	freeb(ipsec_mp);
22494 }
22495 
22496 void
22497 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
22498 {
22499 /* EXPORT DELETE START */
22500 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
22501 	da_ipsec_t *hada;	/* data attributes */
22502 	ill_t *ill = (ill_t *)q->q_ptr;
22503 
22504 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
22505 
22506 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
22507 		/* IPsec KSTATS: Bump lose counter here! */
22508 /* EXPORT DELETE END */
22509 		freemsg(mp);
22510 /* EXPORT DELETE START */
22511 		return;
22512 	}
22513 
22514 	/*
22515 	 * It's an IPsec packet that must be
22516 	 * accelerated by the Provider, and the
22517 	 * outbound ill is IPsec acceleration capable.
22518 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
22519 	 * to the ill.
22520 	 * IPsec KSTATS: should bump packet counter here.
22521 	 */
22522 
22523 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
22524 	if (hada_mp == NULL) {
22525 		/* IPsec KSTATS: should bump packet counter here. */
22526 		freemsg(mp);
22527 		return;
22528 	}
22529 
22530 	hada_mp->b_datap->db_type = M_CTL;
22531 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
22532 	hada_mp->b_cont = mp;
22533 
22534 	hada = (da_ipsec_t *)hada_mp->b_rptr;
22535 	bzero(hada, sizeof (da_ipsec_t));
22536 	hada->da_type = IPHADA_M_CTL;
22537 
22538 	putnext(q, hada_mp);
22539 /* EXPORT DELETE END */
22540 }
22541 
22542 /*
22543  * Finish the outbound IPsec processing. This function is called from
22544  * ipsec_out_process() if the IPsec packet was processed
22545  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
22546  * asynchronously.
22547  */
22548 void
22549 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
22550     ire_t *ire_arg)
22551 {
22552 	uint32_t v_hlen_tos_len;
22553 	ipaddr_t	dst;
22554 	ipif_t	*ipif = NULL;
22555 	ire_t *ire;
22556 	ire_t *ire1 = NULL;
22557 	mblk_t *next_mp = NULL;
22558 	uint32_t max_frag;
22559 	boolean_t multirt_send = B_FALSE;
22560 	mblk_t *mp;
22561 	mblk_t *mp1;
22562 	uint_t	ill_index;
22563 	ipsec_out_t *io;
22564 	boolean_t attach_if;
22565 	int match_flags, offset;
22566 	irb_t *irb = NULL;
22567 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
22568 	zoneid_t zoneid;
22569 	uint32_t cksum;
22570 	uint16_t *up;
22571 	/* Hack until the UDP merge into IP happens. */
22572 	extern boolean_t udp_compute_checksum(void);
22573 #ifdef	_BIG_ENDIAN
22574 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22575 #else
22576 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22577 #endif
22578 
22579 	mp = ipsec_mp->b_cont;
22580 	ASSERT(mp != NULL);
22581 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22582 	dst = ipha->ipha_dst;
22583 
22584 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
22585 	ill_index = io->ipsec_out_ill_index;
22586 	attach_if = io->ipsec_out_attach_if;
22587 	zoneid = io->ipsec_out_zoneid;
22588 	ASSERT(zoneid != ALL_ZONES);
22589 	match_flags = MATCH_IRE_ILL_GROUP;
22590 	if (ill_index != 0) {
22591 		if (ill == NULL) {
22592 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
22593 			    ill_index, B_FALSE);
22594 
22595 			/* Failure case frees things for us. */
22596 			if (ill == NULL)
22597 				return;
22598 
22599 			ill_need_rele = B_TRUE;
22600 		}
22601 		/*
22602 		 * If this packet needs to go out on a particular interface
22603 		 * honor it.
22604 		 */
22605 		if (attach_if) {
22606 			match_flags = MATCH_IRE_ILL;
22607 
22608 			/*
22609 			 * Check if we need an ire that will not be
22610 			 * looked up by anybody else i.e. HIDDEN.
22611 			 */
22612 			if (ill_is_probeonly(ill)) {
22613 				match_flags |= MATCH_IRE_MARK_HIDDEN;
22614 			}
22615 		}
22616 	}
22617 
22618 	if (CLASSD(dst)) {
22619 		boolean_t conn_dontroute;
22620 		/*
22621 		 * Use the ill_index to get the right ipif.
22622 		 */
22623 		conn_dontroute = io->ipsec_out_dontroute;
22624 		if (ill_index == 0)
22625 			ipif = ipif_lookup_group(dst, zoneid);
22626 		else
22627 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
22628 		if (ipif == NULL) {
22629 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
22630 			    " multicast\n"));
22631 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
22632 			freemsg(ipsec_mp);
22633 			goto done;
22634 		}
22635 		/*
22636 		 * ipha_src has already been intialized with the
22637 		 * value of the ipif in ip_wput. All we need now is
22638 		 * an ire to send this downstream.
22639 		 */
22640 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, match_flags);
22641 		if (ire != NULL) {
22642 			ill_t *ill1;
22643 			/*
22644 			 * Do the multicast forwarding now, as the IPSEC
22645 			 * processing has been done.
22646 			 */
22647 			if (ip_g_mrouter && !conn_dontroute &&
22648 			    (ill1 = ire_to_ill(ire))) {
22649 				if (ip_mforward(ill1, ipha, mp)) {
22650 					freemsg(ipsec_mp);
22651 					ip1dbg(("ip_wput_ipsec_out: mforward "
22652 					    "failed\n"));
22653 					ire_refrele(ire);
22654 					goto done;
22655 				}
22656 			}
22657 			goto send;
22658 		}
22659 
22660 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
22661 		mp->b_prev = NULL;
22662 		mp->b_next = NULL;
22663 
22664 		/*
22665 		 * If the IPsec packet was processed asynchronously,
22666 		 * drop it now.
22667 		 */
22668 		if (q == NULL) {
22669 			freemsg(ipsec_mp);
22670 			goto done;
22671 		}
22672 
22673 		/*
22674 		 * We may be using a wrong ipif to create the ire.
22675 		 * But it is okay as the source address is assigned
22676 		 * for the packet already. Next outbound packet would
22677 		 * create the IRE with the right IPIF in ip_wput.
22678 		 *
22679 		 * Also handle RTF_MULTIRT routes.
22680 		 */
22681 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT);
22682 	} else {
22683 		if (attach_if) {
22684 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
22685 			    zoneid, match_flags);
22686 		} else {
22687 			if (ire_arg != NULL) {
22688 				ire = ire_arg;
22689 				ire_need_rele = B_FALSE;
22690 			} else {
22691 				ire = ire_cache_lookup(dst, zoneid);
22692 			}
22693 		}
22694 		if (ire != NULL) {
22695 			goto send;
22696 		}
22697 
22698 		/*
22699 		 * ire disappeared underneath.
22700 		 *
22701 		 * What we need to do here is the ip_newroute
22702 		 * logic to get the ire without doing the IPSEC
22703 		 * processing. Follow the same old path. But this
22704 		 * time, ip_wput or ire_add_then_put will call us
22705 		 * directly as all the IPSEC operations are done.
22706 		 */
22707 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
22708 		mp->b_prev = NULL;
22709 		mp->b_next = NULL;
22710 
22711 		/*
22712 		 * If the IPsec packet was processed asynchronously,
22713 		 * drop it now.
22714 		 */
22715 		if (q == NULL) {
22716 			freemsg(ipsec_mp);
22717 			goto done;
22718 		}
22719 
22720 		/*
22721 		 * Since we're going through ip_newroute() again, we
22722 		 * need to make sure we don't:
22723 		 *
22724 		 *	1.) Trigger the ASSERT() with the ipha_ident
22725 		 *	    overloading.
22726 		 *	2.) Redo transport-layer checksumming, since we've
22727 		 *	    already done all that to get this far.
22728 		 *
22729 		 * The easiest way not do either of the above is to set
22730 		 * the ipha_ident field to IP_HDR_INCLUDED.
22731 		 */
22732 		ipha->ipha_ident = IP_HDR_INCLUDED;
22733 		ip_newroute(q, ipsec_mp, dst, NULL,
22734 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL));
22735 	}
22736 	goto done;
22737 send:
22738 	if (ipha->ipha_protocol == IPPROTO_UDP && udp_compute_checksum()) {
22739 		/*
22740 		 * ESP NAT-Traversal packet.
22741 		 *
22742 		 * Just do software checksum for now.
22743 		 */
22744 
22745 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
22746 		IP_STAT(ip_out_sw_cksum);
22747 #define	iphs	((uint16_t *)ipha)
22748 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
22749 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
22750 		    IP_SIMPLE_HDR_LENGTH);
22751 #undef iphs
22752 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
22753 			cksum = 0xFFFF;
22754 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
22755 			if (mp1->b_wptr - mp1->b_rptr >=
22756 			    offset + sizeof (uint16_t)) {
22757 				up = (uint16_t *)(mp1->b_rptr + offset);
22758 				*up = cksum;
22759 				break;	/* out of for loop */
22760 			} else {
22761 				offset -= (mp->b_wptr - mp->b_rptr);
22762 			}
22763 	} /* Otherwise, just keep the all-zero checksum. */
22764 
22765 	if (ire->ire_stq == NULL) {
22766 		/*
22767 		 * Loopbacks go through ip_wput_local except for one case.
22768 		 * We come here if we generate a icmp_frag_needed message
22769 		 * after IPSEC processing is over. When this function calls
22770 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
22771 		 * icmp_frag_needed. The message generated comes back here
22772 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
22773 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
22774 		 * source address as it is usually set in ip_wput_ire. As
22775 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
22776 		 * and we end up here. We can't enter ip_wput_ire once the
22777 		 * IPSEC processing is over and hence we need to do it here.
22778 		 */
22779 		ASSERT(q != NULL);
22780 		UPDATE_OB_PKT_COUNT(ire);
22781 		ire->ire_last_used_time = lbolt;
22782 		if (ipha->ipha_src == 0)
22783 			ipha->ipha_src = ire->ire_src_addr;
22784 		ip_wput_local(RD(q), ire->ire_ipif->ipif_ill, ipha, ipsec_mp,
22785 		    ire, 0, zoneid);
22786 		if (ire_need_rele)
22787 			ire_refrele(ire);
22788 		goto done;
22789 	}
22790 
22791 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
22792 		/*
22793 		 * We are through with IPSEC processing.
22794 		 * Fragment this and send it on the wire.
22795 		 */
22796 		if (io->ipsec_out_accelerated) {
22797 			/*
22798 			 * The packet has been accelerated but must
22799 			 * be fragmented. This should not happen
22800 			 * since AH and ESP must not accelerate
22801 			 * packets that need fragmentation, however
22802 			 * the configuration could have changed
22803 			 * since the AH or ESP processing.
22804 			 * Drop packet.
22805 			 * IPsec KSTATS: bump bean counter here.
22806 			 */
22807 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
22808 			    "fragmented accelerated packet!\n"));
22809 			freemsg(ipsec_mp);
22810 		} else {
22811 			ip_wput_ire_fragmentit(ipsec_mp, ire);
22812 		}
22813 		if (ire_need_rele)
22814 			ire_refrele(ire);
22815 		goto done;
22816 	}
22817 
22818 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
22819 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
22820 	    (void *)ire->ire_ipif, (void *)ipif));
22821 
22822 	/*
22823 	 * Multiroute the secured packet, unless IPsec really
22824 	 * requires the packet to go out only through a particular
22825 	 * interface.
22826 	 */
22827 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
22828 		ire_t *first_ire;
22829 		irb = ire->ire_bucket;
22830 		ASSERT(irb != NULL);
22831 		/*
22832 		 * This ire has been looked up as the one that
22833 		 * goes through the given ipif;
22834 		 * make sure we do not omit any other multiroute ire
22835 		 * that may be present in the bucket before this one.
22836 		 */
22837 		IRB_REFHOLD(irb);
22838 		for (first_ire = irb->irb_ire;
22839 		    first_ire != NULL;
22840 		    first_ire = first_ire->ire_next) {
22841 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22842 			    (first_ire->ire_addr == ire->ire_addr) &&
22843 			    !(first_ire->ire_marks &
22844 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
22845 				break;
22846 		}
22847 
22848 		if ((first_ire != NULL) && (first_ire != ire)) {
22849 			/*
22850 			 * Don't change the ire if the packet must
22851 			 * be fragmented if sent via this new one.
22852 			 */
22853 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
22854 				IRE_REFHOLD(first_ire);
22855 				if (ire_need_rele)
22856 					ire_refrele(ire);
22857 				else
22858 					ire_need_rele = B_TRUE;
22859 				ire = first_ire;
22860 			}
22861 		}
22862 		IRB_REFRELE(irb);
22863 
22864 		multirt_send = B_TRUE;
22865 		max_frag = ire->ire_max_frag;
22866 	} else {
22867 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
22868 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
22869 			    "flag, attach_if %d\n", attach_if));
22870 		}
22871 	}
22872 
22873 	/*
22874 	 * In most cases, the emission loop below is entered only once.
22875 	 * Only in the case where the ire holds the RTF_MULTIRT
22876 	 * flag, we loop to process all RTF_MULTIRT ires in the
22877 	 * bucket, and send the packet through all crossed
22878 	 * RTF_MULTIRT routes.
22879 	 */
22880 	do {
22881 		if (multirt_send) {
22882 			/*
22883 			 * ire1 holds here the next ire to process in the
22884 			 * bucket. If multirouting is expected,
22885 			 * any non-RTF_MULTIRT ire that has the
22886 			 * right destination address is ignored.
22887 			 */
22888 			ASSERT(irb != NULL);
22889 			IRB_REFHOLD(irb);
22890 			for (ire1 = ire->ire_next;
22891 			    ire1 != NULL;
22892 			    ire1 = ire1->ire_next) {
22893 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22894 					continue;
22895 				if (ire1->ire_addr != ire->ire_addr)
22896 					continue;
22897 				if (ire1->ire_marks &
22898 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22899 					continue;
22900 				/* No loopback here */
22901 				if (ire1->ire_stq == NULL)
22902 					continue;
22903 				/*
22904 				 * Ensure we do not exceed the MTU
22905 				 * of the next route.
22906 				 */
22907 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
22908 					ip_multirt_bad_mtu(ire1, max_frag);
22909 					continue;
22910 				}
22911 
22912 				IRE_REFHOLD(ire1);
22913 				break;
22914 			}
22915 			IRB_REFRELE(irb);
22916 			if (ire1 != NULL) {
22917 				/*
22918 				 * We are in a multiple send case, need to
22919 				 * make a copy of the packet.
22920 				 */
22921 				next_mp = copymsg(ipsec_mp);
22922 				if (next_mp == NULL) {
22923 					ire_refrele(ire1);
22924 					ire1 = NULL;
22925 				}
22926 			}
22927 		}
22928 
22929 		/* Everything is done. Send it out on the wire */
22930 		mp1 = ip_wput_attach_llhdr(mp, ire, 0, 0);
22931 		if (mp1 == NULL) {
22932 			BUMP_MIB(&ip_mib, ipOutDiscards);
22933 			freemsg(ipsec_mp);
22934 			if (ire_need_rele)
22935 				ire_refrele(ire);
22936 			if (ire1 != NULL) {
22937 				ire_refrele(ire1);
22938 				freemsg(next_mp);
22939 			}
22940 			goto done;
22941 		}
22942 		UPDATE_OB_PKT_COUNT(ire);
22943 		ire->ire_last_used_time = lbolt;
22944 		if (!io->ipsec_out_accelerated) {
22945 			putnext(ire->ire_stq, mp1);
22946 		} else {
22947 			/*
22948 			 * Safety Pup says: make sure this is going to
22949 			 * the right interface!
22950 			 */
22951 			ill_t *ill1 = (ill_t *)ire->ire_stq->q_ptr;
22952 			int ifindex = ill1->ill_phyint->phyint_ifindex;
22953 
22954 			if (ifindex != io->ipsec_out_capab_ill_index) {
22955 				/* IPsec kstats: bump lose counter */
22956 				freemsg(mp1);
22957 			} else {
22958 				ipsec_hw_putnext(ire->ire_stq, mp1);
22959 			}
22960 		}
22961 
22962 		freeb(ipsec_mp);
22963 		if (ire_need_rele)
22964 			ire_refrele(ire);
22965 
22966 		if (ire1 != NULL) {
22967 			ire = ire1;
22968 			ire_need_rele = B_TRUE;
22969 			ASSERT(next_mp);
22970 			ipsec_mp = next_mp;
22971 			mp = ipsec_mp->b_cont;
22972 			ire1 = NULL;
22973 			next_mp = NULL;
22974 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
22975 		} else {
22976 			multirt_send = B_FALSE;
22977 		}
22978 	} while (multirt_send);
22979 done:
22980 	if (ill != NULL && ill_need_rele)
22981 		ill_refrele(ill);
22982 	if (ipif != NULL)
22983 		ipif_refrele(ipif);
22984 }
22985 
22986 /*
22987  * Get the ill corresponding to the specified ire, and compare its
22988  * capabilities with the protocol and algorithms specified by the
22989  * the SA obtained from ipsec_out. If they match, annotate the
22990  * ipsec_out structure to indicate that the packet needs acceleration.
22991  *
22992  *
22993  * A packet is eligible for outbound hardware acceleration if the
22994  * following conditions are satisfied:
22995  *
22996  * 1. the packet will not be fragmented
22997  * 2. the provider supports the algorithm
22998  * 3. there is no pending control message being exchanged
22999  * 4. snoop is not attached
23000  * 5. the destination address is not a broadcast or multicast address.
23001  *
23002  * Rationale:
23003  *	- Hardware drivers do not support fragmentation with
23004  *	  the current interface.
23005  *	- snoop, multicast, and broadcast may result in exposure of
23006  *	  a cleartext datagram.
23007  * We check all five of these conditions here.
23008  *
23009  * XXX would like to nuke "ire_t *" parameter here; problem is that
23010  * IRE is only way to figure out if a v4 address is a broadcast and
23011  * thus ineligible for acceleration...
23012  */
23013 static void
23014 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
23015 {
23016 	ipsec_out_t *io;
23017 	mblk_t *data_mp;
23018 	uint_t plen, overhead;
23019 
23020 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
23021 		return;
23022 
23023 	if (ill == NULL)
23024 		return;
23025 
23026 	/*
23027 	 * Destination address is a broadcast or multicast.  Punt.
23028 	 */
23029 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
23030 	    IRE_LOCAL)))
23031 		return;
23032 
23033 	data_mp = ipsec_mp->b_cont;
23034 
23035 	if (ill->ill_isv6) {
23036 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
23037 
23038 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
23039 			return;
23040 
23041 		plen = ip6h->ip6_plen;
23042 	} else {
23043 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
23044 
23045 		if (CLASSD(ipha->ipha_dst))
23046 			return;
23047 
23048 		plen = ipha->ipha_length;
23049 	}
23050 	/*
23051 	 * Is there a pending DLPI control message being exchanged
23052 	 * between IP/IPsec and the DLS Provider? If there is, it
23053 	 * could be a SADB update, and the state of the DLS Provider
23054 	 * SADB might not be in sync with the SADB maintained by
23055 	 * IPsec. To avoid dropping packets or using the wrong keying
23056 	 * material, we do not accelerate this packet.
23057 	 */
23058 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
23059 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
23060 		    "ill_dlpi_pending! don't accelerate packet\n"));
23061 		return;
23062 	}
23063 
23064 	/*
23065 	 * Is the Provider in promiscous mode? If it does, we don't
23066 	 * accelerate the packet since it will bounce back up to the
23067 	 * listeners in the clear.
23068 	 */
23069 	if (ill->ill_promisc_on_phys) {
23070 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
23071 		    "ill in promiscous mode, don't accelerate packet\n"));
23072 		return;
23073 	}
23074 
23075 	/*
23076 	 * Will the packet require fragmentation?
23077 	 */
23078 
23079 	/*
23080 	 * IPsec ESP note: this is a pessimistic estimate, but the same
23081 	 * as is used elsewhere.
23082 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
23083 	 *	+ 2-byte trailer
23084 	 */
23085 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
23086 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
23087 
23088 	if ((plen + overhead) > ill->ill_max_mtu)
23089 		return;
23090 
23091 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23092 
23093 	/*
23094 	 * Can the ill accelerate this IPsec protocol and algorithm
23095 	 * specified by the SA?
23096 	 */
23097 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
23098 	    ill->ill_isv6, sa)) {
23099 		return;
23100 	}
23101 
23102 	/*
23103 	 * Tell AH or ESP that the outbound ill is capable of
23104 	 * accelerating this packet.
23105 	 */
23106 	io->ipsec_out_is_capab_ill = B_TRUE;
23107 }
23108 
23109 /*
23110  * Select which AH & ESP SA's to use (if any) for the outbound packet.
23111  *
23112  * If this function returns B_TRUE, the requested SA's have been filled
23113  * into the ipsec_out_*_sa pointers.
23114  *
23115  * If the function returns B_FALSE, the packet has been "consumed", most
23116  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
23117  *
23118  * The SA references created by the protocol-specific "select"
23119  * function will be released when the ipsec_mp is freed, thanks to the
23120  * ipsec_out_free destructor -- see spd.c.
23121  */
23122 static boolean_t
23123 ipsec_out_select_sa(mblk_t *ipsec_mp)
23124 {
23125 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
23126 	ipsec_out_t *io;
23127 	ipsec_policy_t *pp;
23128 	ipsec_action_t *ap;
23129 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23130 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
23131 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
23132 
23133 	if (!io->ipsec_out_secure) {
23134 		/*
23135 		 * We came here by mistake.
23136 		 * Don't bother with ipsec processing
23137 		 * We should "discourage" this path in the future.
23138 		 */
23139 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
23140 		return (B_FALSE);
23141 	}
23142 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
23143 	ASSERT((io->ipsec_out_policy != NULL) ||
23144 	    (io->ipsec_out_act != NULL));
23145 
23146 	ASSERT(io->ipsec_out_failed == B_FALSE);
23147 
23148 	/*
23149 	 * IPSEC processing has started.
23150 	 */
23151 	io->ipsec_out_proc_begin = B_TRUE;
23152 	ap = io->ipsec_out_act;
23153 	if (ap == NULL) {
23154 		pp = io->ipsec_out_policy;
23155 		ASSERT(pp != NULL);
23156 		ap = pp->ipsp_act;
23157 		ASSERT(ap != NULL);
23158 	}
23159 
23160 	/*
23161 	 * We have an action.  now, let's select SA's.
23162 	 * (In the future, we can cache this in the conn_t..)
23163 	 */
23164 	if (ap->ipa_want_esp) {
23165 		if (io->ipsec_out_esp_sa == NULL) {
23166 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
23167 			    IPPROTO_ESP);
23168 		}
23169 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
23170 	}
23171 
23172 	if (ap->ipa_want_ah) {
23173 		if (io->ipsec_out_ah_sa == NULL) {
23174 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
23175 			    IPPROTO_AH);
23176 		}
23177 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
23178 		/*
23179 		 * The ESP and AH processing order needs to be preserved
23180 		 * when both protocols are required (ESP should be applied
23181 		 * before AH for an outbound packet). Force an ESP ACQUIRE
23182 		 * when both ESP and AH are required, and an AH ACQUIRE
23183 		 * is needed.
23184 		 */
23185 		if (ap->ipa_want_esp && need_ah_acquire)
23186 			need_esp_acquire = B_TRUE;
23187 	}
23188 
23189 	/*
23190 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
23191 	 * Release SAs that got referenced, but will not be used until we
23192 	 * acquire _all_ of the SAs we need.
23193 	 */
23194 	if (need_ah_acquire || need_esp_acquire) {
23195 		if (io->ipsec_out_ah_sa != NULL) {
23196 			IPSA_REFRELE(io->ipsec_out_ah_sa);
23197 			io->ipsec_out_ah_sa = NULL;
23198 		}
23199 		if (io->ipsec_out_esp_sa != NULL) {
23200 			IPSA_REFRELE(io->ipsec_out_esp_sa);
23201 			io->ipsec_out_esp_sa = NULL;
23202 		}
23203 
23204 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
23205 		return (B_FALSE);
23206 	}
23207 
23208 	return (B_TRUE);
23209 }
23210 
23211 /*
23212  * Process an IPSEC_OUT message and see what you can
23213  * do with it.
23214  * IPQoS Notes:
23215  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
23216  * IPSec.
23217  * XXX would like to nuke ire_t.
23218  * XXX ill_index better be "real"
23219  */
23220 void
23221 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
23222 {
23223 	ipsec_out_t *io;
23224 	ipsec_policy_t *pp;
23225 	ipsec_action_t *ap;
23226 	ipha_t *ipha;
23227 	ip6_t *ip6h;
23228 	mblk_t *mp;
23229 	ill_t *ill;
23230 	zoneid_t zoneid;
23231 	ipsec_status_t ipsec_rc;
23232 	boolean_t ill_need_rele = B_FALSE;
23233 
23234 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23235 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
23236 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
23237 	mp = ipsec_mp->b_cont;
23238 
23239 	/*
23240 	 * Initiate IPPF processing. We do it here to account for packets
23241 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
23242 	 * We can check for ipsec_out_proc_begin even for such packets, as
23243 	 * they will always be false (asserted below).
23244 	 */
23245 	if (IPP_ENABLED(IPP_LOCAL_OUT) && !io->ipsec_out_proc_begin) {
23246 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
23247 		    io->ipsec_out_ill_index : ill_index);
23248 		if (mp == NULL) {
23249 			ip2dbg(("ipsec_out_process: packet dropped "\
23250 			    "during IPPF processing\n"));
23251 			freeb(ipsec_mp);
23252 			BUMP_MIB(&ip_mib, ipOutDiscards);
23253 			return;
23254 		}
23255 	}
23256 
23257 	if (!io->ipsec_out_secure) {
23258 		/*
23259 		 * We came here by mistake.
23260 		 * Don't bother with ipsec processing
23261 		 * Should "discourage" this path in the future.
23262 		 */
23263 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
23264 		goto done;
23265 	}
23266 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
23267 	ASSERT((io->ipsec_out_policy != NULL) ||
23268 	    (io->ipsec_out_act != NULL));
23269 	ASSERT(io->ipsec_out_failed == B_FALSE);
23270 
23271 	if (!ipsec_loaded()) {
23272 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
23273 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
23274 			BUMP_MIB(&ip_mib, ipOutDiscards);
23275 		} else {
23276 			BUMP_MIB(&ip6_mib, ipv6OutDiscards);
23277 		}
23278 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
23279 		    &ipdrops_ip_ipsec_not_loaded, &ip_dropper);
23280 		return;
23281 	}
23282 
23283 	/*
23284 	 * IPSEC processing has started.
23285 	 */
23286 	io->ipsec_out_proc_begin = B_TRUE;
23287 	ap = io->ipsec_out_act;
23288 	if (ap == NULL) {
23289 		pp = io->ipsec_out_policy;
23290 		ASSERT(pp != NULL);
23291 		ap = pp->ipsp_act;
23292 		ASSERT(ap != NULL);
23293 	}
23294 
23295 	/*
23296 	 * Save the outbound ill index. When the packet comes back
23297 	 * from IPsec, we make sure the ill hasn't changed or disappeared
23298 	 * before sending it the accelerated packet.
23299 	 */
23300 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
23301 		int ifindex;
23302 		ill = ire_to_ill(ire);
23303 		ifindex = ill->ill_phyint->phyint_ifindex;
23304 		io->ipsec_out_capab_ill_index = ifindex;
23305 	}
23306 
23307 	/*
23308 	 * The order of processing is first insert a IP header if needed.
23309 	 * Then insert the ESP header and then the AH header.
23310 	 */
23311 	if ((io->ipsec_out_se_done == B_FALSE) &&
23312 	    (ap->ipa_want_se)) {
23313 		/*
23314 		 * First get the outer IP header before sending
23315 		 * it to ESP.
23316 		 */
23317 		ipha_t *oipha, *iipha;
23318 		mblk_t *outer_mp, *inner_mp;
23319 
23320 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
23321 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
23322 			    "ipsec_out_process: "
23323 			    "Self-Encapsulation failed: Out of memory\n");
23324 			freemsg(ipsec_mp);
23325 			BUMP_MIB(&ip_mib, ipOutDiscards);
23326 			return;
23327 		}
23328 		inner_mp = ipsec_mp->b_cont;
23329 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
23330 		oipha = (ipha_t *)outer_mp->b_rptr;
23331 		iipha = (ipha_t *)inner_mp->b_rptr;
23332 		*oipha = *iipha;
23333 		outer_mp->b_wptr += sizeof (ipha_t);
23334 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
23335 		    sizeof (ipha_t));
23336 		oipha->ipha_protocol = IPPROTO_ENCAP;
23337 		oipha->ipha_version_and_hdr_length =
23338 		    IP_SIMPLE_HDR_VERSION;
23339 		oipha->ipha_hdr_checksum = 0;
23340 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
23341 		outer_mp->b_cont = inner_mp;
23342 		ipsec_mp->b_cont = outer_mp;
23343 
23344 		io->ipsec_out_se_done = B_TRUE;
23345 		io->ipsec_out_encaps = B_TRUE;
23346 	}
23347 
23348 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
23349 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
23350 	    !ipsec_out_select_sa(ipsec_mp))
23351 		return;
23352 
23353 	/*
23354 	 * By now, we know what SA's to use.  Toss over to ESP & AH
23355 	 * to do the heavy lifting.
23356 	 */
23357 	zoneid = io->ipsec_out_zoneid;
23358 	ASSERT(zoneid != ALL_ZONES);
23359 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
23360 		ASSERT(io->ipsec_out_esp_sa != NULL);
23361 		io->ipsec_out_esp_done = B_TRUE;
23362 		/*
23363 		 * Note that since hw accel can only apply one transform,
23364 		 * not two, we skip hw accel for ESP if we also have AH
23365 		 * This is an design limitation of the interface
23366 		 * which should be revisited.
23367 		 */
23368 		ASSERT(ire != NULL);
23369 		if (io->ipsec_out_ah_sa == NULL) {
23370 			ill = (ill_t *)ire->ire_stq->q_ptr;
23371 			ipsec_out_is_accelerated(ipsec_mp,
23372 			    io->ipsec_out_esp_sa, ill, ire);
23373 		}
23374 
23375 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
23376 		switch (ipsec_rc) {
23377 		case IPSEC_STATUS_SUCCESS:
23378 			break;
23379 		case IPSEC_STATUS_FAILED:
23380 			BUMP_MIB(&ip_mib, ipOutDiscards);
23381 			/* FALLTHRU */
23382 		case IPSEC_STATUS_PENDING:
23383 			return;
23384 		}
23385 	}
23386 
23387 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
23388 		ASSERT(io->ipsec_out_ah_sa != NULL);
23389 		io->ipsec_out_ah_done = B_TRUE;
23390 		if (ire == NULL) {
23391 			int idx = io->ipsec_out_capab_ill_index;
23392 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
23393 			    NULL, NULL, NULL, NULL);
23394 			ill_need_rele = B_TRUE;
23395 		} else {
23396 			ill = (ill_t *)ire->ire_stq->q_ptr;
23397 		}
23398 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
23399 		    ire);
23400 
23401 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
23402 		switch (ipsec_rc) {
23403 		case IPSEC_STATUS_SUCCESS:
23404 			break;
23405 		case IPSEC_STATUS_FAILED:
23406 			BUMP_MIB(&ip_mib, ipOutDiscards);
23407 			/* FALLTHRU */
23408 		case IPSEC_STATUS_PENDING:
23409 			if (ill != NULL && ill_need_rele)
23410 				ill_refrele(ill);
23411 			return;
23412 		}
23413 	}
23414 	/*
23415 	 * We are done with IPSEC processing. Send it over
23416 	 * the wire.
23417 	 */
23418 done:
23419 	mp = ipsec_mp->b_cont;
23420 	ipha = (ipha_t *)mp->b_rptr;
23421 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
23422 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
23423 	} else {
23424 		ip6h = (ip6_t *)ipha;
23425 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
23426 	}
23427 	if (ill != NULL && ill_need_rele)
23428 		ill_refrele(ill);
23429 }
23430 
23431 /* ARGSUSED */
23432 void
23433 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
23434 {
23435 	opt_restart_t	*or;
23436 	int	err;
23437 	conn_t	*connp;
23438 
23439 	ASSERT(CONN_Q(q));
23440 	connp = Q_TO_CONN(q);
23441 
23442 	ASSERT(first_mp->b_datap->db_type == M_CTL);
23443 	or = (opt_restart_t *)first_mp->b_rptr;
23444 	/*
23445 	 * We don't need to pass any credentials here since this is just
23446 	 * a restart. The credentials are passed in when svr4_optcom_req
23447 	 * is called the first time (from ip_wput_nondata).
23448 	 */
23449 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
23450 		err = svr4_optcom_req(q, first_mp, NULL,
23451 		    &ip_opt_obj);
23452 	} else {
23453 		ASSERT(or->or_type == T_OPTMGMT_REQ);
23454 		err = tpi_optcom_req(q, first_mp, NULL,
23455 		    &ip_opt_obj);
23456 	}
23457 	if (err != EINPROGRESS) {
23458 		/* operation is done */
23459 		CONN_OPER_PENDING_DONE(connp);
23460 	}
23461 }
23462 
23463 /*
23464  * ioctls that go through a down/up sequence may need to wait for the down
23465  * to complete. This involves waiting for the ire and ipif refcnts to go down
23466  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
23467  */
23468 /* ARGSUSED */
23469 void
23470 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
23471 {
23472 	struct iocblk *iocp;
23473 	mblk_t *mp1;
23474 	ipif_t	*ipif;
23475 	ip_ioctl_cmd_t *ipip;
23476 	int err;
23477 	sin_t	*sin;
23478 	struct lifreq *lifr;
23479 	struct ifreq *ifr;
23480 
23481 	iocp = (struct iocblk *)mp->b_rptr;
23482 	ASSERT(ipsq != NULL);
23483 	/* Existence of mp1 verified in ip_wput_nondata */
23484 	mp1 = mp->b_cont->b_cont;
23485 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
23486 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
23487 		ill_t *ill;
23488 		/*
23489 		 * Special case where ipsq_current_ipif may not be set.
23490 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
23491 		 * ill could also have become part of a ipmp group in the
23492 		 * process, we are here as were not able to complete the
23493 		 * operation in ipif_set_values because we could not become
23494 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
23495 		 * will not be set so we need to set it.
23496 		 */
23497 		ill = (ill_t *)q->q_ptr;
23498 		ipsq->ipsq_current_ipif = ill->ill_ipif;
23499 		ipsq->ipsq_last_cmd = ipip->ipi_cmd;
23500 	}
23501 
23502 	ipif = ipsq->ipsq_current_ipif;
23503 	ASSERT(ipif != NULL);
23504 	if (ipip->ipi_cmd_type == IF_CMD) {
23505 		/* This a old style SIOC[GS]IF* command */
23506 		ifr = (struct ifreq *)mp1->b_rptr;
23507 		sin = (sin_t *)&ifr->ifr_addr;
23508 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
23509 		/* This a new style SIOC[GS]LIF* command */
23510 		lifr = (struct lifreq *)mp1->b_rptr;
23511 		sin = (sin_t *)&lifr->lifr_addr;
23512 	} else {
23513 		sin = NULL;
23514 	}
23515 
23516 	err = (*ipip->ipi_func_restart)(ipif, sin, q, mp, ipip,
23517 	    (void *)mp1->b_rptr);
23518 
23519 	/* SIOCLIFREMOVEIF could have removed the ipif */
23520 	ip_ioctl_finish(q, mp, err,
23521 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
23522 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ipif, ipsq);
23523 }
23524 
23525 /*
23526  * ioctl processing
23527  *
23528  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
23529  * the ioctl command in the ioctl tables and determines the copyin data size
23530  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
23531  * size.
23532  *
23533  * ioctl processing then continues when the M_IOCDATA makes its way down.
23534  * Now the ioctl is looked up again in the ioctl table, and its properties are
23535  * extracted. The associated 'conn' is then refheld till the end of the ioctl
23536  * and the general ioctl processing function ip_process_ioctl is called.
23537  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
23538  * so goes thru the serialization primitive ipsq_try_enter. Then the
23539  * appropriate function to handle the ioctl is called based on the entry in
23540  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
23541  * which also refreleases the 'conn' that was refheld at the start of the
23542  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
23543  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
23544  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
23545  *
23546  * Many exclusive ioctls go thru an internal down up sequence as part of
23547  * the operation. For example an attempt to change the IP address of an
23548  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
23549  * does all the cleanup such as deleting all ires that use this address.
23550  * Then we need to wait till all references to the interface go away.
23551  */
23552 void
23553 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
23554 {
23555 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
23556 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
23557 	cmd_info_t ci;
23558 	int err;
23559 	boolean_t entered_ipsq = B_FALSE;
23560 
23561 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
23562 
23563 	if (ipip == NULL)
23564 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
23565 
23566 	/*
23567 	 * SIOCLIFADDIF needs to go thru a special path since the
23568 	 * ill may not exist yet. This happens in the case of lo0
23569 	 * which is created using this ioctl.
23570 	 */
23571 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
23572 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
23573 		ip_ioctl_finish(q, mp, err,
23574 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
23575 		    NULL, NULL);
23576 		return;
23577 	}
23578 
23579 	ci.ci_ipif = NULL;
23580 	switch (ipip->ipi_cmd_type) {
23581 	case IF_CMD:
23582 	case LIF_CMD:
23583 		/*
23584 		 * ioctls that pass in a [l]ifreq appear here.
23585 		 * ip_extract_lifreq_cmn returns a refheld ipif in
23586 		 * ci.ci_ipif
23587 		 */
23588 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
23589 		    ipip->ipi_flags, &ci, ip_process_ioctl);
23590 		if (err != 0) {
23591 			ip_ioctl_finish(q, mp, err,
23592 			    ipip->ipi_flags & IPI_GET_CMD ?
23593 			    COPYOUT : NO_COPYOUT, NULL, NULL);
23594 			return;
23595 		}
23596 		ASSERT(ci.ci_ipif != NULL);
23597 		break;
23598 
23599 	case TUN_CMD:
23600 		/*
23601 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
23602 		 * a refheld ipif in ci.ci_ipif
23603 		 */
23604 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
23605 		if (err != 0) {
23606 			ip_ioctl_finish(q, mp, err,
23607 			    ipip->ipi_flags & IPI_GET_CMD ?
23608 			    COPYOUT : NO_COPYOUT, NULL, NULL);
23609 			return;
23610 		}
23611 		ASSERT(ci.ci_ipif != NULL);
23612 		break;
23613 
23614 	case MISC_CMD:
23615 		/*
23616 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
23617 		 * For eg. SIOCGLIFCONF will appear here.
23618 		 */
23619 		switch (ipip->ipi_cmd) {
23620 		case IF_UNITSEL:
23621 			/* ioctl comes down the ill */
23622 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
23623 			ipif_refhold(ci.ci_ipif);
23624 			break;
23625 		case SIOCGMSFILTER:
23626 		case SIOCSMSFILTER:
23627 		case SIOCGIPMSFILTER:
23628 		case SIOCSIPMSFILTER:
23629 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
23630 			    ip_process_ioctl);
23631 			if (err != 0) {
23632 				ip_ioctl_finish(q, mp, err,
23633 				    ipip->ipi_flags & IPI_GET_CMD ?
23634 				    COPYOUT : NO_COPYOUT, NULL, NULL);
23635 				return;
23636 			}
23637 			break;
23638 		}
23639 		err = 0;
23640 		ci.ci_sin = NULL;
23641 		ci.ci_sin6 = NULL;
23642 		ci.ci_lifr = NULL;
23643 		break;
23644 	}
23645 
23646 	/*
23647 	 * If ipsq is non-null, we are already being called exclusively
23648 	 */
23649 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
23650 	if (!(ipip->ipi_flags & IPI_WR)) {
23651 		/*
23652 		 * A return value of EINPROGRESS means the ioctl is
23653 		 * either queued and waiting for some reason or has
23654 		 * already completed.
23655 		 */
23656 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
23657 		    ci.ci_lifr);
23658 		if (ci.ci_ipif != NULL)
23659 			ipif_refrele(ci.ci_ipif);
23660 		ip_ioctl_finish(q, mp, err,
23661 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
23662 		    NULL, NULL);
23663 		return;
23664 	}
23665 
23666 	ASSERT(ci.ci_ipif != NULL);
23667 
23668 	if (ipsq == NULL) {
23669 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
23670 		    ip_process_ioctl, NEW_OP, B_TRUE);
23671 		entered_ipsq = B_TRUE;
23672 	}
23673 	/*
23674 	 * Release the ipif so that ipif_down and friends that wait for
23675 	 * references to go away are not misled about the current ipif_refcnt
23676 	 * values. We are writer so we can access the ipif even after releasing
23677 	 * the ipif.
23678 	 */
23679 	ipif_refrele(ci.ci_ipif);
23680 	if (ipsq == NULL)
23681 		return;
23682 
23683 	mutex_enter(&ipsq->ipsq_lock);
23684 	ASSERT(ipsq->ipsq_current_ipif == NULL);
23685 	ipsq->ipsq_current_ipif = ci.ci_ipif;
23686 	ipsq->ipsq_last_cmd = ipip->ipi_cmd;
23687 	mutex_exit(&ipsq->ipsq_lock);
23688 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
23689 	/*
23690 	 * For most set ioctls that come here, this serves as a single point
23691 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
23692 	 * be any new references to the ipif. This helps functions that go
23693 	 * through this path and end up trying to wait for the refcnts
23694 	 * associated with the ipif to go down to zero. Some exceptions are
23695 	 * Failover, Failback, and Groupname commands that operate on more than
23696 	 * just the ci.ci_ipif. These commands internally determine the
23697 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
23698 	 * flags on that set. Another exception is the Removeif command that
23699 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
23700 	 * ipif to operate on.
23701 	 */
23702 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
23703 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
23704 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
23705 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
23706 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
23707 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
23708 
23709 	/*
23710 	 * A return value of EINPROGRESS means the ioctl is
23711 	 * either queued and waiting for some reason or has
23712 	 * already completed.
23713 	 */
23714 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
23715 	    ci.ci_lifr);
23716 
23717 	/* SIOCLIFREMOVEIF could have removed the ipif */
23718 	ip_ioctl_finish(q, mp, err,
23719 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
23720 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ci.ci_ipif, ipsq);
23721 
23722 	if (entered_ipsq)
23723 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
23724 }
23725 
23726 /*
23727  * Complete the ioctl. Typically ioctls use the mi package and need to
23728  * do mi_copyout/mi_copy_done.
23729  */
23730 void
23731 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode,
23732     ipif_t *ipif, ipsq_t *ipsq)
23733 {
23734 	conn_t	*connp = NULL;
23735 
23736 	if (err == EINPROGRESS)
23737 		return;
23738 
23739 	if (CONN_Q(q)) {
23740 		connp = Q_TO_CONN(q);
23741 		ASSERT(connp->conn_ref >= 2);
23742 	}
23743 
23744 	switch (mode) {
23745 	case COPYOUT:
23746 		if (err == 0)
23747 			mi_copyout(q, mp);
23748 		else
23749 			mi_copy_done(q, mp, err);
23750 		break;
23751 
23752 	case NO_COPYOUT:
23753 		mi_copy_done(q, mp, err);
23754 		break;
23755 
23756 	default:
23757 		/* An ioctl aborted through a conn close would take this path */
23758 		break;
23759 	}
23760 
23761 	/*
23762 	 * The refhold placed at the start of the ioctl is released here.
23763 	 */
23764 	if (connp != NULL)
23765 		CONN_OPER_PENDING_DONE(connp);
23766 
23767 	/*
23768 	 * If the ioctl were an exclusive ioctl it would have set
23769 	 * IPIF_CHANGING at the start of the ioctl which is undone here.
23770 	 */
23771 	if (ipif != NULL) {
23772 		mutex_enter(&(ipif)->ipif_ill->ill_lock);
23773 		ipif->ipif_state_flags &= ~IPIF_CHANGING;
23774 		mutex_exit(&(ipif)->ipif_ill->ill_lock);
23775 	}
23776 
23777 	/*
23778 	 * Clear the current ipif in the ipsq at the completion of the ioctl.
23779 	 * Note that a non-null ipsq_current_ipif prevents new ioctls from
23780 	 * entering the ipsq
23781 	 */
23782 	if (ipsq != NULL) {
23783 		mutex_enter(&ipsq->ipsq_lock);
23784 		ipsq->ipsq_current_ipif = NULL;
23785 		mutex_exit(&ipsq->ipsq_lock);
23786 	}
23787 }
23788 
23789 /*
23790  * This is called from ip_wput_nondata to resume a deferred TCP bind.
23791  */
23792 /* ARGSUSED */
23793 void
23794 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
23795 {
23796 	conn_t *connp = (conn_t *)arg;
23797 	tcp_t	*tcp;
23798 
23799 	ASSERT(connp != NULL && connp->conn_tcp != NULL);
23800 	tcp = connp->conn_tcp;
23801 
23802 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
23803 		freemsg(mp);
23804 	else
23805 		tcp_rput_other(tcp, mp);
23806 	CONN_OPER_PENDING_DONE(connp);
23807 
23808 }
23809 
23810 /* Called from ip_wput for all non data messages */
23811 /* ARGSUSED */
23812 void
23813 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
23814 {
23815 	mblk_t		*mp1;
23816 	ire_t		*ire;
23817 	ill_t		*ill;
23818 	struct iocblk	*iocp;
23819 	ip_ioctl_cmd_t	*ipip;
23820 	cred_t		*cr;
23821 	conn_t		*connp = NULL;
23822 	int		cmd, err;
23823 
23824 	if (CONN_Q(q))
23825 		connp = Q_TO_CONN(q);
23826 
23827 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
23828 
23829 	/* Check if it is a queue to /dev/sctp. */
23830 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
23831 	    connp->conn_rq == NULL) {
23832 		sctp_wput(q, mp);
23833 		return;
23834 	}
23835 
23836 	switch (DB_TYPE(mp)) {
23837 	case M_IOCTL:
23838 		/*
23839 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
23840 		 * will arrange to copy in associated control structures.
23841 		 */
23842 		ip_sioctl_copyin_setup(q, mp);
23843 		return;
23844 	case M_IOCDATA:
23845 		/*
23846 		 * Ensure that this is associated with one of our trans-
23847 		 * parent ioctls.  If it's not ours, discard it if we're
23848 		 * running as a driver, or pass it on if we're a module.
23849 		 */
23850 		iocp = (struct iocblk *)mp->b_rptr;
23851 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
23852 		if (ipip == NULL) {
23853 			if (q->q_next == NULL) {
23854 				goto nak;
23855 			} else {
23856 				putnext(q, mp);
23857 			}
23858 			return;
23859 		} else if ((q->q_next != NULL) &&
23860 		    !(ipip->ipi_flags & IPI_MODOK)) {
23861 			/*
23862 			 * the ioctl is one we recognise, but is not
23863 			 * consumed by IP as a module, pass M_IOCDATA
23864 			 * for processing downstream, but only for
23865 			 * common Streams ioctls.
23866 			 */
23867 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
23868 				putnext(q, mp);
23869 				return;
23870 			} else {
23871 				goto nak;
23872 			}
23873 		}
23874 
23875 		/* IOCTL continuation following copyin or copyout. */
23876 		if (mi_copy_state(q, mp, NULL) == -1) {
23877 			/*
23878 			 * The copy operation failed.  mi_copy_state already
23879 			 * cleaned up, so we're out of here.
23880 			 */
23881 			return;
23882 		}
23883 		/*
23884 		 * If we just completed a copy in, we become writer and
23885 		 * continue processing in ip_sioctl_copyin_done.  If it
23886 		 * was a copy out, we call mi_copyout again.  If there is
23887 		 * nothing more to copy out, it will complete the IOCTL.
23888 		 */
23889 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
23890 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
23891 				mi_copy_done(q, mp, EPROTO);
23892 				return;
23893 			}
23894 			/*
23895 			 * Check for cases that need more copying.  A return
23896 			 * value of 0 means a second copyin has been started,
23897 			 * so we return; a return value of 1 means no more
23898 			 * copying is needed, so we continue.
23899 			 */
23900 			cmd = iocp->ioc_cmd;
23901 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
23902 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
23903 			    MI_COPY_COUNT(mp) == 1) {
23904 				if (ip_copyin_msfilter(q, mp) == 0)
23905 					return;
23906 			}
23907 			/*
23908 			 * Refhold the conn, till the ioctl completes. This is
23909 			 * needed in case the ioctl ends up in the pending mp
23910 			 * list. Every mp in the ill_pending_mp list and
23911 			 * the ipsq_pending_mp must have a refhold on the conn
23912 			 * to resume processing. The refhold is released when
23913 			 * the ioctl completes. (normally or abnormally)
23914 			 * In all cases ip_ioctl_finish is called to finish
23915 			 * the ioctl.
23916 			 */
23917 			if (connp != NULL) {
23918 				/* This is not a reentry */
23919 				ASSERT(ipsq == NULL);
23920 				CONN_INC_REF(connp);
23921 			} else {
23922 				if (!(ipip->ipi_flags & IPI_MODOK)) {
23923 					mi_copy_done(q, mp, EINVAL);
23924 					return;
23925 				}
23926 			}
23927 
23928 			ip_process_ioctl(ipsq, q, mp, ipip);
23929 
23930 		} else {
23931 			mi_copyout(q, mp);
23932 		}
23933 		return;
23934 nak:
23935 		iocp->ioc_error = EINVAL;
23936 		mp->b_datap->db_type = M_IOCNAK;
23937 		iocp->ioc_count = 0;
23938 		qreply(q, mp);
23939 		return;
23940 
23941 	case M_IOCNAK:
23942 		/*
23943 		 * The only way we could get here is if a resolver didn't like
23944 		 * an IOCTL we sent it.	 This shouldn't happen.
23945 		 */
23946 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
23947 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
23948 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
23949 		freemsg(mp);
23950 		return;
23951 	case M_IOCACK:
23952 		/* Finish socket ioctls passed through to ARP. */
23953 		ip_sioctl_iocack(q, mp);
23954 		return;
23955 	case M_FLUSH:
23956 		if (*mp->b_rptr & FLUSHW)
23957 			flushq(q, FLUSHALL);
23958 		if (q->q_next) {
23959 			/*
23960 			 * M_FLUSH is sent up to IP by some drivers during
23961 			 * unbind. ip_rput has already replied to it. We are
23962 			 * here for the M_FLUSH that we originated in IP
23963 			 * before sending the unbind request to the driver.
23964 			 * Just free it as we don't queue packets in IP
23965 			 * on the write side of the device instance.
23966 			 */
23967 			freemsg(mp);
23968 			return;
23969 		}
23970 		if (*mp->b_rptr & FLUSHR) {
23971 			*mp->b_rptr &= ~FLUSHW;
23972 			qreply(q, mp);
23973 			return;
23974 		}
23975 		freemsg(mp);
23976 		return;
23977 	case IRE_DB_REQ_TYPE:
23978 		/* An Upper Level Protocol wants a copy of an IRE. */
23979 		ip_ire_req(q, mp);
23980 		return;
23981 	case M_CTL:
23982 		/* M_CTL messages are used by ARP to tell us things. */
23983 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
23984 			break;
23985 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
23986 		case AR_ENTRY_SQUERY:
23987 			ip_wput_ctl(q, mp);
23988 			return;
23989 		case AR_CLIENT_NOTIFY:
23990 			ip_arp_news(q, mp);
23991 			return;
23992 		case AR_DLPIOP_DONE:
23993 			ASSERT(q->q_next != NULL);
23994 			ill = (ill_t *)q->q_ptr;
23995 			/* qwriter_ip releases the refhold */
23996 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
23997 			ill_refhold(ill);
23998 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
23999 			    CUR_OP, B_FALSE);
24000 			return;
24001 		case AR_ARP_CLOSING:
24002 			/*
24003 			 * ARP (above us) is closing. If no ARP bringup is
24004 			 * currently pending, ack the message so that ARP
24005 			 * can complete its close. Also mark ill_arp_closing
24006 			 * so that new ARP bringups will fail. If any
24007 			 * ARP bringup is currently in progress, we will
24008 			 * ack this when the current ARP bringup completes.
24009 			 */
24010 			ASSERT(q->q_next != NULL);
24011 			ill = (ill_t *)q->q_ptr;
24012 			mutex_enter(&ill->ill_lock);
24013 			ill->ill_arp_closing = 1;
24014 			if (!ill->ill_arp_bringup_pending) {
24015 				mutex_exit(&ill->ill_lock);
24016 				qreply(q, mp);
24017 			} else {
24018 				mutex_exit(&ill->ill_lock);
24019 				freemsg(mp);
24020 			}
24021 			return;
24022 		default:
24023 			break;
24024 		}
24025 		break;
24026 	case M_PROTO:
24027 	case M_PCPROTO:
24028 		/*
24029 		 * The only PROTO messages we expect are ULP binds and
24030 		 * copies of option negotiation acknowledgements.
24031 		 */
24032 		switch (((union T_primitives *)mp->b_rptr)->type) {
24033 		case O_T_BIND_REQ:
24034 		case T_BIND_REQ: {
24035 			/* Request can get queued in bind */
24036 			ASSERT(connp != NULL);
24037 			/* Don't increment refcnt if this is a re-entry */
24038 			if (ipsq == NULL)
24039 				CONN_INC_REF(connp);
24040 			mp = connp->conn_af_isv6 ?
24041 			    ip_bind_v6(q, mp, connp, NULL) :
24042 				ip_bind_v4(q, mp, connp);
24043 			if (mp != NULL) {
24044 				tcp_t	*tcp;
24045 
24046 				tcp = connp->conn_tcp;
24047 				if (tcp != NULL) {
24048 					if (ipsq == NULL) {
24049 						tcp_rput_other(tcp, mp);
24050 					} else {
24051 						CONN_INC_REF(connp);
24052 						squeue_fill(connp->conn_sqp, mp,
24053 						    ip_resume_tcp_bind,
24054 						    connp, SQTAG_TCP_RPUTOTHER);
24055 						return;
24056 					}
24057 				} else {
24058 					qreply(q, mp);
24059 				}
24060 				CONN_OPER_PENDING_DONE(connp);
24061 			}
24062 			return;
24063 		}
24064 		case T_SVR4_OPTMGMT_REQ:
24065 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
24066 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
24067 
24068 			ASSERT(connp != NULL);
24069 			if (!snmpcom_req(q, mp, ip_snmp_set,
24070 			    ip_snmp_get, cr)) {
24071 				/*
24072 				 * Call svr4_optcom_req so that it can
24073 				 * generate the ack. We don't come here
24074 				 * if this operation is being restarted.
24075 				 * ip_restart_optmgmt will drop the conn ref.
24076 				 * In the case of ipsec option after the ipsec
24077 				 * load is complete conn_restart_ipsec_waiter
24078 				 * drops the conn ref.
24079 				 */
24080 				ASSERT(ipsq == NULL);
24081 				CONN_INC_REF(connp);
24082 				if (ip_check_for_ipsec_opt(q, mp))
24083 					return;
24084 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
24085 				if (err != EINPROGRESS) {
24086 					/* Operation is done */
24087 					CONN_OPER_PENDING_DONE(connp);
24088 				}
24089 			}
24090 			return;
24091 		case T_OPTMGMT_REQ:
24092 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
24093 			/*
24094 			 * Note: No snmpcom_req support through new
24095 			 * T_OPTMGMT_REQ.
24096 			 * Call tpi_optcom_req so that it can
24097 			 * generate the ack.
24098 			 */
24099 			ASSERT(connp != NULL);
24100 			ASSERT(ipsq == NULL);
24101 			/*
24102 			 * We don't come here for restart. ip_restart_optmgmt
24103 			 * will drop the conn ref. In the case of ipsec option
24104 			 * after the ipsec load is complete
24105 			 * conn_restart_ipsec_waiter drops the conn ref.
24106 			 */
24107 			CONN_INC_REF(connp);
24108 			if (ip_check_for_ipsec_opt(q, mp))
24109 				return;
24110 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
24111 			if (err != EINPROGRESS) {
24112 				/* Operation is done */
24113 				CONN_OPER_PENDING_DONE(connp);
24114 			}
24115 			return;
24116 		case T_UNBIND_REQ:
24117 			ip_unbind(q, mp);
24118 			return;
24119 		default:
24120 			/*
24121 			 * Have to drop any DLPI messages coming down from
24122 			 * arp (such as an info_req which would cause ip
24123 			 * to receive an extra info_ack if it was passed
24124 			 * through.
24125 			 */
24126 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
24127 			    (int)*(uint_t *)mp->b_rptr));
24128 			freemsg(mp);
24129 			return;
24130 		}
24131 		/* NOTREACHED */
24132 	case IRE_DB_TYPE: {
24133 		nce_t		*nce;
24134 		ill_t		*ill;
24135 		in6_addr_t	gw_addr_v6;
24136 
24137 
24138 		/*
24139 		 * This is a response back from a resolver.  It
24140 		 * consists of a message chain containing:
24141 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
24142 		 * The IRE_MBLK is the one we allocated in ip_newroute.
24143 		 * The LL_HDR_MBLK is the DLPI header to use to get
24144 		 * the attached packet, and subsequent ones for the
24145 		 * same destination, transmitted.
24146 		 */
24147 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
24148 			break;
24149 		/*
24150 		 * First, check to make sure the resolution succeeded.
24151 		 * If it failed, the second mblk will be empty.
24152 		 * If it is, free the chain, dropping the packet.
24153 		 * (We must ire_delete the ire; that frees the ire mblk)
24154 		 * We're doing this now to support PVCs for ATM; it's
24155 		 * a partial xresolv implementation. When we fully implement
24156 		 * xresolv interfaces, instead of freeing everything here
24157 		 * we'll initiate neighbor discovery.
24158 		 *
24159 		 * For v4 (ARP and other external resolvers) the resolver
24160 		 * frees the message, so no check is needed. This check
24161 		 * is required, though, for a full xresolve implementation.
24162 		 * Including this code here now both shows how external
24163 		 * resolvers can NACK a resolution request using an
24164 		 * existing design that has no specific provisions for NACKs,
24165 		 * and also takes into account that the current non-ARP
24166 		 * external resolver has been coded to use this method of
24167 		 * NACKing for all IPv6 (xresolv) cases,
24168 		 * whether our xresolv implementation is complete or not.
24169 		 *
24170 		 */
24171 		ire = (ire_t *)mp->b_rptr;
24172 		ill = ire_to_ill(ire);
24173 		mp1 = mp->b_cont;		/* dl_unitdata_req */
24174 		if (mp1->b_rptr == mp1->b_wptr) {
24175 			if (ire->ire_ipversion == IPV6_VERSION) {
24176 				/*
24177 				 * XRESOLV interface.
24178 				 */
24179 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
24180 				mutex_enter(&ire->ire_lock);
24181 				gw_addr_v6 = ire->ire_gateway_addr_v6;
24182 				mutex_exit(&ire->ire_lock);
24183 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
24184 					nce = ndp_lookup(ill,
24185 					    &ire->ire_addr_v6, B_FALSE);
24186 				} else {
24187 					nce = ndp_lookup(ill, &gw_addr_v6,
24188 					    B_FALSE);
24189 				}
24190 				if (nce != NULL) {
24191 					nce_resolv_failed(nce);
24192 					ndp_delete(nce);
24193 					NCE_REFRELE(nce);
24194 				}
24195 			}
24196 			mp->b_cont = NULL;
24197 			freemsg(mp1);		/* frees the pkt as well */
24198 			ire_delete((ire_t *)mp->b_rptr);
24199 			return;
24200 		}
24201 		/*
24202 		 * Split them into IRE_MBLK and pkt and feed it into
24203 		 * ire_add_then_send. Then in ire_add_then_send
24204 		 * the IRE will be added, and then the packet will be
24205 		 * run back through ip_wput. This time it will make
24206 		 * it to the wire.
24207 		 */
24208 		mp->b_cont = NULL;
24209 		mp = mp1->b_cont;		/* now, mp points to pkt */
24210 		mp1->b_cont = NULL;
24211 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
24212 		if (ire->ire_ipversion == IPV6_VERSION) {
24213 			/*
24214 			 * XRESOLV interface. Find the nce and put a copy
24215 			 * of the dl_unitdata_req in nce_res_mp
24216 			 */
24217 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
24218 			mutex_enter(&ire->ire_lock);
24219 			gw_addr_v6 = ire->ire_gateway_addr_v6;
24220 			mutex_exit(&ire->ire_lock);
24221 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
24222 				nce = ndp_lookup(ill, &ire->ire_addr_v6,
24223 				    B_FALSE);
24224 			} else {
24225 				nce = ndp_lookup(ill, &gw_addr_v6, B_FALSE);
24226 			}
24227 			if (nce != NULL) {
24228 				/*
24229 				 * We have to protect nce_res_mp here
24230 				 * from being accessed by other threads
24231 				 * while we change the mblk pointer.
24232 				 * Other functions will also lock the nce when
24233 				 * accessing nce_res_mp.
24234 				 *
24235 				 * The reason we change the mblk pointer
24236 				 * here rather than copying the resolved address
24237 				 * into the template is that, unlike with
24238 				 * ethernet, we have no guarantee that the
24239 				 * resolved address length will be
24240 				 * smaller than or equal to the lla length
24241 				 * with which the template was allocated,
24242 				 * (for ethernet, they're equal)
24243 				 * so we have to use the actual resolved
24244 				 * address mblk - which holds the real
24245 				 * dl_unitdata_req with the resolved address.
24246 				 *
24247 				 * Doing this is the same behavior as was
24248 				 * previously used in the v4 ARP case.
24249 				 */
24250 				mutex_enter(&nce->nce_lock);
24251 				if (nce->nce_res_mp != NULL)
24252 					freemsg(nce->nce_res_mp);
24253 				nce->nce_res_mp = mp1;
24254 				mutex_exit(&nce->nce_lock);
24255 				/*
24256 				 * We do a fastpath probe here because
24257 				 * we have resolved the address without
24258 				 * using Neighbor Discovery.
24259 				 * In the non-XRESOLV v6 case, the fastpath
24260 				 * probe is done right after neighbor
24261 				 * discovery completes.
24262 				 */
24263 				if (nce->nce_res_mp != NULL) {
24264 					int res;
24265 					nce_fastpath_list_add(nce);
24266 					res = ill_fastpath_probe(ill,
24267 					    nce->nce_res_mp);
24268 					if (res != 0 && res != EAGAIN)
24269 						nce_fastpath_list_delete(nce);
24270 				}
24271 
24272 				ire_add_then_send(q, ire, mp);
24273 				/*
24274 				 * Now we have to clean out any packets
24275 				 * that may have been queued on the nce
24276 				 * while it was waiting for address resolution
24277 				 * to complete.
24278 				 */
24279 				mutex_enter(&nce->nce_lock);
24280 				mp1 = nce->nce_qd_mp;
24281 				nce->nce_qd_mp = NULL;
24282 				mutex_exit(&nce->nce_lock);
24283 				while (mp1 != NULL) {
24284 					mblk_t *nxt_mp;
24285 					queue_t *fwdq = NULL;
24286 					ill_t   *inbound_ill;
24287 					uint_t ifindex;
24288 
24289 					nxt_mp = mp1->b_next;
24290 					mp1->b_next = NULL;
24291 					/*
24292 					 * Retrieve ifindex stored in
24293 					 * ip_rput_data_v6()
24294 					 */
24295 					ifindex =
24296 					    (uint_t)(uintptr_t)mp1->b_prev;
24297 					inbound_ill =
24298 						ill_lookup_on_ifindex(ifindex,
24299 						    B_TRUE, NULL, NULL, NULL,
24300 						    NULL);
24301 					mp1->b_prev = NULL;
24302 					if (inbound_ill != NULL)
24303 						fwdq = inbound_ill->ill_rq;
24304 
24305 					if (fwdq != NULL) {
24306 						put(fwdq, mp1);
24307 						ill_refrele(inbound_ill);
24308 					} else
24309 						put(WR(ill->ill_rq), mp1);
24310 					mp1 = nxt_mp;
24311 				}
24312 				NCE_REFRELE(nce);
24313 			} else {	/* nce is NULL; clean up */
24314 				ire_delete(ire);
24315 				freemsg(mp);
24316 				freemsg(mp1);
24317 				return;
24318 			}
24319 		} else {
24320 			ire->ire_dlureq_mp = mp1;
24321 			ire_add_then_send(q, ire, mp);
24322 		}
24323 		return;	/* All is well, the packet has been sent. */
24324 	}
24325 	default:
24326 		break;
24327 	}
24328 	if (q->q_next) {
24329 		putnext(q, mp);
24330 	} else
24331 		freemsg(mp);
24332 }
24333 
24334 /*
24335  * Process IP options in an outbound packet.  Modify the destination if there
24336  * is a source route option.
24337  * Returns non-zero if something fails in which case an ICMP error has been
24338  * sent and mp freed.
24339  */
24340 static int
24341 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
24342     boolean_t mctl_present, zoneid_t zoneid)
24343 {
24344 	ipoptp_t	opts;
24345 	uchar_t		*opt;
24346 	uint8_t		optval;
24347 	uint8_t		optlen;
24348 	ipaddr_t	dst;
24349 	intptr_t	code = 0;
24350 	mblk_t		*mp;
24351 	ire_t		*ire = NULL;
24352 
24353 	ip2dbg(("ip_wput_options\n"));
24354 	mp = ipsec_mp;
24355 	if (mctl_present) {
24356 		mp = ipsec_mp->b_cont;
24357 	}
24358 
24359 	dst = ipha->ipha_dst;
24360 	for (optval = ipoptp_first(&opts, ipha);
24361 	    optval != IPOPT_EOL;
24362 	    optval = ipoptp_next(&opts)) {
24363 		opt = opts.ipoptp_cur;
24364 		optlen = opts.ipoptp_len;
24365 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
24366 		    optval, optlen));
24367 		switch (optval) {
24368 			uint32_t off;
24369 		case IPOPT_SSRR:
24370 		case IPOPT_LSRR:
24371 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
24372 				ip1dbg((
24373 				    "ip_wput_options: bad option offset\n"));
24374 				code = (char *)&opt[IPOPT_OLEN] -
24375 				    (char *)ipha;
24376 				goto param_prob;
24377 			}
24378 			off = opt[IPOPT_OFFSET];
24379 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
24380 			    ntohl(dst)));
24381 			/*
24382 			 * For strict: verify that dst is directly
24383 			 * reachable.
24384 			 */
24385 			if (optval == IPOPT_SSRR) {
24386 				ire = ire_ftable_lookup(dst, 0, 0,
24387 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
24388 				    MATCH_IRE_TYPE);
24389 				if (ire == NULL) {
24390 					ip1dbg(("ip_wput_options: SSRR not"
24391 					    " directly reachable: 0x%x\n",
24392 					    ntohl(dst)));
24393 					goto bad_src_route;
24394 				}
24395 				ire_refrele(ire);
24396 			}
24397 			break;
24398 		case IPOPT_RR:
24399 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
24400 				ip1dbg((
24401 				    "ip_wput_options: bad option offset\n"));
24402 				code = (char *)&opt[IPOPT_OLEN] -
24403 				    (char *)ipha;
24404 				goto param_prob;
24405 			}
24406 			break;
24407 		case IPOPT_TS:
24408 			/*
24409 			 * Verify that length >=5 and that there is either
24410 			 * room for another timestamp or that the overflow
24411 			 * counter is not maxed out.
24412 			 */
24413 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
24414 			if (optlen < IPOPT_MINLEN_IT) {
24415 				goto param_prob;
24416 			}
24417 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
24418 				ip1dbg((
24419 				    "ip_wput_options: bad option offset\n"));
24420 				code = (char *)&opt[IPOPT_OFFSET] -
24421 				    (char *)ipha;
24422 				goto param_prob;
24423 			}
24424 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24425 			case IPOPT_TS_TSONLY:
24426 				off = IPOPT_TS_TIMELEN;
24427 				break;
24428 			case IPOPT_TS_TSANDADDR:
24429 			case IPOPT_TS_PRESPEC:
24430 			case IPOPT_TS_PRESPEC_RFC791:
24431 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
24432 				break;
24433 			default:
24434 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
24435 				    (char *)ipha;
24436 				goto param_prob;
24437 			}
24438 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
24439 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
24440 				/*
24441 				 * No room and the overflow counter is 15
24442 				 * already.
24443 				 */
24444 				goto param_prob;
24445 			}
24446 			break;
24447 		}
24448 	}
24449 
24450 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
24451 		return (0);
24452 
24453 	ip1dbg(("ip_wput_options: error processing IP options."));
24454 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
24455 
24456 param_prob:
24457 	/*
24458 	 * Since ip_wput() isn't close to finished, we fill
24459 	 * in enough of the header for credible error reporting.
24460 	 */
24461 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
24462 		/* Failed */
24463 		freemsg(ipsec_mp);
24464 		return (-1);
24465 	}
24466 	icmp_param_problem(q, ipsec_mp, (uint8_t)code);
24467 	return (-1);
24468 
24469 bad_src_route:
24470 	/*
24471 	 * Since ip_wput() isn't close to finished, we fill
24472 	 * in enough of the header for credible error reporting.
24473 	 */
24474 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
24475 		/* Failed */
24476 		freemsg(ipsec_mp);
24477 		return (-1);
24478 	}
24479 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED);
24480 	return (-1);
24481 }
24482 
24483 /*
24484  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
24485  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
24486  * thru /etc/system.
24487  */
24488 #define	CONN_MAXDRAINCNT	64
24489 
24490 static void
24491 conn_drain_init(void)
24492 {
24493 	int i;
24494 
24495 	conn_drain_list_cnt = conn_drain_nthreads;
24496 
24497 	if ((conn_drain_list_cnt == 0) ||
24498 	    (conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
24499 		/*
24500 		 * Default value of the number of drainers is the
24501 		 * number of cpus, subject to maximum of 8 drainers.
24502 		 */
24503 		if (boot_max_ncpus != -1)
24504 			conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
24505 		else
24506 			conn_drain_list_cnt = MIN(max_ncpus, 8);
24507 	}
24508 
24509 	conn_drain_list = kmem_zalloc(conn_drain_list_cnt * sizeof (idl_t),
24510 	    KM_SLEEP);
24511 
24512 	for (i = 0; i < conn_drain_list_cnt; i++) {
24513 		mutex_init(&conn_drain_list[i].idl_lock, NULL,
24514 		    MUTEX_DEFAULT, NULL);
24515 	}
24516 }
24517 
24518 static void
24519 conn_drain_fini(void)
24520 {
24521 	int i;
24522 
24523 	for (i = 0; i < conn_drain_list_cnt; i++)
24524 		mutex_destroy(&conn_drain_list[i].idl_lock);
24525 	kmem_free(conn_drain_list, conn_drain_list_cnt * sizeof (idl_t));
24526 	conn_drain_list = NULL;
24527 }
24528 
24529 /*
24530  * Note: For an overview of how flowcontrol is handled in IP please see the
24531  * IP Flowcontrol notes at the top of this file.
24532  *
24533  * Flow control has blocked us from proceeding. Insert the given conn in one
24534  * of the conn drain lists. These conn wq's will be qenabled later on when
24535  * STREAMS flow control does a backenable. conn_walk_drain will enable
24536  * the first conn in each of these drain lists. Each of these qenabled conns
24537  * in turn enables the next in the list, after it runs, or when it closes,
24538  * thus sustaining the drain process.
24539  *
24540  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
24541  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
24542  * running at any time, on a given conn, since there can be only 1 service proc
24543  * running on a queue at any time.
24544  */
24545 void
24546 conn_drain_insert(conn_t *connp)
24547 {
24548 	idl_t	*idl;
24549 	uint_t	index;
24550 
24551 	mutex_enter(&connp->conn_lock);
24552 	if (connp->conn_state_flags & CONN_CLOSING) {
24553 		/*
24554 		 * The conn is closing as a result of which CONN_CLOSING
24555 		 * is set. Return.
24556 		 */
24557 		mutex_exit(&connp->conn_lock);
24558 		return;
24559 	} else if (connp->conn_idl == NULL) {
24560 		/*
24561 		 * Assign the next drain list round robin. We dont' use
24562 		 * a lock, and thus it may not be strictly round robin.
24563 		 * Atomicity of load/stores is enough to make sure that
24564 		 * conn_drain_list_index is always within bounds.
24565 		 */
24566 		index = conn_drain_list_index;
24567 		ASSERT(index < conn_drain_list_cnt);
24568 		connp->conn_idl = &conn_drain_list[index];
24569 		index++;
24570 		if (index == conn_drain_list_cnt)
24571 			index = 0;
24572 		conn_drain_list_index = index;
24573 	}
24574 	mutex_exit(&connp->conn_lock);
24575 
24576 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
24577 	if ((connp->conn_drain_prev != NULL) ||
24578 	    (connp->conn_state_flags & CONN_CLOSING)) {
24579 		/*
24580 		 * The conn is already in the drain list, OR
24581 		 * the conn is closing. We need to check again for
24582 		 * the closing case again since close can happen
24583 		 * after we drop the conn_lock, and before we
24584 		 * acquire the CONN_DRAIN_LIST_LOCK.
24585 		 */
24586 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
24587 		return;
24588 	} else {
24589 		idl = connp->conn_idl;
24590 	}
24591 
24592 	/*
24593 	 * The conn is not in the drain list. Insert it at the
24594 	 * tail of the drain list. The drain list is circular
24595 	 * and doubly linked. idl_conn points to the 1st element
24596 	 * in the list.
24597 	 */
24598 	if (idl->idl_conn == NULL) {
24599 		idl->idl_conn = connp;
24600 		connp->conn_drain_next = connp;
24601 		connp->conn_drain_prev = connp;
24602 	} else {
24603 		conn_t *head = idl->idl_conn;
24604 
24605 		connp->conn_drain_next = head;
24606 		connp->conn_drain_prev = head->conn_drain_prev;
24607 		head->conn_drain_prev->conn_drain_next = connp;
24608 		head->conn_drain_prev = connp;
24609 	}
24610 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
24611 }
24612 
24613 /*
24614  * This conn is closing, and we are called from ip_close. OR
24615  * This conn has been serviced by ip_wsrv, and we need to do the tail
24616  * processing.
24617  * If this conn is part of the drain list, we may need to sustain the drain
24618  * process by qenabling the next conn in the drain list. We may also need to
24619  * remove this conn from the list, if it is done.
24620  */
24621 static void
24622 conn_drain_tail(conn_t *connp, boolean_t closing)
24623 {
24624 	idl_t *idl;
24625 
24626 	/*
24627 	 * connp->conn_idl is stable at this point, and no lock is needed
24628 	 * to check it. If we are called from ip_close, close has already
24629 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
24630 	 * called us only because conn_idl is non-null. If we are called thru
24631 	 * service, conn_idl could be null, but it cannot change because
24632 	 * service is single-threaded per queue, and there cannot be another
24633 	 * instance of service trying to call conn_drain_insert on this conn
24634 	 * now.
24635 	 */
24636 	ASSERT(!closing || (connp->conn_idl != NULL));
24637 
24638 	/*
24639 	 * If connp->conn_idl is null, the conn has not been inserted into any
24640 	 * drain list even once since creation of the conn. Just return.
24641 	 */
24642 	if (connp->conn_idl == NULL)
24643 		return;
24644 
24645 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
24646 
24647 	if (connp->conn_drain_prev == NULL) {
24648 		/* This conn is currently not in the drain list.  */
24649 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
24650 		return;
24651 	}
24652 	idl = connp->conn_idl;
24653 	if (idl->idl_conn_draining == connp) {
24654 		/*
24655 		 * This conn is the current drainer. If this is the last conn
24656 		 * in the drain list, we need to do more checks, in the 'if'
24657 		 * below. Otherwwise we need to just qenable the next conn,
24658 		 * to sustain the draining, and is handled in the 'else'
24659 		 * below.
24660 		 */
24661 		if (connp->conn_drain_next == idl->idl_conn) {
24662 			/*
24663 			 * This conn is the last in this list. This round
24664 			 * of draining is complete. If idl_repeat is set,
24665 			 * it means another flow enabling has happened from
24666 			 * the driver/streams and we need to another round
24667 			 * of draining.
24668 			 * If there are more than 2 conns in the drain list,
24669 			 * do a left rotate by 1, so that all conns except the
24670 			 * conn at the head move towards the head by 1, and the
24671 			 * the conn at the head goes to the tail. This attempts
24672 			 * a more even share for all queues that are being
24673 			 * drained.
24674 			 */
24675 			if ((connp->conn_drain_next != connp) &&
24676 			    (idl->idl_conn->conn_drain_next != connp)) {
24677 				idl->idl_conn = idl->idl_conn->conn_drain_next;
24678 			}
24679 			if (idl->idl_repeat) {
24680 				qenable(idl->idl_conn->conn_wq);
24681 				idl->idl_conn_draining = idl->idl_conn;
24682 				idl->idl_repeat = 0;
24683 			} else {
24684 				idl->idl_conn_draining = NULL;
24685 			}
24686 		} else {
24687 			/*
24688 			 * If the next queue that we are now qenable'ing,
24689 			 * is closing, it will remove itself from this list
24690 			 * and qenable the subsequent queue in ip_close().
24691 			 * Serialization is acheived thru idl_lock.
24692 			 */
24693 			qenable(connp->conn_drain_next->conn_wq);
24694 			idl->idl_conn_draining = connp->conn_drain_next;
24695 		}
24696 	}
24697 	if (!connp->conn_did_putbq || closing) {
24698 		/*
24699 		 * Remove ourself from the drain list, if we did not do
24700 		 * a putbq, or if the conn is closing.
24701 		 * Note: It is possible that q->q_first is non-null. It means
24702 		 * that these messages landed after we did a enableok() in
24703 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
24704 		 * service them.
24705 		 */
24706 		if (connp->conn_drain_next == connp) {
24707 			/* Singleton in the list */
24708 			ASSERT(connp->conn_drain_prev == connp);
24709 			idl->idl_conn = NULL;
24710 			idl->idl_conn_draining = NULL;
24711 		} else {
24712 			connp->conn_drain_prev->conn_drain_next =
24713 			    connp->conn_drain_next;
24714 			connp->conn_drain_next->conn_drain_prev =
24715 			    connp->conn_drain_prev;
24716 			if (idl->idl_conn == connp)
24717 				idl->idl_conn = connp->conn_drain_next;
24718 			ASSERT(idl->idl_conn_draining != connp);
24719 
24720 		}
24721 		connp->conn_drain_next = NULL;
24722 		connp->conn_drain_prev = NULL;
24723 	}
24724 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
24725 }
24726 
24727 /*
24728  * Write service routine. Shared perimeter entry point.
24729  * ip_wsrv can be called in any of the following ways.
24730  * 1. The device queue's messages has fallen below the low water mark
24731  *    and STREAMS has backenabled the ill_wq. We walk thru all the
24732  *    the drain lists and backenable the first conn in each list.
24733  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
24734  *    qenabled non-tcp upper layers. We start dequeing messages and call
24735  *    ip_wput for each message.
24736  */
24737 
24738 void
24739 ip_wsrv(queue_t *q)
24740 {
24741 	conn_t	*connp;
24742 	ill_t	*ill;
24743 	mblk_t	*mp;
24744 
24745 	if (q->q_next) {
24746 		ill = (ill_t *)q->q_ptr;
24747 		if (ill->ill_state_flags == 0) {
24748 			/*
24749 			 * The device flow control has opened up.
24750 			 * Walk through conn drain lists and qenable the
24751 			 * first conn in each list. This makes sense only
24752 			 * if the stream is fully plumbed and setup.
24753 			 * Hence the if check above.
24754 			 */
24755 			ip1dbg(("ip_wsrv: walking\n"));
24756 			conn_walk_drain();
24757 		}
24758 		return;
24759 	}
24760 
24761 	connp = Q_TO_CONN(q);
24762 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
24763 
24764 	/*
24765 	 * 1. Set conn_draining flag to signal that service is active.
24766 	 *
24767 	 * 2. ip_output determines whether it has been called from service,
24768 	 *    based on the last parameter. If it is IP_WSRV it concludes it
24769 	 *    has been called from service.
24770 	 *
24771 	 * 3. Message ordering is preserved by the following logic.
24772 	 *    i. A directly called ip_output (i.e. not thru service) will queue
24773 	 *    the message at the tail, if conn_draining is set (i.e. service
24774 	 *    is running) or if q->q_first is non-null.
24775 	 *
24776 	 *    ii. If ip_output is called from service, and if ip_output cannot
24777 	 *    putnext due to flow control, it does a putbq.
24778 	 *
24779 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
24780 	 *    (causing an infinite loop).
24781 	 */
24782 	ASSERT(!connp->conn_did_putbq);
24783 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
24784 		connp->conn_draining = 1;
24785 		noenable(q);
24786 		while ((mp = getq(q)) != NULL) {
24787 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
24788 			if (connp->conn_did_putbq) {
24789 				/* ip_wput did a putbq */
24790 				break;
24791 			}
24792 		}
24793 		/*
24794 		 * At this point, a thread coming down from top, calling
24795 		 * ip_wput, may end up queueing the message. We have not yet
24796 		 * enabled the queue, so ip_wsrv won't be called again.
24797 		 * To avoid this race, check q->q_first again (in the loop)
24798 		 * If the other thread queued the message before we call
24799 		 * enableok(), we will catch it in the q->q_first check.
24800 		 * If the other thread queues the message after we call
24801 		 * enableok(), ip_wsrv will be called again by STREAMS.
24802 		 */
24803 		connp->conn_draining = 0;
24804 		enableok(q);
24805 	}
24806 
24807 	/* Enable the next conn for draining */
24808 	conn_drain_tail(connp, B_FALSE);
24809 
24810 	connp->conn_did_putbq = 0;
24811 }
24812 
24813 /*
24814  * Walk the list of all conn's calling the function provided with the
24815  * specified argument for each.	 Note that this only walks conn's that
24816  * have been bound.
24817  * Applies to both IPv4 and IPv6.
24818  */
24819 static void
24820 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid)
24821 {
24822 	conn_walk_fanout_table(ipcl_udp_fanout, ipcl_udp_fanout_size,
24823 	    func, arg, zoneid);
24824 	conn_walk_fanout_table(ipcl_conn_fanout, ipcl_conn_fanout_size,
24825 	    func, arg, zoneid);
24826 	conn_walk_fanout_table(ipcl_bind_fanout, ipcl_bind_fanout_size,
24827 	    func, arg, zoneid);
24828 	conn_walk_fanout_table(ipcl_proto_fanout,
24829 	    A_CNT(ipcl_proto_fanout), func, arg, zoneid);
24830 	conn_walk_fanout_table(ipcl_proto_fanout_v6,
24831 	    A_CNT(ipcl_proto_fanout_v6), func, arg, zoneid);
24832 }
24833 
24834 /*
24835  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
24836  * of conns that need to be drained, check if drain is already in progress.
24837  * If so set the idl_repeat bit, indicating that the last conn in the list
24838  * needs to reinitiate the drain once again, for the list. If drain is not
24839  * in progress for the list, initiate the draining, by qenabling the 1st
24840  * conn in the list. The drain is self-sustaining, each qenabled conn will
24841  * in turn qenable the next conn, when it is done/blocked/closing.
24842  */
24843 static void
24844 conn_walk_drain(void)
24845 {
24846 	int i;
24847 	idl_t *idl;
24848 
24849 	IP_STAT(ip_conn_walk_drain);
24850 
24851 	for (i = 0; i < conn_drain_list_cnt; i++) {
24852 		idl = &conn_drain_list[i];
24853 		mutex_enter(&idl->idl_lock);
24854 		if (idl->idl_conn == NULL) {
24855 			mutex_exit(&idl->idl_lock);
24856 			continue;
24857 		}
24858 		/*
24859 		 * If this list is not being drained currently by
24860 		 * an ip_wsrv thread, start the process.
24861 		 */
24862 		if (idl->idl_conn_draining == NULL) {
24863 			ASSERT(idl->idl_repeat == 0);
24864 			qenable(idl->idl_conn->conn_wq);
24865 			idl->idl_conn_draining = idl->idl_conn;
24866 		} else {
24867 			idl->idl_repeat = 1;
24868 		}
24869 		mutex_exit(&idl->idl_lock);
24870 	}
24871 }
24872 
24873 /*
24874  * Walk an conn hash table of `count' buckets, calling func for each entry.
24875  */
24876 static void
24877 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
24878     zoneid_t zoneid)
24879 {
24880 	conn_t	*connp;
24881 
24882 	while (count-- > 0) {
24883 		mutex_enter(&connfp->connf_lock);
24884 		for (connp = connfp->connf_head; connp != NULL;
24885 		    connp = connp->conn_next) {
24886 			if (zoneid == GLOBAL_ZONEID ||
24887 			    zoneid == connp->conn_zoneid) {
24888 				CONN_INC_REF(connp);
24889 				mutex_exit(&connfp->connf_lock);
24890 				(*func)(connp, arg);
24891 				mutex_enter(&connfp->connf_lock);
24892 				CONN_DEC_REF(connp);
24893 			}
24894 		}
24895 		mutex_exit(&connfp->connf_lock);
24896 		connfp++;
24897 	}
24898 }
24899 
24900 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
24901 static void
24902 conn_report1(conn_t *connp, void *mp)
24903 {
24904 	char	buf1[INET6_ADDRSTRLEN];
24905 	char	buf2[INET6_ADDRSTRLEN];
24906 	uint_t	print_len, buf_len;
24907 
24908 	ASSERT(connp != NULL);
24909 
24910 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
24911 	if (buf_len <= 0)
24912 		return;
24913 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
24914 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
24915 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
24916 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
24917 	    "%5d %s/%05d %s/%05d\n",
24918 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
24919 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
24920 	    buf1, connp->conn_lport,
24921 	    buf2, connp->conn_fport);
24922 	if (print_len < buf_len) {
24923 		((mblk_t *)mp)->b_wptr += print_len;
24924 	} else {
24925 		((mblk_t *)mp)->b_wptr += buf_len;
24926 	}
24927 }
24928 
24929 /*
24930  * Named Dispatch routine to produce a formatted report on all conns
24931  * that are listed in one of the fanout tables.
24932  * This report is accessed by using the ndd utility to "get" ND variable
24933  * "ip_conn_status".
24934  */
24935 /* ARGSUSED */
24936 static int
24937 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
24938 {
24939 	(void) mi_mpprintf(mp,
24940 	    "CONN      " MI_COL_HDRPAD_STR
24941 	    "rfq      " MI_COL_HDRPAD_STR
24942 	    "stq      " MI_COL_HDRPAD_STR
24943 	    " zone local                 remote");
24944 
24945 	/*
24946 	 * Because of the ndd constraint, at most we can have 64K buffer
24947 	 * to put in all conn info.  So to be more efficient, just
24948 	 * allocate a 64K buffer here, assuming we need that large buffer.
24949 	 * This should be OK as only privileged processes can do ndd /dev/ip.
24950 	 */
24951 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
24952 		/* The following may work even if we cannot get a large buf. */
24953 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
24954 		return (0);
24955 	}
24956 
24957 	conn_walk_fanout(conn_report1, mp->b_cont, Q_TO_CONN(q)->conn_zoneid);
24958 	return (0);
24959 }
24960 
24961 /*
24962  * Determine if the ill and multicast aspects of that packets
24963  * "matches" the conn.
24964  */
24965 boolean_t
24966 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
24967     zoneid_t zoneid)
24968 {
24969 	ill_t *in_ill;
24970 	boolean_t found;
24971 	ipif_t *ipif;
24972 	ire_t *ire;
24973 	ipaddr_t dst, src;
24974 
24975 	dst = ipha->ipha_dst;
24976 	src = ipha->ipha_src;
24977 
24978 	/*
24979 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
24980 	 * unicast, broadcast and multicast reception to
24981 	 * conn_incoming_ill. conn_wantpacket itself is called
24982 	 * only for BROADCAST and multicast.
24983 	 *
24984 	 * 1) ip_rput supresses duplicate broadcasts if the ill
24985 	 *    is part of a group. Hence, we should be receiving
24986 	 *    just one copy of broadcast for the whole group.
24987 	 *    Thus, if it is part of the group the packet could
24988 	 *    come on any ill of the group and hence we need a
24989 	 *    match on the group. Otherwise, match on ill should
24990 	 *    be sufficient.
24991 	 *
24992 	 * 2) ip_rput does not suppress duplicate multicast packets.
24993 	 *    If there are two interfaces in a ill group and we have
24994 	 *    2 applications (conns) joined a multicast group G on
24995 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
24996 	 *    will give us two packets because we join G on both the
24997 	 *    interfaces rather than nominating just one interface
24998 	 *    for receiving multicast like broadcast above. So,
24999 	 *    we have to call ilg_lookup_ill to filter out duplicate
25000 	 *    copies, if ill is part of a group.
25001 	 */
25002 	in_ill = connp->conn_incoming_ill;
25003 	if (in_ill != NULL) {
25004 		if (in_ill->ill_group == NULL) {
25005 			if (in_ill != ill)
25006 				return (B_FALSE);
25007 		} else if (in_ill->ill_group != ill->ill_group) {
25008 			return (B_FALSE);
25009 		}
25010 	}
25011 
25012 	if (!CLASSD(dst)) {
25013 		if (connp->conn_zoneid == zoneid)
25014 			return (B_TRUE);
25015 		/*
25016 		 * The conn is in a different zone; we need to check that this
25017 		 * broadcast address is configured in the application's zone and
25018 		 * on one ill in the group.
25019 		 */
25020 		ipif = ipif_get_next_ipif(NULL, ill);
25021 		if (ipif == NULL)
25022 			return (B_FALSE);
25023 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
25024 		    connp->conn_zoneid, (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
25025 		ipif_refrele(ipif);
25026 		if (ire != NULL) {
25027 			ire_refrele(ire);
25028 			return (B_TRUE);
25029 		} else {
25030 			return (B_FALSE);
25031 		}
25032 	}
25033 
25034 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
25035 	    connp->conn_zoneid == zoneid) {
25036 		/*
25037 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
25038 		 * disabled, therefore we don't dispatch the multicast packet to
25039 		 * the sending zone.
25040 		 */
25041 		return (B_FALSE);
25042 	}
25043 
25044 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
25045 	    connp->conn_zoneid != zoneid) {
25046 		/*
25047 		 * Multicast packet on the loopback interface: we only match
25048 		 * conns who joined the group in the specified zone.
25049 		 */
25050 		return (B_FALSE);
25051 	}
25052 
25053 	if (connp->conn_multi_router) {
25054 		/* multicast packet and multicast router socket: send up */
25055 		return (B_TRUE);
25056 	}
25057 
25058 	mutex_enter(&connp->conn_lock);
25059 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
25060 	mutex_exit(&connp->conn_lock);
25061 	return (found);
25062 }
25063 
25064 /*
25065  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
25066  */
25067 /* ARGSUSED */
25068 static void
25069 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
25070 {
25071 	ill_t *ill = (ill_t *)q->q_ptr;
25072 	mblk_t	*mp1, *mp2;
25073 	ipif_t  *ipif;
25074 	int err = 0;
25075 	conn_t *connp = NULL;
25076 	ipsq_t	*ipsq;
25077 	arc_t	*arc;
25078 
25079 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
25080 
25081 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
25082 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
25083 
25084 	ASSERT(IAM_WRITER_ILL(ill));
25085 	mp2 = mp->b_cont;
25086 	mp->b_cont = NULL;
25087 
25088 	/*
25089 	 * We have now received the arp bringup completion message
25090 	 * from ARP. Mark the arp bringup as done. Also if the arp
25091 	 * stream has already started closing, send up the AR_ARP_CLOSING
25092 	 * ack now since ARP is waiting in close for this ack.
25093 	 */
25094 	mutex_enter(&ill->ill_lock);
25095 	ill->ill_arp_bringup_pending = 0;
25096 	if (ill->ill_arp_closing) {
25097 		mutex_exit(&ill->ill_lock);
25098 		/* Let's reuse the mp for sending the ack */
25099 		arc = (arc_t *)mp->b_rptr;
25100 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
25101 		arc->arc_cmd = AR_ARP_CLOSING;
25102 		qreply(q, mp);
25103 	} else {
25104 		mutex_exit(&ill->ill_lock);
25105 		freeb(mp);
25106 	}
25107 
25108 	/* We should have an IOCTL waiting on this. */
25109 	ipsq = ill->ill_phyint->phyint_ipsq;
25110 	ipif = ipsq->ipsq_pending_ipif;
25111 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
25112 	ASSERT(!((mp1 != NULL)  ^ (ipif != NULL)));
25113 	if (mp1 == NULL) {
25114 		/* bringup was aborted by the user */
25115 		freemsg(mp2);
25116 		return;
25117 	}
25118 	ASSERT(connp != NULL);
25119 	q = CONNP_TO_WQ(connp);
25120 	/*
25121 	 * If the DL_BIND_REQ fails, it is noted
25122 	 * in arc_name_offset.
25123 	 */
25124 	err = *((int *)mp2->b_rptr);
25125 	if (err == 0) {
25126 		if (ipif->ipif_isv6) {
25127 			if ((err = ipif_up_done_v6(ipif)) != 0)
25128 				ip0dbg(("ip_arp_done: init failed\n"));
25129 		} else {
25130 			if ((err = ipif_up_done(ipif)) != 0)
25131 				ip0dbg(("ip_arp_done: init failed\n"));
25132 		}
25133 	} else {
25134 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
25135 	}
25136 
25137 	freemsg(mp2);
25138 
25139 	if ((err == 0) && (ill->ill_up_ipifs)) {
25140 		err = ill_up_ipifs(ill, q, mp1);
25141 		if (err == EINPROGRESS)
25142 			return;
25143 	}
25144 
25145 	if (ill->ill_up_ipifs) {
25146 		ill_group_cleanup(ill);
25147 	}
25148 
25149 	/*
25150 	 * The ioctl must complete now without EINPROGRESS
25151 	 * since ipsq_pending_mp_get has removed the ioctl mblk
25152 	 * from ipsq_pending_mp. Otherwise the ioctl will be
25153 	 * stuck for ever in the ipsq.
25154 	 */
25155 	ASSERT(err != EINPROGRESS);
25156 	ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipif, ipsq);
25157 }
25158 
25159 /* Allocate the private structure */
25160 static int
25161 ip_priv_alloc(void **bufp)
25162 {
25163 	void	*buf;
25164 
25165 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
25166 		return (ENOMEM);
25167 
25168 	*bufp = buf;
25169 	return (0);
25170 }
25171 
25172 /* Function to delete the private structure */
25173 void
25174 ip_priv_free(void *buf)
25175 {
25176 	ASSERT(buf != NULL);
25177 	kmem_free(buf, sizeof (ip_priv_t));
25178 }
25179 
25180 /*
25181  * The entry point for IPPF processing.
25182  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
25183  * routine just returns.
25184  *
25185  * When called, ip_process generates an ipp_packet_t structure
25186  * which holds the state information for this packet and invokes the
25187  * the classifier (via ipp_packet_process). The classification, depending on
25188  * configured filters, results in a list of actions for this packet. Invoking
25189  * an action may cause the packet to be dropped, in which case the resulting
25190  * mblk (*mpp) is NULL. proc indicates the callout position for
25191  * this packet and ill_index is the interface this packet on or will leave
25192  * on (inbound and outbound resp.).
25193  */
25194 void
25195 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
25196 {
25197 	mblk_t		*mp;
25198 	ip_priv_t	*priv;
25199 	ipp_action_id_t	aid;
25200 	int		rc = 0;
25201 	ipp_packet_t	*pp;
25202 #define	IP_CLASS	"ip"
25203 
25204 	/* If the classifier is not loaded, return  */
25205 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
25206 		return;
25207 	}
25208 
25209 	mp = *mpp;
25210 	ASSERT(mp != NULL);
25211 
25212 	/* Allocate the packet structure */
25213 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
25214 	if (rc != 0) {
25215 		*mpp = NULL;
25216 		freemsg(mp);
25217 		return;
25218 	}
25219 
25220 	/* Allocate the private structure */
25221 	rc = ip_priv_alloc((void **)&priv);
25222 	if (rc != 0) {
25223 		*mpp = NULL;
25224 		freemsg(mp);
25225 		ipp_packet_free(pp);
25226 		return;
25227 	}
25228 	priv->proc = proc;
25229 	priv->ill_index = ill_index;
25230 	ipp_packet_set_private(pp, priv, ip_priv_free);
25231 	ipp_packet_set_data(pp, mp);
25232 
25233 	/* Invoke the classifier */
25234 	rc = ipp_packet_process(&pp);
25235 	if (pp != NULL) {
25236 		mp = ipp_packet_get_data(pp);
25237 		ipp_packet_free(pp);
25238 		if (rc != 0) {
25239 			freemsg(mp);
25240 			*mpp = NULL;
25241 		}
25242 	} else {
25243 		*mpp = NULL;
25244 	}
25245 #undef	IP_CLASS
25246 }
25247 
25248 /*
25249  * Propagate a multicast group membership operation (add/drop) on
25250  * all the interfaces crossed by the related multirt routes.
25251  * The call is considered successful if the operation succeeds
25252  * on at least one interface.
25253  */
25254 static int
25255 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
25256     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
25257     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
25258     mblk_t *first_mp)
25259 {
25260 	ire_t		*ire_gw;
25261 	irb_t		*irb;
25262 	int		error = 0;
25263 	opt_restart_t	*or;
25264 
25265 	irb = ire->ire_bucket;
25266 	ASSERT(irb != NULL);
25267 
25268 	ASSERT(DB_TYPE(first_mp) == M_CTL);
25269 
25270 	or = (opt_restart_t *)first_mp->b_rptr;
25271 	IRB_REFHOLD(irb);
25272 	for (; ire != NULL; ire = ire->ire_next) {
25273 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
25274 			continue;
25275 		if (ire->ire_addr != group)
25276 			continue;
25277 
25278 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
25279 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
25280 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE);
25281 		/* No resolver exists for the gateway; skip this ire. */
25282 		if (ire_gw == NULL)
25283 			continue;
25284 
25285 		/*
25286 		 * This function can return EINPROGRESS. If so the operation
25287 		 * will be restarted from ip_restart_optmgmt which will
25288 		 * call ip_opt_set and option processing will restart for
25289 		 * this option. So we may end up calling 'fn' more than once.
25290 		 * This requires that 'fn' is idempotent except for the
25291 		 * return value. The operation is considered a success if
25292 		 * it succeeds at least once on any one interface.
25293 		 */
25294 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
25295 		    NULL, fmode, src, first_mp);
25296 		if (error == 0)
25297 			or->or_private = CGTP_MCAST_SUCCESS;
25298 
25299 		if (ip_debug > 0) {
25300 			ulong_t	off;
25301 			char	*ksym;
25302 			ksym = kobj_getsymname((uintptr_t)fn, &off);
25303 			ip2dbg(("ip_multirt_apply_membership: "
25304 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
25305 			    "error %d [success %u]\n",
25306 			    ksym ? ksym : "?",
25307 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
25308 			    error, or->or_private));
25309 		}
25310 
25311 		ire_refrele(ire_gw);
25312 		if (error == EINPROGRESS) {
25313 			IRB_REFRELE(irb);
25314 			return (error);
25315 		}
25316 	}
25317 	IRB_REFRELE(irb);
25318 	/*
25319 	 * Consider the call as successful if we succeeded on at least
25320 	 * one interface. Otherwise, return the last encountered error.
25321 	 */
25322 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
25323 }
25324 
25325 
25326 /*
25327  * Issue a warning regarding a route crossing an interface with an
25328  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
25329  * amount of time is logged.
25330  */
25331 static void
25332 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
25333 {
25334 	hrtime_t	current = gethrtime();
25335 	char		buf[16];
25336 
25337 	/* Convert interval in ms to hrtime in ns */
25338 	if (multirt_bad_mtu_last_time +
25339 	    ((hrtime_t)ip_multirt_log_interval * (hrtime_t)1000000) <=
25340 	    current) {
25341 		cmn_err(CE_WARN, "ip: ignoring multiroute "
25342 		    "to %s, incorrect MTU %u (expected %u)\n",
25343 		    ip_dot_addr(ire->ire_addr, buf),
25344 		    ire->ire_max_frag, max_frag);
25345 
25346 		multirt_bad_mtu_last_time = current;
25347 	}
25348 }
25349 
25350 
25351 /*
25352  * Get the CGTP (multirouting) filtering status.
25353  * If 0, the CGTP hooks are transparent.
25354  */
25355 /* ARGSUSED */
25356 static int
25357 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
25358 {
25359 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
25360 
25361 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
25362 	return (0);
25363 }
25364 
25365 
25366 /*
25367  * Set the CGTP (multirouting) filtering status.
25368  * If the status is changed from active to transparent
25369  * or from transparent to active, forward the new status
25370  * to the filtering module (if loaded).
25371  */
25372 /* ARGSUSED */
25373 static int
25374 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
25375     cred_t *ioc_cr)
25376 {
25377 	long		new_value;
25378 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
25379 
25380 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
25381 	    new_value < 0 || new_value > 1) {
25382 		return (EINVAL);
25383 	}
25384 
25385 	/*
25386 	 * Do not enable CGTP filtering - thus preventing the hooks
25387 	 * from being invoked - if the version number of the
25388 	 * filtering module hooks does not match.
25389 	 */
25390 	if ((ip_cgtp_filter_ops != NULL) &&
25391 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
25392 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
25393 		    "(module hooks version %d, expecting %d)\n",
25394 		    ip_cgtp_filter_ops->cfo_filter_rev, CGTP_FILTER_REV);
25395 		return (ENOTSUP);
25396 	}
25397 
25398 	if ((!*ip_cgtp_filter_value) && new_value) {
25399 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
25400 		    ip_cgtp_filter_ops == NULL ?
25401 		    " (module not loaded)" : "");
25402 	}
25403 	if (*ip_cgtp_filter_value && (!new_value)) {
25404 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
25405 		    ip_cgtp_filter_ops == NULL ?
25406 		    " (module not loaded)" : "");
25407 	}
25408 
25409 	if (ip_cgtp_filter_ops != NULL) {
25410 		int	res;
25411 		if ((res = ip_cgtp_filter_ops->cfo_change_state(new_value))) {
25412 			return (res);
25413 		}
25414 	}
25415 
25416 	*ip_cgtp_filter_value = (boolean_t)new_value;
25417 
25418 	return (0);
25419 }
25420 
25421 
25422 /*
25423  * Return the expected CGTP hooks version number.
25424  */
25425 int
25426 ip_cgtp_filter_supported(void)
25427 {
25428 	return (ip_cgtp_filter_rev);
25429 }
25430 
25431 
25432 /*
25433  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
25434  * or by invoking this function. In the first case, the version number
25435  * of the registered structure is checked at hooks activation time
25436  * in ip_cgtp_filter_set().
25437  */
25438 int
25439 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
25440 {
25441 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
25442 		return (ENOTSUP);
25443 
25444 	ip_cgtp_filter_ops = ops;
25445 	return (0);
25446 }
25447 
25448 static squeue_func_t
25449 ip_squeue_switch(int val)
25450 {
25451 	squeue_func_t rval = squeue_fill;
25452 
25453 	switch (val) {
25454 	case IP_SQUEUE_ENTER_NODRAIN:
25455 		rval = squeue_enter_nodrain;
25456 		break;
25457 	case IP_SQUEUE_ENTER:
25458 		rval = squeue_enter;
25459 		break;
25460 	default:
25461 		break;
25462 	}
25463 	return (rval);
25464 }
25465 
25466 /* ARGSUSED */
25467 static int
25468 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
25469     caddr_t addr, cred_t *cr)
25470 {
25471 	int *v = (int *)addr;
25472 	long new_value;
25473 
25474 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
25475 		return (EINVAL);
25476 
25477 	ip_input_proc = ip_squeue_switch(new_value);
25478 	*v = new_value;
25479 	return (0);
25480 }
25481 
25482 /* ARGSUSED */
25483 static int
25484 ip_fanout_set(queue_t *q, mblk_t *mp, char *value,
25485     caddr_t addr, cred_t *cr)
25486 {
25487 	int *v = (int *)addr;
25488 	long new_value;
25489 
25490 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
25491 		return (EINVAL);
25492 
25493 	*v = new_value;
25494 	return (0);
25495 }
25496 
25497 
25498 static void
25499 ip_kstat_init(void)
25500 {
25501 	ip_named_kstat_t template = {
25502 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
25503 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
25504 		{ "inReceives",		KSTAT_DATA_UINT32, 0 },
25505 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
25506 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
25507 		{ "forwDatagrams",	KSTAT_DATA_UINT32, 0 },
25508 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
25509 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
25510 		{ "inDelivers",		KSTAT_DATA_UINT32, 0 },
25511 		{ "outRequests",	KSTAT_DATA_UINT32, 0 },
25512 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
25513 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
25514 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
25515 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
25516 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
25517 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
25518 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
25519 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
25520 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
25521 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
25522 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
25523 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
25524 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
25525 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
25526 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
25527 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
25528 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
25529 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
25530 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
25531 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
25532 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
25533 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
25534 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
25535 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
25536 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
25537 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
25538 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
25539 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
25540 	};
25541 
25542 	ip_mibkp = kstat_create("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
25543 					NUM_OF_FIELDS(ip_named_kstat_t),
25544 					0);
25545 	if (!ip_mibkp)
25546 		return;
25547 
25548 	template.forwarding.value.ui32 = WE_ARE_FORWARDING ? 1:2;
25549 	template.defaultTTL.value.ui32 = (uint32_t)ip_def_ttl;
25550 	template.reasmTimeout.value.ui32 = ip_g_frag_timeout;
25551 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
25552 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
25553 
25554 	template.netToMediaEntrySize.value.i32 =
25555 		sizeof (mib2_ipNetToMediaEntry_t);
25556 
25557 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
25558 
25559 	bcopy(&template, ip_mibkp->ks_data, sizeof (template));
25560 
25561 	ip_mibkp->ks_update = ip_kstat_update;
25562 
25563 	kstat_install(ip_mibkp);
25564 }
25565 
25566 static void
25567 ip_kstat_fini(void)
25568 {
25569 
25570 	if (ip_mibkp != NULL) {
25571 		kstat_delete(ip_mibkp);
25572 		ip_mibkp = NULL;
25573 	}
25574 }
25575 
25576 static int
25577 ip_kstat_update(kstat_t *kp, int rw)
25578 {
25579 	ip_named_kstat_t *ipkp;
25580 
25581 	if (!kp || !kp->ks_data)
25582 		return (EIO);
25583 
25584 	if (rw == KSTAT_WRITE)
25585 		return (EACCES);
25586 
25587 	ipkp = (ip_named_kstat_t *)kp->ks_data;
25588 
25589 	ipkp->forwarding.value.ui32 =		ip_mib.ipForwarding;
25590 	ipkp->defaultTTL.value.ui32 =		ip_mib.ipDefaultTTL;
25591 	ipkp->inReceives.value.ui32 =		ip_mib.ipInReceives;
25592 	ipkp->inHdrErrors.value.ui32 =		ip_mib.ipInHdrErrors;
25593 	ipkp->inAddrErrors.value.ui32 =		ip_mib.ipInAddrErrors;
25594 	ipkp->forwDatagrams.value.ui32 =	ip_mib.ipForwDatagrams;
25595 	ipkp->inUnknownProtos.value.ui32 =	ip_mib.ipInUnknownProtos;
25596 	ipkp->inDiscards.value.ui32 =		ip_mib.ipInDiscards;
25597 	ipkp->inDelivers.value.ui32 =		ip_mib.ipInDelivers;
25598 	ipkp->outRequests.value.ui32 =		ip_mib.ipOutRequests;
25599 	ipkp->outDiscards.value.ui32 =		ip_mib.ipOutDiscards;
25600 	ipkp->outNoRoutes.value.ui32 =		ip_mib.ipOutNoRoutes;
25601 	ipkp->reasmTimeout.value.ui32 =		ip_mib.ipReasmTimeout;
25602 	ipkp->reasmReqds.value.ui32 =		ip_mib.ipReasmReqds;
25603 	ipkp->reasmOKs.value.ui32 =		ip_mib.ipReasmOKs;
25604 	ipkp->reasmFails.value.ui32 =		ip_mib.ipReasmFails;
25605 	ipkp->fragOKs.value.ui32 =		ip_mib.ipFragOKs;
25606 	ipkp->fragFails.value.ui32 =		ip_mib.ipFragFails;
25607 	ipkp->fragCreates.value.ui32 =		ip_mib.ipFragCreates;
25608 
25609 	ipkp->routingDiscards.value.ui32 =	ip_mib.ipRoutingDiscards;
25610 	ipkp->inErrs.value.ui32 =		ip_mib.tcpInErrs;
25611 	ipkp->noPorts.value.ui32 =		ip_mib.udpNoPorts;
25612 	ipkp->inCksumErrs.value.ui32 =		ip_mib.ipInCksumErrs;
25613 	ipkp->reasmDuplicates.value.ui32 =	ip_mib.ipReasmDuplicates;
25614 	ipkp->reasmPartDups.value.ui32 =	ip_mib.ipReasmPartDups;
25615 	ipkp->forwProhibits.value.ui32 =	ip_mib.ipForwProhibits;
25616 	ipkp->udpInCksumErrs.value.ui32 =	ip_mib.udpInCksumErrs;
25617 	ipkp->udpInOverflows.value.ui32 =	ip_mib.udpInOverflows;
25618 	ipkp->rawipInOverflows.value.ui32 =	ip_mib.rawipInOverflows;
25619 	ipkp->ipsecInSucceeded.value.ui32 =	ip_mib.ipsecInSucceeded;
25620 	ipkp->ipsecInFailed.value.i32 =		ip_mib.ipsecInFailed;
25621 
25622 	ipkp->inIPv6.value.ui32 =		ip_mib.ipInIPv6;
25623 	ipkp->outIPv6.value.ui32 =		ip_mib.ipOutIPv6;
25624 	ipkp->outSwitchIPv6.value.ui32 =	ip_mib.ipOutSwitchIPv6;
25625 
25626 	return (0);
25627 }
25628 
25629 static void
25630 icmp_kstat_init(void)
25631 {
25632 	icmp_named_kstat_t template = {
25633 		{ "inMsgs",		KSTAT_DATA_UINT32 },
25634 		{ "inErrors",		KSTAT_DATA_UINT32 },
25635 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
25636 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
25637 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
25638 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
25639 		{ "inRedirects",	KSTAT_DATA_UINT32 },
25640 		{ "inEchos",		KSTAT_DATA_UINT32 },
25641 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
25642 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
25643 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
25644 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
25645 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
25646 		{ "outMsgs",		KSTAT_DATA_UINT32 },
25647 		{ "outErrors",		KSTAT_DATA_UINT32 },
25648 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
25649 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
25650 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
25651 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
25652 		{ "outRedirects",	KSTAT_DATA_UINT32 },
25653 		{ "outEchos",		KSTAT_DATA_UINT32 },
25654 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
25655 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
25656 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
25657 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
25658 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
25659 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
25660 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
25661 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
25662 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
25663 		{ "outDrops",		KSTAT_DATA_UINT32 },
25664 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
25665 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
25666 	};
25667 
25668 	icmp_mibkp = kstat_create("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
25669 					NUM_OF_FIELDS(icmp_named_kstat_t),
25670 					0);
25671 	if (icmp_mibkp == NULL)
25672 		return;
25673 
25674 	bcopy(&template, icmp_mibkp->ks_data, sizeof (template));
25675 
25676 	icmp_mibkp->ks_update = icmp_kstat_update;
25677 
25678 	kstat_install(icmp_mibkp);
25679 }
25680 
25681 static void
25682 icmp_kstat_fini(void)
25683 {
25684 
25685 	if (icmp_mibkp != NULL) {
25686 		kstat_delete(icmp_mibkp);
25687 		icmp_mibkp = NULL;
25688 	}
25689 }
25690 
25691 static int
25692 icmp_kstat_update(kstat_t *kp, int rw)
25693 {
25694 	icmp_named_kstat_t *icmpkp;
25695 
25696 	if ((kp == NULL) || (kp->ks_data == NULL))
25697 		return (EIO);
25698 
25699 	if (rw == KSTAT_WRITE)
25700 		return (EACCES);
25701 
25702 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
25703 
25704 	icmpkp->inMsgs.value.ui32 =		icmp_mib.icmpInMsgs;
25705 	icmpkp->inErrors.value.ui32 =		icmp_mib.icmpInErrors;
25706 	icmpkp->inDestUnreachs.value.ui32 =	icmp_mib.icmpInDestUnreachs;
25707 	icmpkp->inTimeExcds.value.ui32 =	icmp_mib.icmpInTimeExcds;
25708 	icmpkp->inParmProbs.value.ui32 =	icmp_mib.icmpInParmProbs;
25709 	icmpkp->inSrcQuenchs.value.ui32 =	icmp_mib.icmpInSrcQuenchs;
25710 	icmpkp->inRedirects.value.ui32 =	icmp_mib.icmpInRedirects;
25711 	icmpkp->inEchos.value.ui32 =		icmp_mib.icmpInEchos;
25712 	icmpkp->inEchoReps.value.ui32 =		icmp_mib.icmpInEchoReps;
25713 	icmpkp->inTimestamps.value.ui32 =	icmp_mib.icmpInTimestamps;
25714 	icmpkp->inTimestampReps.value.ui32 =	icmp_mib.icmpInTimestampReps;
25715 	icmpkp->inAddrMasks.value.ui32 =	icmp_mib.icmpInAddrMasks;
25716 	icmpkp->inAddrMaskReps.value.ui32 =	icmp_mib.icmpInAddrMaskReps;
25717 	icmpkp->outMsgs.value.ui32 =		icmp_mib.icmpOutMsgs;
25718 	icmpkp->outErrors.value.ui32 =		icmp_mib.icmpOutErrors;
25719 	icmpkp->outDestUnreachs.value.ui32 =	icmp_mib.icmpOutDestUnreachs;
25720 	icmpkp->outTimeExcds.value.ui32 =	icmp_mib.icmpOutTimeExcds;
25721 	icmpkp->outParmProbs.value.ui32 =	icmp_mib.icmpOutParmProbs;
25722 	icmpkp->outSrcQuenchs.value.ui32 =	icmp_mib.icmpOutSrcQuenchs;
25723 	icmpkp->outRedirects.value.ui32 =	icmp_mib.icmpOutRedirects;
25724 	icmpkp->outEchos.value.ui32 =		icmp_mib.icmpOutEchos;
25725 	icmpkp->outEchoReps.value.ui32 =	icmp_mib.icmpOutEchoReps;
25726 	icmpkp->outTimestamps.value.ui32 =	icmp_mib.icmpOutTimestamps;
25727 	icmpkp->outTimestampReps.value.ui32 =	icmp_mib.icmpOutTimestampReps;
25728 	icmpkp->outAddrMasks.value.ui32 =	icmp_mib.icmpOutAddrMasks;
25729 	icmpkp->outAddrMaskReps.value.ui32 =	icmp_mib.icmpOutAddrMaskReps;
25730 	icmpkp->inCksumErrs.value.ui32 =	icmp_mib.icmpInCksumErrs;
25731 	icmpkp->inUnknowns.value.ui32 =		icmp_mib.icmpInUnknowns;
25732 	icmpkp->inFragNeeded.value.ui32 =	icmp_mib.icmpInFragNeeded;
25733 	icmpkp->outFragNeeded.value.ui32 =	icmp_mib.icmpOutFragNeeded;
25734 	icmpkp->outDrops.value.ui32 =		icmp_mib.icmpOutDrops;
25735 	icmpkp->inOverflows.value.ui32 =	icmp_mib.icmpInOverflows;
25736 	icmpkp->inBadRedirects.value.ui32 =	icmp_mib.icmpInBadRedirects;
25737 
25738 	return (0);
25739 }
25740 
25741 /*
25742  * This is the fanout function for raw socket opened for SCTP.  Note
25743  * that it is called after SCTP checks that there is no socket which
25744  * wants a packet.  Then before SCTP handles this out of the blue packet,
25745  * this function is called to see if there is any raw socket for SCTP.
25746  * If there is and it is bound to the correct address, the packet will
25747  * be sent to that socket.  Note that only one raw socket can be bound to
25748  * a port.  This is assured in ipcl_sctp_hash_insert();
25749  */
25750 void
25751 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
25752     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
25753     uint_t ipif_seqid, zoneid_t zoneid)
25754 {
25755 	conn_t		*connp;
25756 	queue_t		*rq;
25757 	mblk_t		*first_mp;
25758 	boolean_t	secure;
25759 	ip6_t		*ip6h;
25760 
25761 	first_mp = mp;
25762 	if (mctl_present) {
25763 		mp = first_mp->b_cont;
25764 		secure = ipsec_in_is_secure(first_mp);
25765 		ASSERT(mp != NULL);
25766 	} else {
25767 		secure = B_FALSE;
25768 	}
25769 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
25770 
25771 	connp = ipcl_classify_raw(IPPROTO_SCTP, zoneid, ports, ipha);
25772 	if (connp == NULL) {
25773 		sctp_ootb_input(first_mp, recv_ill, ipif_seqid, zoneid,
25774 		    mctl_present);
25775 		return;
25776 	}
25777 	rq = connp->conn_rq;
25778 	if (!canputnext(rq)) {
25779 		CONN_DEC_REF(connp);
25780 		BUMP_MIB(&ip_mib, rawipInOverflows);
25781 		freemsg(first_mp);
25782 		return;
25783 	}
25784 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp) :
25785 	    CONN_INBOUND_POLICY_PRESENT_V6(connp)) || secure) {
25786 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
25787 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
25788 		if (first_mp == NULL) {
25789 			CONN_DEC_REF(connp);
25790 			return;
25791 		}
25792 	}
25793 	/*
25794 	 * We probably should not send M_CTL message up to
25795 	 * raw socket.
25796 	 */
25797 	if (mctl_present)
25798 		freeb(first_mp);
25799 
25800 	/* Initiate IPPF processing here if needed. */
25801 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) ||
25802 	    (!isv4 && IP6_IN_IPP(flags))) {
25803 		ip_process(IPP_LOCAL_IN, &mp,
25804 		    recv_ill->ill_phyint->phyint_ifindex);
25805 		if (mp == NULL) {
25806 			CONN_DEC_REF(connp);
25807 			return;
25808 		}
25809 	}
25810 
25811 	if (connp->conn_recvif || connp->conn_recvslla ||
25812 	    ((connp->conn_ipv6_recvpktinfo ||
25813 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
25814 	    (flags & IP_FF_IP6INFO))) {
25815 		int in_flags = 0;
25816 
25817 		if (connp->conn_recvif || connp->conn_ipv6_recvpktinfo) {
25818 			in_flags = IPF_RECVIF;
25819 		}
25820 		if (connp->conn_recvslla) {
25821 			in_flags |= IPF_RECVSLLA;
25822 		}
25823 		if (isv4) {
25824 			mp = ip_add_info(mp, recv_ill, in_flags);
25825 		} else {
25826 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
25827 			if (mp == NULL) {
25828 				CONN_DEC_REF(connp);
25829 				return;
25830 			}
25831 		}
25832 	}
25833 
25834 	BUMP_MIB(&ip_mib, ipInDelivers);
25835 	/*
25836 	 * We are sending the IPSEC_IN message also up. Refer
25837 	 * to comments above this function.
25838 	 */
25839 	putnext(rq, mp);
25840 	CONN_DEC_REF(connp);
25841 }
25842 
25843 /*
25844  * Martian Address Filtering [RFC 1812, Section 5.3.7]
25845  */
25846 static boolean_t
25847 ip_no_forward(ipha_t *ipha, ill_t *ill)
25848 {
25849 	ipaddr_t ip_src, ip_dst;
25850 	ire_t *src_ire = NULL;
25851 
25852 	ip_src = ntohl(ipha->ipha_src);
25853 	ip_dst = ntohl(ipha->ipha_dst);
25854 
25855 	if (ip_dst == INADDR_ANY)
25856 		goto dont_forward;
25857 
25858 	if (IN_CLASSD(ip_src))
25859 		goto dont_forward;
25860 
25861 	if ((ip_src >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
25862 		goto dont_forward;
25863 
25864 	if (IN_BADCLASS(ip_dst))
25865 		goto dont_forward;
25866 
25867 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
25868 	    ALL_ZONES, MATCH_IRE_TYPE);
25869 	if (src_ire != NULL) {
25870 		ire_refrele(src_ire);
25871 		goto dont_forward;
25872 	}
25873 
25874 	return (B_FALSE);
25875 
25876 dont_forward:
25877 	if (ip_debug > 2) {
25878 		printf("ip_no_forward: dropping packet received on %s\n",
25879 		    ill->ill_name);
25880 		pr_addr_dbg("ip_no_forward: from src %s\n",
25881 		    AF_INET, &ipha->ipha_src);
25882 		pr_addr_dbg("ip_no_forward: to dst %s\n",
25883 		    AF_INET, &ipha->ipha_dst);
25884 	}
25885 	BUMP_MIB(&ip_mib, ipForwProhibits);
25886 	return (B_TRUE);
25887 }
25888 
25889 static boolean_t
25890 ip_loopback_src_or_dst(ipha_t *ipha, ill_t *ill)
25891 {
25892 	if (((ntohl(ipha->ipha_src) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) ||
25893 	    ((ntohl(ipha->ipha_dst) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)) {
25894 		if (ip_debug > 2) {
25895 			printf("ip_loopback_src_or_dst: "
25896 			    "dropping packet received on %s\n",
25897 			    ill->ill_name);
25898 			pr_addr_dbg(
25899 			    "ip_loopback_src_or_dst: from src %s\n",
25900 			    AF_INET, &ipha->ipha_src);
25901 			pr_addr_dbg(
25902 			    "ip_loopback_src_or_dst: to dst %s\n",
25903 			    AF_INET, &ipha->ipha_dst);
25904 		}
25905 
25906 		BUMP_MIB(&ip_mib, ipInAddrErrors);
25907 		return (B_TRUE);
25908 	}
25909 	return (B_FALSE);
25910 }
25911