xref: /titanic_50/usr/src/uts/common/inet/ip/ip.c (revision 49df45665521d358380d3324f56fbc1ef143e72f)
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 #include <sys/iphada.h>
97 #include <inet/tun.h>
98 #include <inet/ipdrop.h>
99 
100 #include <sys/ethernet.h>
101 #include <net/if_types.h>
102 #include <sys/cpuvar.h>
103 
104 #include <ipp/ipp.h>
105 #include <ipp/ipp_impl.h>
106 #include <ipp/ipgpc/ipgpc.h>
107 
108 #include <sys/multidata.h>
109 #include <sys/pattr.h>
110 
111 #include <inet/ipclassifier.h>
112 #include <inet/sctp_ip.h>
113 
114 /*
115  * Values for squeue switch:
116  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
117  * IP_SQUEUE_ENTER: squeue_enter
118  * IP_SQUEUE_FILL: squeue_fill
119  */
120 int ip_squeue_enter = 2;
121 squeue_func_t ip_input_proc;
122 /*
123  * IP statistics.
124  */
125 #define	IP_STAT(x)	(ip_statistics.x.value.ui64++)
126 
127 typedef struct ip_stat {
128 	kstat_named_t	ipsec_fanout_proto;
129 	kstat_named_t	ip_udp_fannorm;
130 	kstat_named_t	ip_udp_fanmb;
131 	kstat_named_t	ip_udp_fanothers;
132 	kstat_named_t	ip_udp_fast_path;
133 	kstat_named_t	ip_udp_slow_path;
134 	kstat_named_t	ip_udp_input_err;
135 	kstat_named_t	ip_tcppullup;
136 	kstat_named_t	ip_tcpoptions;
137 	kstat_named_t	ip_multipkttcp;
138 	kstat_named_t	ip_tcp_fast_path;
139 	kstat_named_t	ip_tcp_slow_path;
140 	kstat_named_t	ip_tcp_input_error;
141 	kstat_named_t	ip_db_ref;
142 	kstat_named_t	ip_notaligned1;
143 	kstat_named_t	ip_notaligned2;
144 	kstat_named_t	ip_multimblk3;
145 	kstat_named_t	ip_multimblk4;
146 	kstat_named_t	ip_ipoptions;
147 	kstat_named_t	ip_classify_fail;
148 	kstat_named_t	ip_opt;
149 	kstat_named_t	ip_udp_rput_local;
150 	kstat_named_t	ipsec_proto_ahesp;
151 	kstat_named_t	ip_conn_flputbq;
152 	kstat_named_t	ip_conn_walk_drain;
153 	kstat_named_t   ip_out_sw_cksum;
154 	kstat_named_t   ip_in_sw_cksum;
155 	kstat_named_t   ip_trash_ire_reclaim_calls;
156 	kstat_named_t   ip_trash_ire_reclaim_success;
157 	kstat_named_t   ip_ire_arp_timer_expired;
158 	kstat_named_t   ip_ire_redirect_timer_expired;
159 	kstat_named_t	ip_ire_pmtu_timer_expired;
160 	kstat_named_t	ip_input_multi_squeue;
161 } ip_stat_t;
162 
163 static ip_stat_t ip_statistics = {
164 	{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
165 	{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
166 	{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
167 	{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
168 	{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
169 	{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
170 	{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
171 	{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
172 	{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
173 	{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
174 	{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
175 	{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
176 	{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
177 	{ "ip_db_ref",			KSTAT_DATA_UINT64 },
178 	{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
179 	{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
180 	{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
181 	{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
182 	{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
183 	{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
184 	{ "ip_opt",			KSTAT_DATA_UINT64 },
185 	{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
186 	{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
187 	{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
188 	{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
189 	{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
190 	{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
191 	{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
192 	{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
193 	{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
194 	{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
195 	{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
196 	{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
197 };
198 
199 static kstat_t *ip_kstat;
200 
201 #define	TCP6 "tcp6"
202 #define	TCP "tcp"
203 #define	SCTP "sctp"
204 #define	SCTP6 "sctp6"
205 
206 major_t TCP6_MAJ;
207 major_t TCP_MAJ;
208 major_t SCTP_MAJ;
209 major_t SCTP6_MAJ;
210 
211 int ip_poll_normal_ms = 100;
212 int ip_poll_normal_ticks = 0;
213 
214 /*
215  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
216  */
217 
218 struct listptr_s {
219 	mblk_t	*lp_head;	/* pointer to the head of the list */
220 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
221 };
222 
223 typedef struct listptr_s listptr_t;
224 
225 /*
226  * Cluster specific hooks. These should be NULL when booted as a non-cluster
227  */
228 
229 /*
230  * Hook functions to enable cluster networking
231  * On non-clustered systems these vectors must always be NULL.
232  *
233  * Hook function to Check ip specified ip address is a shared ip address
234  * in the cluster
235  *
236  */
237 int (*cl_inet_isclusterwide)(uint8_t protocol,
238     sa_family_t addr_family, uint8_t *laddrp) = NULL;
239 
240 /*
241  * Hook function to generate cluster wide ip fragment identifier
242  */
243 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
244     uint8_t *laddrp, uint8_t *faddrp) = NULL;
245 
246 /*
247  * Synchronization notes:
248  *
249  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
250  * MT level protection given by STREAMS. IP uses a combination of its own
251  * internal serialization mechanism and standard Solaris locking techniques.
252  * The internal serialization is per phyint (no IPMP) or per IPMP group.
253  * This is used to serialize plumbing operations, IPMP operations, certain
254  * multicast operations, most set ioctls, igmp/mld timers etc.
255  *
256  * Plumbing is a long sequence of operations involving message
257  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
258  * involved in plumbing operations. A natural model is to serialize these
259  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
260  * parallel without any interference. But various set ioctls on hme0 are best
261  * serialized. However if the system uses IPMP, the operations are easier if
262  * they are serialized on a per IPMP group basis since IPMP operations
263  * happen across ill's of a group. Thus the lowest common denominator is to
264  * serialize most set ioctls, multicast join/leave operations, IPMP operations
265  * igmp/mld timer operations, and processing of DLPI control messages received
266  * from drivers on a per IPMP group basis. If the system does not employ
267  * IPMP the serialization is on a per phyint basis. This serialization is
268  * provided by the ipsq_t and primitives operating on this. Details can
269  * be found in ip_if.c above the core primitives operating on ipsq_t.
270  *
271  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
272  * Simiarly lookup of an ire by a thread also returns a refheld ire.
273  * In addition ipif's and ill's referenced by the ire are also indirectly
274  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
275  * the ipif's address or netmask change as long as an ipif is refheld
276  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
277  * address of an ipif has to go through the ipsq_t. This ensures that only
278  * 1 such exclusive operation proceeds at any time on the ipif. It then
279  * deletes all ires associated with this ipif, and waits for all refcnts
280  * associated with this ipif to come down to zero. The address is changed
281  * only after the ipif has been quiesced. Then the ipif is brought up again.
282  * More details are described above the comment in ip_sioctl_flags.
283  *
284  * Packet processing is based mostly on IREs and are fully multi-threaded
285  * using standard Solaris MT techniques.
286  *
287  * There are explicit locks in IP to handle:
288  * - The ip_g_head list maintained by mi_open_link() and friends.
289  *
290  * - The reassembly data structures (one lock per hash bucket)
291  *
292  * - conn_lock is meant to protect conn_t fields. The fields actually
293  *   protected by conn_lock are documented in the conn_t definition.
294  *
295  * - ire_lock to protect some of the fields of the ire, IRE tables
296  *   (one lock per hash bucket). Refer to ip_ire.c for details.
297  *
298  * - ndp_g_lock and nce_lock for protecting NCEs.
299  *
300  * - ill_lock protects fields of the ill and ipif. Details in ip.h
301  *
302  * - ill_g_lock: This is a global reader/writer lock. Protects the following
303  *	* The AVL tree based global multi list of all ills.
304  *	* The linked list of all ipifs of an ill
305  *	* The <ill-ipsq> mapping
306  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
307  *	* The illgroup list threaded by ill_group_next.
308  *	* <ill-phyint> association
309  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
310  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
311  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
312  *   will all have to hold the ill_g_lock as writer for the actual duration
313  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
314  *   may be found in the IPMP section.
315  *
316  * - ill_lock:  This is a per ill mutex.
317  *   It protects some members of the ill and is documented below.
318  *   It also protects the <ill-ipsq> mapping
319  *   It also protects the illgroup list threaded by ill_group_next.
320  *   It also protects the <ill-phyint> assoc.
321  *   It also protects the list of ipifs hanging off the ill.
322  *
323  * - ipsq_lock: This is a per ipsq_t mutex lock.
324  *   This protects all the other members of the ipsq struct except
325  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
326  *
327  * - illgrp_lock: This is a per ill_group mutex lock.
328  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
329  *   which dictates which is the next ill in an ill_group that is to be chosen
330  *   for sending outgoing packets, through creation of an IRE_CACHE that
331  *   references this ill.
332  *
333  * - phyint_lock: This is a per phyint mutex lock. Protects just the
334  *   phyint_flags
335  *
336  * - ip_g_nd_lock: This is a global reader/writer lock.
337  *   Any call to nd_load to load a new parameter to the ND table must hold the
338  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
339  *   as reader.
340  *
341  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
342  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
343  *   uniqueness check also done atomically.
344  *
345  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
346  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
347  *   as a writer when adding or deleting elements from these lists, and
348  *   as a reader when walking these lists to send a SADB update to the
349  *   IPsec capable ills.
350  *
351  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
352  *   group list linked by ill_usesrc_grp_next. It also protects the
353  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
354  *   group is being added or deleted.  This lock is taken as a reader when
355  *   walking the list/group(eg: to get the number of members in a usesrc group).
356  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
357  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
358  *   example, it is not necessary to take this lock in the initial portion
359  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
360  *   ip_sioctl_flags since the these operations are executed exclusively and
361  *   that ensures that the "usesrc group state" cannot change. The "usesrc
362  *   group state" change can happen only in the latter part of
363  *   ip_sioctl_slifusesrc and in ill_delete.
364  *
365  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
366  *
367  * To change the <ill-phyint> association, the ill_g_lock must be held
368  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
369  * must be held.
370  *
371  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
372  * and the ill_lock of the ill in question must be held.
373  *
374  * To change the <ill-illgroup> association the ill_g_lock must be held as
375  * writer and the ill_lock of the ill in question must be held.
376  *
377  * To add or delete an ipif from the list of ipifs hanging off the ill,
378  * ill_g_lock (writer) and ill_lock must be held and the thread must be
379  * a writer on the associated ipsq,.
380  *
381  * To add or delete an ill to the system, the ill_g_lock must be held as
382  * writer and the thread must be a writer on the associated ipsq.
383  *
384  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
385  * must be a writer on the associated ipsq.
386  *
387  * Lock hierarchy
388  *
389  * Some lock hierarchy scenarios are listed below.
390  *
391  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
392  * ill_g_lock -> illgrp_lock -> ill_lock
393  * ill_g_lock -> ill_lock(s) -> phyint_lock
394  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
395  * ill_g_lock -> ip_addr_avail_lock
396  * conn_lock -> irb_lock -> ill_lock -> ire_lock
397  * ipsa_lock -> ill_g_lock -> ill_lock
398  * ill_g_lock -> ip_g_nd_lock
399  * irb_lock -> ill_lock -> ire_mrtun_lock
400  * irb_lock -> ill_lock -> ire_srcif_table_lock
401  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
402  * ipsec_capab_ills_lock -> ipsa_lock
403  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
404  *
405  * When more than 1 ill lock is needed to be held, all ill lock addresses
406  * are sorted on address and locked starting from highest addressed lock
407  * downward.
408  *
409  * IPSEC notes :
410  *
411  * IP interacts with the IPSEC code (AH/ESP) by tagging a M_CTL message
412  * in front of the actual packet. For outbound datagrams, the M_CTL
413  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
414  * information used by the IPSEC code for applying the right level of
415  * protection. The information initialized by IP in the ipsec_out_t
416  * is determined by the per-socket policy or global policy in the system.
417  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
418  * ipsec_info.h) which starts out with nothing in it. It gets filled
419  * with the right information if it goes through the AH/ESP code, which
420  * happens if the incoming packet is secure. The information initialized
421  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
422  * the policy requirements needed by per-socket policy or global policy
423  * is met or not.
424  *
425  * If there is both per-socket policy (set using setsockopt) and there
426  * is also global policy match for the 5 tuples of the socket,
427  * ipsec_override_policy() makes the decision of which one to use.
428  *
429  * For fully connected sockets i.e dst, src [addr, port] is known,
430  * conn_policy_cached is set indicating that policy has been cached.
431  * conn_in_enforce_policy may or may not be set depending on whether
432  * there is a global policy match or per-socket policy match.
433  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
434  * Once the right policy is set on the conn_t, policy cannot change for
435  * this socket. This makes life simpler for TCP (UDP ?) where
436  * re-transmissions go out with the same policy. For symmetry, policy
437  * is cached for fully connected UDP sockets also. Thus if policy is cached,
438  * it also implies that policy is latched i.e policy cannot change
439  * on these sockets. As we have the right policy on the conn, we don't
440  * have to lookup global policy for every outbound and inbound datagram
441  * and thus serving as an optimization. Note that a global policy change
442  * does not affect fully connected sockets if they have policy. If fully
443  * connected sockets did not have any policy associated with it, global
444  * policy change may affect them.
445  *
446  * IP Flow control notes:
447  *
448  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
449  * cannot be sent down to the driver by IP, because of a canput failure, IP
450  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
451  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
452  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
453  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
454  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
455  * the queued messages, and removes the conn from the drain list, if all
456  * messages were drained. It also qenables the next conn in the drain list to
457  * continue the drain process.
458  *
459  * In reality the drain list is not a single list, but a configurable number
460  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
461  * list. If the ip_wsrv of the next qenabled conn does not run, because the
462  * stream closes, ip_close takes responsibility to qenable the next conn in
463  * the drain list. The directly called ip_wput path always does a putq, if
464  * it cannot putnext. Thus synchronization problems are handled between
465  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
466  * functions that manipulate this drain list. Furthermore conn_drain_insert
467  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
468  * running on a queue at any time. conn_drain_tail can be simultaneously called
469  * from both ip_wsrv and ip_close.
470  *
471  * IPQOS notes:
472  *
473  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
474  * and IPQoS modules. IPPF includes hooks in IP at different control points
475  * (callout positions) which direct packets to IPQoS modules for policy
476  * processing. Policies, if present, are global.
477  *
478  * The callout positions are located in the following paths:
479  *		o local_in (packets destined for this host)
480  *		o local_out (packets orginating from this host )
481  *		o fwd_in  (packets forwarded by this m/c - inbound)
482  *		o fwd_out (packets forwarded by this m/c - outbound)
483  * Hooks at these callout points can be enabled/disabled using the ndd variable
484  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
485  * By default all the callout positions are enabled.
486  *
487  * Outbound (local_out)
488  * Hooks are placed in ip_wput_ire and ipsec_out_process.
489  *
490  * Inbound (local_in)
491  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
492  * TCP and UDP fanout routines.
493  *
494  * Forwarding (in and out)
495  * Hooks are placed in ip_rput_forward and ip_mrtun_forward.
496  *
497  * IP Policy Framework processing (IPPF processing)
498  * Policy processing for a packet is initiated by ip_process, which ascertains
499  * that the classifier (ipgpc) is loaded and configured, failing which the
500  * packet resumes normal processing in IP. If the clasifier is present, the
501  * packet is acted upon by one or more IPQoS modules (action instances), per
502  * filters configured in ipgpc and resumes normal IP processing thereafter.
503  * An action instance can drop a packet in course of its processing.
504  *
505  * A boolean variable, ip_policy, is used in all the fanout routines that can
506  * invoke ip_process for a packet. This variable indicates if the packet should
507  * to be sent for policy processing. The variable is set to B_TRUE by default,
508  * i.e. when the routines are invoked in the normal ip procesing path for a
509  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
510  * ip_policy is set to B_FALSE for all the routines called in these two
511  * functions because, in the former case,  we don't process loopback traffic
512  * currently while in the latter, the packets have already been processed in
513  * icmp_inbound.
514  *
515  * Zones notes:
516  *
517  * The partitioning rules for networking are as follows:
518  * 1) Packets coming from a zone must have a source address belonging to that
519  * zone.
520  * 2) Packets coming from a zone can only be sent on a physical interface on
521  * which the zone has an IP address.
522  * 3) Between two zones on the same machine, packet delivery is only allowed if
523  * there's a matching route for the destination and zone in the forwarding
524  * table.
525  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
526  * different zones can bind to the same port with the wildcard address
527  * (INADDR_ANY).
528  *
529  * The granularity of interface partitioning is at the logical interface level.
530  * Therefore, every zone has its own IP addresses, and incoming packets can be
531  * attributed to a zone unambiguously. A logical interface is placed into a zone
532  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
533  * structure. Rule (1) is implemented by modifying the source address selection
534  * algorithm so that the list of eligible addresses is filtered based on the
535  * sending process zone.
536  *
537  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
538  * across all zones, depending on their type. Here is the break-up:
539  *
540  * IRE type				Shared/exclusive
541  * --------				----------------
542  * IRE_BROADCAST			Exclusive
543  * IRE_DEFAULT (default routes)		Shared (*)
544  * IRE_LOCAL				Exclusive
545  * IRE_LOOPBACK				Exclusive
546  * IRE_PREFIX (net routes)		Shared (*)
547  * IRE_CACHE				Exclusive
548  * IRE_IF_NORESOLVER (interface routes)	Exclusive
549  * IRE_IF_RESOLVER (interface routes)	Exclusive
550  * IRE_HOST (host routes)		Shared (*)
551  *
552  * (*) A zone can only use a default or off-subnet route if the gateway is
553  * directly reachable from the zone, that is, if the gateway's address matches
554  * one of the zone's logical interfaces.
555  *
556  * Multiple zones can share a common broadcast address; typically all zones
557  * share the 255.255.255.255 address. Incoming as well as locally originated
558  * broadcast packets must be dispatched to all the zones on the broadcast
559  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
560  * since some zones may not be on the 10.16.72/24 network. To handle this, each
561  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
562  * sent to every zone that has an IRE_BROADCAST entry for the destination
563  * address on the input ill, see conn_wantpacket().
564  *
565  * Applications in different zones can join the same multicast group address.
566  * For IPv4, group memberships are per-logical interface, so they're already
567  * inherently part of a zone. For IPv6, group memberships are per-physical
568  * interface, so we distinguish IPv6 group memberships based on group address,
569  * interface and zoneid. In both cases, received multicast packets are sent to
570  * every zone for which a group membership entry exists. On IPv6 we need to
571  * check that the target zone still has an address on the receiving physical
572  * interface; it could have been removed since the application issued the
573  * IPV6_JOIN_GROUP.
574  */
575 
576 /*
577  * Squeue Fanout flags:
578  *	0: No fanout.
579  *	1: Fanout across all squeues
580  */
581 boolean_t	ip_squeue_fanout = 0;
582 
583 /*
584  * Maximum dups allowed per packet.
585  */
586 uint_t ip_max_frag_dups = 10;
587 
588 #define	IS_SIMPLE_IPH(ipha)						\
589 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
590 
591 /* RFC1122 Conformance */
592 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
593 
594 #ifdef	_BIG_ENDIAN
595 #define	IP_HDR_CSUM_TTL_ADJUST	256
596 #define	IP_TCP_CSUM_COMP	IPPROTO_TCP
597 #define	IP_UDP_CSUM_COMP	IPPROTO_UDP
598 #else
599 #define	IP_HDR_CSUM_TTL_ADJUST	1
600 #define	IP_TCP_CSUM_COMP	(IPPROTO_TCP << 8)
601 #define	IP_UDP_CSUM_COMP	(IPPROTO_UDP << 8)
602 #endif
603 
604 #define	TCP_CHECKSUM_OFFSET		16
605 #define	UDP_CHECKSUM_OFFSET		6
606 
607 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
608 
609 #define	UDPH_SIZE	8
610 
611 /* Leave room for ip_newroute to tack on the src and target addresses */
612 #define	OK_RESOLVER_MP(mp)						\
613 	((mp) && ((mp)->b_wptr - (mp)->b_rptr) >= (2 * IP_ADDR_LEN))
614 
615 static ipif_t	*conn_get_held_ipif(conn_t *, ipif_t **, int *);
616 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
617 
618 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
619 static void	ip_ipsec_out_prepend(mblk_t *, mblk_t *, ill_t *);
620 
621 static void	icmp_frag_needed(queue_t *, mblk_t *, int);
622 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
623     uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
624 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *);
625 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
626 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
627 		    ill_t *, zoneid_t);
628 static void	icmp_options_update(ipha_t *);
629 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t);
630 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t);
631 static mblk_t	*icmp_pkt_err_ok(mblk_t *);
632 static void	icmp_redirect(mblk_t *);
633 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t);
634 
635 static void	ip_arp_news(queue_t *, mblk_t *);
636 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *);
637 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
638 char		*ip_dot_addr(ipaddr_t, char *);
639 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
640 int		ip_close(queue_t *, int);
641 static char	*ip_dot_saddr(uchar_t *, char *);
642 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
643 		    boolean_t, boolean_t, ill_t *, zoneid_t);
644 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
645 		    boolean_t, boolean_t, zoneid_t);
646 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
647 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
648 static void	ip_lrput(queue_t *, mblk_t *);
649 ipaddr_t	ip_massage_options(ipha_t *);
650 static void	ip_mrtun_forward(ire_t *, ill_t *, mblk_t *);
651 ipaddr_t	ip_net_mask(ipaddr_t);
652 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, ill_t *, conn_t *);
653 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
654 		    conn_t *, uint32_t);
655 static int	ip_hdr_complete(ipha_t *, zoneid_t);
656 char		*ip_nv_lookup(nv_t *, int);
657 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
658 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
659 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
660 static boolean_t	ip_param_register(ipparam_t *, size_t, ipndp_t *,
661 			    size_t);
662 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
663 void	ip_rput(queue_t *, mblk_t *);
664 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
665 		    void *dummy_arg);
666 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
667 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *);
668 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
669 			    ire_t *);
670 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *);
671 int		ip_snmp_get(queue_t *, mblk_t *);
672 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *);
673 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *);
674 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *);
675 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *);
676 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *);
677 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *);
678 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *);
679 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *);
680 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *);
681 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *);
682 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *);
683 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *);
684 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *);
685 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *);
686 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *);
687 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *);
688 static void	ip_snmp_get2_v4(ire_t *, listptr_t []);
689 static void	ip_snmp_get2_v6_route(ire_t *, listptr_t *);
690 static int	ip_snmp_get2_v6_media(nce_t *, listptr_t *);
691 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
692 static boolean_t	ip_source_routed(ipha_t *);
693 static boolean_t	ip_source_route_included(ipha_t *);
694 
695 static void	ip_unbind(queue_t *, mblk_t *);
696 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t);
697 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int);
698 static void	ip_wput_local_options(ipha_t *);
699 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
700     zoneid_t);
701 
702 static void	conn_drain_init(void);
703 static void	conn_drain_fini(void);
704 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
705 
706 static void	conn_walk_drain(void);
707 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
708     zoneid_t);
709 
710 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
711     zoneid_t);
712 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
713     void *dummy_arg);
714 
715 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
716 
717 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
718     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
719     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
720 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
721 
722 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
723 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
724     caddr_t, cred_t *);
725 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
726     caddr_t cp, cred_t *cr);
727 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
728     cred_t *);
729 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
730     caddr_t cp, cred_t *cr);
731 static int	ip_fanout_set(queue_t *, mblk_t *, char *, caddr_t,
732     cred_t *);
733 static squeue_func_t ip_squeue_switch(int);
734 
735 static void	ip_kstat_init(void);
736 static void	ip_kstat_fini(void);
737 static int	ip_kstat_update(kstat_t *kp, int rw);
738 static void	icmp_kstat_init(void);
739 static void	icmp_kstat_fini(void);
740 static int	icmp_kstat_update(kstat_t *kp, int rw);
741 
742 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
743 
744 static boolean_t	ip_no_forward(ipha_t *, ill_t *);
745 static boolean_t	ip_loopback_src_or_dst(ipha_t *, ill_t *);
746 
747 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
748     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
749 
750 void	ip_input(ill_t *, ill_rx_ring_t *, mblk_t *, size_t);
751 
752 timeout_id_t ip_ire_expire_id;	/* IRE expiration timer. */
753 static clock_t ip_ire_arp_time_elapsed; /* Time since IRE cache last flushed */
754 static clock_t ip_ire_rd_time_elapsed;	/* ... redirect IREs last flushed */
755 static clock_t ip_ire_pmtu_time_elapsed; /* Time since path mtu increase */
756 
757 uint_t	ip_ire_default_count;	/* Number of IPv4 IRE_DEFAULT entries. */
758 uint_t	ip_ire_default_index;	/* Walking index used to mod in */
759 
760 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
761 clock_t icmp_pkt_err_last = 0;	/* Time since last icmp_pkt_err */
762 uint_t	icmp_pkt_err_sent = 0;	/* Number of packets sent in burst */
763 
764 /* How long, in seconds, we allow frags to hang around. */
765 #define	IP_FRAG_TIMEOUT	60
766 
767 time_t	ip_g_frag_timeout = IP_FRAG_TIMEOUT;
768 clock_t	ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
769 
770 /* Protected by ip_mi_lock */
771 static void	*ip_g_head;		/* Instance Data List Head */
772 kmutex_t	ip_mi_lock;		/* Lock for list of instances */
773 
774 /* Only modified during _init and _fini thus no locking is needed. */
775 caddr_t		ip_g_nd;		/* Named Dispatch List Head */
776 
777 
778 static long ip_rput_pullups;
779 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
780 
781 vmem_t *ip_minor_arena;
782 
783 /*
784  * MIB-2 stuff for SNMP (both IP and ICMP)
785  */
786 mib2_ip_t	ip_mib;
787 mib2_icmp_t	icmp_mib;
788 
789 #ifdef DEBUG
790 uint32_t ipsechw_debug = 0;
791 #endif
792 
793 kstat_t		*ip_mibkp;	/* kstat exporting ip_mib data */
794 kstat_t		*icmp_mibkp;	/* kstat exporting icmp_mib data */
795 
796 uint_t	loopback_packets = 0;
797 
798 /*
799  * Multirouting/CGTP stuff
800  */
801 cgtp_filter_ops_t	*ip_cgtp_filter_ops;	/* CGTP hooks */
802 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
803 boolean_t	ip_cgtp_filter;		/* Enable/disable CGTP hooks */
804 /* Interval (in ms) between consecutive 'bad MTU' warnings */
805 hrtime_t ip_multirt_log_interval = 1000;
806 /* Time since last warning issued. */
807 static hrtime_t	multirt_bad_mtu_last_time = 0;
808 
809 kmutex_t ip_trash_timer_lock;
810 krwlock_t ip_g_nd_lock;
811 
812 /*
813  * XXX following really should only be in a header. Would need more
814  * header and .c clean up first.
815  */
816 extern optdb_obj_t	ip_opt_obj;
817 
818 ulong_t ip_squeue_enter_unbound = 0;
819 
820 /*
821  * Named Dispatch Parameter Table.
822  * All of these are alterable, within the min/max values given, at run time.
823  */
824 static ipparam_t	lcl_param_arr[] = {
825 	/* min	max	value	name */
826 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
827 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
828 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
829 	{  0,	1,	0,	"ip_respond_to_timestamp"},
830 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
831 	{  0,	1,	1,	"ip_send_redirects"},
832 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
833 	{  0,	10,	0,	"ip_debug"},
834 	{  0,	10,	0,	"ip_mrtdebug"},
835 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
836 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
837 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
838 	{  1,	255,	255,	"ip_def_ttl" },
839 	{  0,	1,	0,	"ip_forward_src_routed"},
840 	{  0,	256,	32,	"ip_wroff_extra" },
841 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
842 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
843 	{  0,	1,	1,	"ip_path_mtu_discovery" },
844 	{  0,	240,	30,	"ip_ignore_delete_time" },
845 	{  0,	1,	0,	"ip_ignore_redirect" },
846 	{  0,	1,	1,	"ip_output_queue" },
847 	{  1,	254,	1,	"ip_broadcast_ttl" },
848 	{  0,	99999,	100,	"ip_icmp_err_interval" },
849 	{  1,	99999,	10,	"ip_icmp_err_burst" },
850 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
851 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
852 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
853 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
854 	{  0,	1,	1,	"icmp_accept_clear_messages" },
855 	{  0,	1,	1,	"igmp_accept_clear_messages" },
856 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
857 				"ip_ndp_delay_first_probe_time"},
858 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
859 				"ip_ndp_max_unicast_solicit"},
860 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
861 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
862 	{  0,	1,	0,	"ip6_forward_src_routed"},
863 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
864 	{  0,	1,	1,	"ip6_send_redirects"},
865 	{  0,	1,	0,	"ip6_ignore_redirect" },
866 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
867 
868 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
869 
870 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
871 
872 	{  0,	1,	1,	"pim_accept_clear_messages" },
873 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
874 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
875 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
876 	{  0,	15,	0,	"ip_policy_mask" },
877 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
878 	{  0,	255,	1,	"ip_multirt_ttl" },
879 	{  0,	1,	1,	"ip_multidata_outbound" },
880 #ifdef DEBUG
881 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
882 #endif
883 };
884 
885 ipparam_t	*ip_param_arr = lcl_param_arr;
886 
887 /* Extended NDP table */
888 static ipndp_t	lcl_ndp_arr[] = {
889 	/* getf			setf		data			name */
890 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ip_g_forward,
891 	    "ip_forwarding" },
892 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ipv6_forward,
893 	    "ip6_forwarding" },
894 	{  ip_ill_report,	NULL,		NULL,
895 	    "ip_ill_status" },
896 	{  ip_ipif_report,	NULL,		NULL,
897 	    "ip_ipif_status" },
898 	{  ip_ire_report,	NULL,		NULL,
899 	    "ipv4_ire_status" },
900 	{  ip_ire_report_mrtun,	NULL,		NULL,
901 	    "ipv4_mrtun_ire_status" },
902 	{  ip_ire_report_srcif,	NULL,		NULL,
903 	    "ipv4_srcif_ire_status" },
904 	{  ip_ire_report_v6,	NULL,		NULL,
905 	    "ipv6_ire_status" },
906 	{  ip_conn_report,	NULL,		NULL,
907 	    "ip_conn_status" },
908 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
909 	    "ip_rput_pullups" },
910 	{  ndp_report,		NULL,		NULL,
911 	    "ip_ndp_cache_report" },
912 	{  ip_srcid_report,	NULL,		NULL,
913 	    "ip_srcid_status" },
914 	{ ip_param_generic_get, ip_squeue_profile_set,
915 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
916 	{ ip_param_generic_get, ip_squeue_bind_set,
917 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
918 	{ ip_param_generic_get, ip_input_proc_set,
919 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
920 	{ ip_param_generic_get, ip_fanout_set,
921 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
922 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, (caddr_t)&ip_cgtp_filter,
923 	    "ip_cgtp_filter" }
924 };
925 
926 /*
927  * ip_g_forward controls IP forwarding.  It takes two values:
928  *	0: IP_FORWARD_NEVER	Don't forward packets ever.
929  *	1: IP_FORWARD_ALWAYS	Forward packets for elsewhere.
930  *
931  * RFC1122 says there must be a configuration switch to control forwarding,
932  * but that the default MUST be to not forward packets ever.  Implicit
933  * control based on configuration of multiple interfaces MUST NOT be
934  * implemented (Section 3.1).  SunOS 4.1 did provide the "automatic" capability
935  * and, in fact, it was the default.  That capability is now provided in the
936  * /etc/rc2.d/S69inet script.
937  */
938 int ip_g_forward = IP_FORWARD_DEFAULT;
939 
940 /* It also has an IPv6 counterpart. */
941 
942 int ipv6_forward = IP_FORWARD_DEFAULT;
943 
944 /* Following line is external, and in ip.h.  Normally marked with * *. */
945 #define	ip_respond_to_address_mask_broadcast ip_param_arr[0].ip_param_value
946 #define	ip_g_resp_to_echo_bcast		ip_param_arr[1].ip_param_value
947 #define	ip_g_resp_to_echo_mcast		ip_param_arr[2].ip_param_value
948 #define	ip_g_resp_to_timestamp		ip_param_arr[3].ip_param_value
949 #define	ip_g_resp_to_timestamp_bcast	ip_param_arr[4].ip_param_value
950 #define	ip_g_send_redirects		ip_param_arr[5].ip_param_value
951 #define	ip_g_forward_directed_bcast	ip_param_arr[6].ip_param_value
952 #define	ip_debug			ip_param_arr[7].ip_param_value	/* */
953 #define	ip_mrtdebug			ip_param_arr[8].ip_param_value	/* */
954 #define	ip_timer_interval		ip_param_arr[9].ip_param_value	/* */
955 #define	ip_ire_arp_interval		ip_param_arr[10].ip_param_value  /* */
956 #define	ip_ire_redir_interval		ip_param_arr[11].ip_param_value
957 #define	ip_def_ttl			ip_param_arr[12].ip_param_value
958 #define	ip_forward_src_routed		ip_param_arr[13].ip_param_value
959 #define	ip_wroff_extra			ip_param_arr[14].ip_param_value
960 #define	ip_ire_pathmtu_interval		ip_param_arr[15].ip_param_value
961 #define	ip_icmp_return			ip_param_arr[16].ip_param_value
962 #define	ip_path_mtu_discovery		ip_param_arr[17].ip_param_value /* */
963 #define	ip_ignore_delete_time		ip_param_arr[18].ip_param_value /* */
964 #define	ip_ignore_redirect		ip_param_arr[19].ip_param_value
965 #define	ip_output_queue			ip_param_arr[20].ip_param_value
966 #define	ip_broadcast_ttl		ip_param_arr[21].ip_param_value
967 #define	ip_icmp_err_interval		ip_param_arr[22].ip_param_value
968 #define	ip_icmp_err_burst		ip_param_arr[23].ip_param_value
969 #define	ip_reass_queue_bytes		ip_param_arr[24].ip_param_value
970 #define	ip_strict_dst_multihoming	ip_param_arr[25].ip_param_value
971 #define	ip_addrs_per_if			ip_param_arr[26].ip_param_value
972 #define	ipsec_override_persocket_policy	ip_param_arr[27].ip_param_value /* */
973 #define	icmp_accept_clear_messages	ip_param_arr[28].ip_param_value
974 #define	igmp_accept_clear_messages	ip_param_arr[29].ip_param_value
975 
976 /* IPv6 configuration knobs */
977 #define	delay_first_probe_time		ip_param_arr[30].ip_param_value
978 #define	max_unicast_solicit		ip_param_arr[31].ip_param_value
979 #define	ipv6_def_hops			ip_param_arr[32].ip_param_value
980 #define	ipv6_icmp_return		ip_param_arr[33].ip_param_value
981 #define	ipv6_forward_src_routed		ip_param_arr[34].ip_param_value
982 #define	ipv6_resp_echo_mcast		ip_param_arr[35].ip_param_value
983 #define	ipv6_send_redirects		ip_param_arr[36].ip_param_value
984 #define	ipv6_ignore_redirect		ip_param_arr[37].ip_param_value
985 #define	ipv6_strict_dst_multihoming	ip_param_arr[38].ip_param_value
986 #define	ip_ire_reclaim_fraction		ip_param_arr[39].ip_param_value
987 #define	ipsec_policy_log_interval	ip_param_arr[40].ip_param_value
988 #define	pim_accept_clear_messages	ip_param_arr[41].ip_param_value
989 #define	ip_ndp_unsolicit_interval	ip_param_arr[42].ip_param_value
990 #define	ip_ndp_unsolicit_count		ip_param_arr[43].ip_param_value
991 #define	ipv6_ignore_home_address_opt	ip_param_arr[44].ip_param_value
992 #define	ip_policy_mask			ip_param_arr[45].ip_param_value
993 #define	ip_multirt_resolution_interval  ip_param_arr[46].ip_param_value
994 #define	ip_multirt_ttl  		ip_param_arr[47].ip_param_value
995 #define	ip_multidata_outbound		ip_param_arr[48].ip_param_value
996 #ifdef DEBUG
997 #define	ipv6_drop_inbound_icmpv6	ip_param_arr[49].ip_param_value
998 #else
999 #define	ipv6_drop_inbound_icmpv6	0
1000 #endif
1001 
1002 
1003 /*
1004  * Table of IP ioctls encoding the various properties of the ioctl and
1005  * indexed based on the last byte of the ioctl command. Occasionally there
1006  * is a clash, and there is more than 1 ioctl with the same last byte.
1007  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1008  * ioctls are encoded in the misc table. An entry in the ndx table is
1009  * retrieved by indexing on the last byte of the ioctl command and comparing
1010  * the ioctl command with the value in the ndx table. In the event of a
1011  * mismatch the misc table is then searched sequentially for the desired
1012  * ioctl command.
1013  *
1014  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1015  */
1016 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1017 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1018 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1019 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1020 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1021 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1022 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1023 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1024 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1025 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 
1028 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1029 			MISC_CMD, ip_siocaddrt, NULL },
1030 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1031 			MISC_CMD, ip_siocdelrt, NULL },
1032 
1033 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1034 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1035 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1036 			IF_CMD, ip_sioctl_get_addr, NULL },
1037 
1038 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1039 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1040 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1041 			IPI_GET_CMD | IPI_REPL,
1042 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
1043 
1044 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1045 			IPI_PRIV | IPI_WR | IPI_REPL,
1046 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1047 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1048 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
1049 			IF_CMD, ip_sioctl_get_flags, NULL },
1050 
1051 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 
1054 	/* copyin size cannot be coded for SIOCGIFCONF */
1055 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1056 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1057 
1058 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1059 			IF_CMD, ip_sioctl_mtu, NULL },
1060 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1061 			IF_CMD, ip_sioctl_get_mtu, NULL },
1062 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1063 			IPI_GET_CMD | IPI_REPL,
1064 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1065 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1066 			IF_CMD, ip_sioctl_brdaddr, NULL },
1067 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1068 			IPI_GET_CMD | IPI_REPL,
1069 			IF_CMD, ip_sioctl_get_netmask, NULL },
1070 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1071 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1072 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1073 			IPI_GET_CMD | IPI_REPL,
1074 			IF_CMD, ip_sioctl_get_metric, NULL },
1075 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1076 			IF_CMD, ip_sioctl_metric, NULL },
1077 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 
1079 	/* See 166-168 below for extended SIOC*XARP ioctls */
1080 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1081 			MISC_CMD, ip_sioctl_arp, NULL },
1082 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1083 			MISC_CMD, ip_sioctl_arp, NULL },
1084 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1085 			MISC_CMD, ip_sioctl_arp, NULL },
1086 
1087 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1088 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1089 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1090 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1091 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1092 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1093 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1094 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1095 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1096 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1097 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 
1109 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1110 			MISC_CMD, if_unitsel, if_unitsel_restart },
1111 
1112 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1113 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1114 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1115 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1116 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1124 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1125 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1126 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1127 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1128 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1129 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1130 
1131 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1132 			IPI_PRIV | IPI_WR | IPI_MODOK,
1133 			IF_CMD, ip_sioctl_sifname, NULL },
1134 
1135 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1136 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1137 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1138 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1139 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 
1149 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1150 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1151 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1152 			IF_CMD, ip_sioctl_get_muxid, NULL },
1153 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1154 			IPI_PRIV | IPI_WR | IPI_REPL,
1155 			IF_CMD, ip_sioctl_muxid, NULL },
1156 
1157 	/* Both if and lif variants share same func */
1158 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1159 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1160 	/* Both if and lif variants share same func */
1161 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1162 			IPI_PRIV | IPI_WR | IPI_REPL,
1163 			IF_CMD, ip_sioctl_slifindex, NULL },
1164 
1165 	/* copyin size cannot be coded for SIOCGIFCONF */
1166 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1167 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1168 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1169 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1170 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1171 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1173 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1174 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1175 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1176 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1177 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1178 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1179 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1180 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1181 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1182 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1183 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1184 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1185 
1186 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1187 			IPI_PRIV | IPI_WR | IPI_REPL,
1188 			LIF_CMD, ip_sioctl_removeif,
1189 			ip_sioctl_removeif_restart },
1190 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1191 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1192 			LIF_CMD, ip_sioctl_addif, NULL },
1193 #define	SIOCLIFADDR_NDX 112
1194 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1195 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1196 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1197 			IPI_GET_CMD | IPI_REPL,
1198 			LIF_CMD, ip_sioctl_get_addr, NULL },
1199 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1200 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1201 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1202 			IPI_GET_CMD | IPI_REPL,
1203 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1204 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1205 			IPI_PRIV | IPI_WR | IPI_REPL,
1206 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1207 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1208 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1209 			LIF_CMD, ip_sioctl_get_flags, NULL },
1210 
1211 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1212 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1213 
1214 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1215 			ip_sioctl_get_lifconf, NULL },
1216 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1217 			LIF_CMD, ip_sioctl_mtu, NULL },
1218 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1219 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1220 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1221 			IPI_GET_CMD | IPI_REPL,
1222 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1223 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1224 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1225 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1226 			IPI_GET_CMD | IPI_REPL,
1227 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1228 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1229 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1230 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1231 			IPI_GET_CMD | IPI_REPL,
1232 			LIF_CMD, ip_sioctl_get_metric, NULL },
1233 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1234 			LIF_CMD, ip_sioctl_metric, NULL },
1235 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1236 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1237 			LIF_CMD, ip_sioctl_slifname,
1238 			ip_sioctl_slifname_restart },
1239 
1240 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1241 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1242 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1243 			IPI_GET_CMD | IPI_REPL,
1244 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1245 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1246 			IPI_PRIV | IPI_WR | IPI_REPL,
1247 			LIF_CMD, ip_sioctl_muxid, NULL },
1248 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1249 			IPI_GET_CMD | IPI_REPL,
1250 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1251 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1252 			IPI_PRIV | IPI_WR | IPI_REPL,
1253 			LIF_CMD, ip_sioctl_slifindex, 0 },
1254 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1255 			LIF_CMD, ip_sioctl_token, NULL },
1256 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1257 			IPI_GET_CMD | IPI_REPL,
1258 			LIF_CMD, ip_sioctl_get_token, NULL },
1259 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1260 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1261 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1262 			IPI_GET_CMD | IPI_REPL,
1263 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1264 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1265 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1266 
1267 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1268 			IPI_GET_CMD | IPI_REPL,
1269 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1270 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1271 			LIF_CMD, ip_siocdelndp_v6, NULL },
1272 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1273 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1274 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1275 			LIF_CMD, ip_siocsetndp_v6, NULL },
1276 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1277 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1278 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1279 			MISC_CMD, ip_sioctl_tonlink, NULL },
1280 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1281 			MISC_CMD, ip_sioctl_tmysite, NULL },
1282 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1283 			TUN_CMD, ip_sioctl_tunparam, NULL },
1284 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1285 			IPI_PRIV | IPI_WR,
1286 			TUN_CMD, ip_sioctl_tunparam, NULL },
1287 
1288 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1289 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1290 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1291 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1292 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1293 
1294 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1295 			IPI_PRIV | IPI_WR | IPI_REPL,
1296 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1297 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1298 			IPI_PRIV | IPI_WR | IPI_REPL,
1299 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1300 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1301 			IPI_PRIV | IPI_WR,
1302 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1303 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1304 			IPI_GET_CMD | IPI_REPL,
1305 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1306 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1307 			IPI_GET_CMD | IPI_REPL,
1308 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1309 
1310 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1311 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1312 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1313 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1314 
1315 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1316 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1317 
1318 	/* These are handled in ip_sioctl_copyin_setup itself */
1319 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1320 			MISC_CMD, NULL, NULL },
1321 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1322 			MISC_CMD, NULL, NULL },
1323 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1324 
1325 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1326 			ip_sioctl_get_lifconf, NULL },
1327 
1328 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1329 			MISC_CMD, ip_sioctl_xarp, NULL },
1330 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1331 			MISC_CMD, ip_sioctl_xarp, NULL },
1332 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1333 			MISC_CMD, ip_sioctl_xarp, NULL },
1334 
1335 	/* SIOCPOPSOCKFS is not handled by IP */
1336 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1337 
1338 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1339 			IPI_GET_CMD | IPI_REPL,
1340 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1341 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1342 			IPI_PRIV | IPI_WR | IPI_REPL,
1343 			LIF_CMD, ip_sioctl_slifzone,
1344 			ip_sioctl_slifzone_restart },
1345 	/* 172-174 are SCTP ioctls and not handled by IP */
1346 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1347 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1348 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1349 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1350 			IPI_GET_CMD, LIF_CMD,
1351 			ip_sioctl_get_lifusesrc, 0 },
1352 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1353 			IPI_PRIV | IPI_WR,
1354 			LIF_CMD, ip_sioctl_slifusesrc,
1355 			NULL },
1356 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1357 			ip_sioctl_get_lifsrcof, NULL },
1358 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1359 			MISC_CMD, ip_sioctl_msfilter, NULL },
1360 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1361 			MISC_CMD, ip_sioctl_msfilter, NULL },
1362 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1363 			MISC_CMD, ip_sioctl_msfilter, NULL },
1364 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1365 			MISC_CMD, ip_sioctl_msfilter, NULL },
1366 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1367 			ip_sioctl_set_ipmpfailback, NULL }
1368 };
1369 
1370 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1371 
1372 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1373 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1374 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1375 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1376 		TUN_CMD, ip_sioctl_tunparam, NULL },
1377 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1378 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1379 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1380 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1381 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1382 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1383 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1384 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1385 		MISC_CMD, mrt_ioctl},
1386 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1387 		MISC_CMD, mrt_ioctl},
1388 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1389 		MISC_CMD, mrt_ioctl}
1390 };
1391 
1392 int ip_misc_ioctl_count =
1393     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1394 
1395 static  idl_t *conn_drain_list;		/* The array of conn drain lists */
1396 static  uint_t conn_drain_list_cnt;	/* Total count of conn_drain_list */
1397 static  int    conn_drain_list_index;	/* Next drain_list to be used */
1398 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1399 					/* Settable in /etc/system */
1400 
1401 /* Defined in ip_ire.c */
1402 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1403 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1404 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1405 
1406 static nv_t	ire_nv_arr[] = {
1407 	{ IRE_BROADCAST, "BROADCAST" },
1408 	{ IRE_LOCAL, "LOCAL" },
1409 	{ IRE_LOOPBACK, "LOOPBACK" },
1410 	{ IRE_CACHE, "CACHE" },
1411 	{ IRE_DEFAULT, "DEFAULT" },
1412 	{ IRE_PREFIX, "PREFIX" },
1413 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1414 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1415 	{ IRE_HOST, "HOST" },
1416 	{ IRE_HOST_REDIRECT, "HOST_REDIRECT" },
1417 	{ 0 }
1418 };
1419 
1420 nv_t	*ire_nv_tbl = ire_nv_arr;
1421 
1422 /* Defined in ip_if.c, protect the list of IPsec capable ills */
1423 extern krwlock_t ipsec_capab_ills_lock;
1424 
1425 /* Packet dropper for IP IPsec processing failures */
1426 ipdropper_t ip_dropper;
1427 
1428 /* Simple ICMP IP Header Template */
1429 static ipha_t icmp_ipha = {
1430 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1431 };
1432 
1433 struct module_info ip_mod_info = {
1434 	5701, "ip", 1, INFPSZ, 65536, 1024
1435 };
1436 
1437 static struct qinit rinit = {
1438 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1439 	&ip_mod_info
1440 };
1441 
1442 static struct qinit winit = {
1443 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1444 	&ip_mod_info
1445 };
1446 
1447 static struct qinit lrinit = {
1448 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1449 	&ip_mod_info
1450 };
1451 
1452 static struct qinit lwinit = {
1453 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1454 	&ip_mod_info
1455 };
1456 
1457 struct streamtab ipinfo = {
1458 	&rinit, &winit, &lrinit, &lwinit
1459 };
1460 
1461 #ifdef	DEBUG
1462 static boolean_t skip_sctp_cksum = B_FALSE;
1463 #endif
1464 /*
1465  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1466  */
1467 mblk_t *
1468 ip_copymsg(mblk_t *mp)
1469 {
1470 	mblk_t *nmp;
1471 	ipsec_info_t *in;
1472 
1473 	if (mp->b_datap->db_type != M_CTL)
1474 		return (copymsg(mp));
1475 
1476 	in = (ipsec_info_t *)mp->b_rptr;
1477 
1478 	/*
1479 	 * Note that M_CTL is also used for delivering ICMP error messages
1480 	 * upstream to transport layers.
1481 	 */
1482 	if (in->ipsec_info_type != IPSEC_OUT &&
1483 	    in->ipsec_info_type != IPSEC_IN)
1484 		return (copymsg(mp));
1485 
1486 	nmp = copymsg(mp->b_cont);
1487 
1488 	if (in->ipsec_info_type == IPSEC_OUT)
1489 		return (ipsec_out_tag(mp, nmp));
1490 	else
1491 		return (ipsec_in_tag(mp, nmp));
1492 }
1493 
1494 /* Generate an ICMP fragmentation needed message. */
1495 static void
1496 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu)
1497 {
1498 	icmph_t	icmph;
1499 	mblk_t *first_mp;
1500 	boolean_t mctl_present;
1501 
1502 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1503 
1504 	if (!(mp = icmp_pkt_err_ok(mp))) {
1505 		if (mctl_present)
1506 			freeb(first_mp);
1507 		return;
1508 	}
1509 
1510 	bzero(&icmph, sizeof (icmph_t));
1511 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1512 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1513 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1514 	BUMP_MIB(&icmp_mib, icmpOutFragNeeded);
1515 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
1516 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present);
1517 }
1518 
1519 /*
1520  * icmp_inbound deals with ICMP messages in the following ways.
1521  *
1522  * 1) It needs to send a reply back and possibly delivering it
1523  *    to the "interested" upper clients.
1524  * 2) It needs to send it to the upper clients only.
1525  * 3) It needs to change some values in IP only.
1526  * 4) It needs to change some values in IP and upper layers e.g TCP.
1527  *
1528  * We need to accomodate icmp messages coming in clear until we get
1529  * everything secure from the wire. If icmp_accept_clear_messages
1530  * is zero we check with the global policy and act accordingly. If
1531  * it is non-zero, we accept the message without any checks. But
1532  * *this does not mean* that this will be delivered to the upper
1533  * clients. By accepting we might send replies back, change our MTU
1534  * value etc. but delivery to the ULP/clients depends on their policy
1535  * dispositions.
1536  *
1537  * We handle the above 4 cases in the context of IPSEC in the
1538  * following way :
1539  *
1540  * 1) Send the reply back in the same way as the request came in.
1541  *    If it came in encrypted, it goes out encrypted. If it came in
1542  *    clear, it goes out in clear. Thus, this will prevent chosen
1543  *    plain text attack.
1544  * 2) The client may or may not expect things to come in secure.
1545  *    If it comes in secure, the policy constraints are checked
1546  *    before delivering it to the upper layers. If it comes in
1547  *    clear, ipsec_inbound_accept_clear will decide whether to
1548  *    accept this in clear or not. In both the cases, if the returned
1549  *    message (IP header + 8 bytes) that caused the icmp message has
1550  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1551  *    sending up. If there are only 8 bytes of returned message, then
1552  *    upper client will not be notified.
1553  * 3) Check with global policy to see whether it matches the constaints.
1554  *    But this will be done only if icmp_accept_messages_in_clear is
1555  *    zero.
1556  * 4) If we need to change both in IP and ULP, then the decision taken
1557  *    while affecting the values in IP and while delivering up to TCP
1558  *    should be the same.
1559  *
1560  * 	There are two cases.
1561  *
1562  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1563  *	   failed), we will not deliver it to the ULP, even though they
1564  *	   are *willing* to accept in *clear*. This is fine as our global
1565  *	   disposition to icmp messages asks us reject the datagram.
1566  *
1567  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1568  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1569  *	   to deliver it to ULP (policy failed), it can lead to
1570  *	   consistency problems. The cases known at this time are
1571  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1572  *	   values :
1573  *
1574  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1575  *	     and Upper layer rejects. Then the communication will
1576  *	     come to a stop. This is solved by making similar decisions
1577  *	     at both levels. Currently, when we are unable to deliver
1578  *	     to the Upper Layer (due to policy failures) while IP has
1579  *	     adjusted ire_max_frag, the next outbound datagram would
1580  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1581  *	     will be with the right level of protection. Thus the right
1582  *	     value will be communicated even if we are not able to
1583  *	     communicate when we get from the wire initially. But this
1584  *	     assumes there would be at least one outbound datagram after
1585  *	     IP has adjusted its ire_max_frag value. To make things
1586  *	     simpler, we accept in clear after the validation of
1587  *	     AH/ESP headers.
1588  *
1589  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1590  *	     upper layer depending on the level of protection the upper
1591  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1592  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1593  *	     should be accepted in clear when the Upper layer expects secure.
1594  *	     Thus the communication may get aborted by some bad ICMP
1595  *	     packets.
1596  *
1597  * IPQoS Notes:
1598  * The only instance when a packet is sent for processing is when there
1599  * isn't an ICMP client and if we are interested in it.
1600  * If there is a client, IPPF processing will take place in the
1601  * ip_fanout_proto routine.
1602  *
1603  * Zones notes:
1604  * The packet is only processed in the context of the specified zone: typically
1605  * only this zone will reply to an echo request, and only interested clients in
1606  * this zone will receive a copy of the packet. This means that the caller must
1607  * call icmp_inbound() for each relevant zone.
1608  */
1609 static void
1610 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1611     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1612     ill_t *recv_ill, zoneid_t zoneid)
1613 {
1614 	icmph_t	*icmph;
1615 	ipha_t	*ipha;
1616 	int	iph_hdr_length;
1617 	int	hdr_length;
1618 	boolean_t	interested;
1619 	uint32_t	ts;
1620 	uchar_t	*wptr;
1621 	ipif_t	*ipif;
1622 	mblk_t *first_mp;
1623 	ipsec_in_t *ii;
1624 	ire_t *src_ire;
1625 	boolean_t onlink;
1626 	timestruc_t now;
1627 	uint32_t ill_index;
1628 
1629 	ASSERT(ill != NULL);
1630 
1631 	first_mp = mp;
1632 	if (mctl_present) {
1633 		mp = first_mp->b_cont;
1634 		ASSERT(mp != NULL);
1635 	}
1636 
1637 	ipha = (ipha_t *)mp->b_rptr;
1638 	if (icmp_accept_clear_messages == 0) {
1639 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1640 		    ipha, NULL, mctl_present);
1641 		if (first_mp == NULL)
1642 			return;
1643 	}
1644 	/*
1645 	 * We have accepted the ICMP message. It means that we will
1646 	 * respond to the packet if needed. It may not be delivered
1647 	 * to the upper client depending on the policy constraints
1648 	 * and the disposition in ipsec_inbound_accept_clear.
1649 	 */
1650 
1651 	ASSERT(ill != NULL);
1652 
1653 	BUMP_MIB(&icmp_mib, icmpInMsgs);
1654 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1655 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1656 		/* Last chance to get real. */
1657 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1658 			BUMP_MIB(&icmp_mib, icmpInErrors);
1659 			freemsg(first_mp);
1660 			return;
1661 		}
1662 		/* Refresh iph following the pullup. */
1663 		ipha = (ipha_t *)mp->b_rptr;
1664 	}
1665 	/* ICMP header checksum, including checksum field, should be zero. */
1666 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1667 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1668 		BUMP_MIB(&icmp_mib, icmpInCksumErrs);
1669 		freemsg(first_mp);
1670 		return;
1671 	}
1672 	/* The IP header will always be a multiple of four bytes */
1673 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1674 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1675 	    icmph->icmph_code));
1676 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1677 	/* We will set "interested" to "true" if we want a copy */
1678 	interested = B_FALSE;
1679 	switch (icmph->icmph_type) {
1680 	case ICMP_ECHO_REPLY:
1681 		BUMP_MIB(&icmp_mib, icmpInEchoReps);
1682 		break;
1683 	case ICMP_DEST_UNREACHABLE:
1684 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1685 			BUMP_MIB(&icmp_mib, icmpInFragNeeded);
1686 		interested = B_TRUE;	/* Pass up to transport */
1687 		BUMP_MIB(&icmp_mib, icmpInDestUnreachs);
1688 		break;
1689 	case ICMP_SOURCE_QUENCH:
1690 		interested = B_TRUE;	/* Pass up to transport */
1691 		BUMP_MIB(&icmp_mib, icmpInSrcQuenchs);
1692 		break;
1693 	case ICMP_REDIRECT:
1694 		if (!ip_ignore_redirect)
1695 			interested = B_TRUE;
1696 		BUMP_MIB(&icmp_mib, icmpInRedirects);
1697 		break;
1698 	case ICMP_ECHO_REQUEST:
1699 		/*
1700 		 * Whether to respond to echo requests that come in as IP
1701 		 * broadcasts or as IP multicast is subject to debate
1702 		 * (what isn't?).  We aim to please, you pick it.
1703 		 * Default is do it.
1704 		 */
1705 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1706 			/* unicast: always respond */
1707 			interested = B_TRUE;
1708 		} else if (CLASSD(ipha->ipha_dst)) {
1709 			/* multicast: respond based on tunable */
1710 			interested = ip_g_resp_to_echo_mcast;
1711 		} else if (broadcast) {
1712 			/* broadcast: respond based on tunable */
1713 			interested = ip_g_resp_to_echo_bcast;
1714 		}
1715 		BUMP_MIB(&icmp_mib, icmpInEchos);
1716 		break;
1717 	case ICMP_ROUTER_ADVERTISEMENT:
1718 	case ICMP_ROUTER_SOLICITATION:
1719 		break;
1720 	case ICMP_TIME_EXCEEDED:
1721 		interested = B_TRUE;	/* Pass up to transport */
1722 		BUMP_MIB(&icmp_mib, icmpInTimeExcds);
1723 		break;
1724 	case ICMP_PARAM_PROBLEM:
1725 		interested = B_TRUE;	/* Pass up to transport */
1726 		BUMP_MIB(&icmp_mib, icmpInParmProbs);
1727 		break;
1728 	case ICMP_TIME_STAMP_REQUEST:
1729 		/* Response to Time Stamp Requests is local policy. */
1730 		if (ip_g_resp_to_timestamp &&
1731 		    /* So is whether to respond if it was an IP broadcast. */
1732 		    (!broadcast || ip_g_resp_to_timestamp_bcast)) {
1733 			int tstamp_len = 3 * sizeof (uint32_t);
1734 
1735 			if (wptr +  tstamp_len > mp->b_wptr) {
1736 				if (!pullupmsg(mp, wptr + tstamp_len -
1737 				    mp->b_rptr)) {
1738 					BUMP_MIB(&ip_mib, ipInDiscards);
1739 					freemsg(first_mp);
1740 					return;
1741 				}
1742 				/* Refresh ipha following the pullup. */
1743 				ipha = (ipha_t *)mp->b_rptr;
1744 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1745 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1746 			}
1747 			interested = B_TRUE;
1748 		}
1749 		BUMP_MIB(&icmp_mib, icmpInTimestamps);
1750 		break;
1751 	case ICMP_TIME_STAMP_REPLY:
1752 		BUMP_MIB(&icmp_mib, icmpInTimestampReps);
1753 		break;
1754 	case ICMP_INFO_REQUEST:
1755 		/* Per RFC 1122 3.2.2.7, ignore this. */
1756 	case ICMP_INFO_REPLY:
1757 		break;
1758 	case ICMP_ADDRESS_MASK_REQUEST:
1759 		if ((ip_respond_to_address_mask_broadcast || !broadcast) &&
1760 		    /* TODO m_pullup of complete header? */
1761 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN)
1762 			interested = B_TRUE;
1763 		BUMP_MIB(&icmp_mib, icmpInAddrMasks);
1764 		break;
1765 	case ICMP_ADDRESS_MASK_REPLY:
1766 		BUMP_MIB(&icmp_mib, icmpInAddrMaskReps);
1767 		break;
1768 	default:
1769 		interested = B_TRUE;	/* Pass up to transport */
1770 		BUMP_MIB(&icmp_mib, icmpInUnknowns);
1771 		break;
1772 	}
1773 	/* See if there is an ICMP client. */
1774 	if (ipcl_proto_search(IPPROTO_ICMP) != NULL) {
1775 		/* If there is an ICMP client and we want one too, copy it. */
1776 		mblk_t *first_mp1;
1777 
1778 		if (!interested) {
1779 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1780 			    ip_policy, recv_ill, zoneid);
1781 			return;
1782 		}
1783 		first_mp1 = ip_copymsg(first_mp);
1784 		if (first_mp1 != NULL) {
1785 			ip_fanout_proto(q, first_mp1, ill, ipha,
1786 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1787 		}
1788 	} else if (!interested) {
1789 		freemsg(first_mp);
1790 		return;
1791 	} else {
1792 		/*
1793 		 * Initiate policy processing for this packet if ip_policy
1794 		 * is true.
1795 		 */
1796 		if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
1797 			ill_index = ill->ill_phyint->phyint_ifindex;
1798 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1799 			if (mp == NULL) {
1800 				if (mctl_present) {
1801 					freeb(first_mp);
1802 				}
1803 				BUMP_MIB(&icmp_mib, icmpInErrors);
1804 				return;
1805 			}
1806 		}
1807 	}
1808 	/* We want to do something with it. */
1809 	/* Check db_ref to make sure we can modify the packet. */
1810 	if (mp->b_datap->db_ref > 1) {
1811 		mblk_t	*first_mp1;
1812 
1813 		first_mp1 = ip_copymsg(first_mp);
1814 		freemsg(first_mp);
1815 		if (!first_mp1) {
1816 			BUMP_MIB(&icmp_mib, icmpOutDrops);
1817 			return;
1818 		}
1819 		first_mp = first_mp1;
1820 		if (mctl_present) {
1821 			mp = first_mp->b_cont;
1822 			ASSERT(mp != NULL);
1823 		} else {
1824 			mp = first_mp;
1825 		}
1826 		ipha = (ipha_t *)mp->b_rptr;
1827 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1828 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1829 	}
1830 	switch (icmph->icmph_type) {
1831 	case ICMP_ADDRESS_MASK_REQUEST:
1832 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1833 		if (ipif == NULL) {
1834 			freemsg(first_mp);
1835 			return;
1836 		}
1837 		/*
1838 		 * outging interface must be IPv4
1839 		 */
1840 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1841 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1842 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1843 		ipif_refrele(ipif);
1844 		BUMP_MIB(&icmp_mib, icmpOutAddrMaskReps);
1845 		break;
1846 	case ICMP_ECHO_REQUEST:
1847 		icmph->icmph_type = ICMP_ECHO_REPLY;
1848 		BUMP_MIB(&icmp_mib, icmpOutEchoReps);
1849 		break;
1850 	case ICMP_TIME_STAMP_REQUEST: {
1851 		uint32_t *tsp;
1852 
1853 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1854 		tsp = (uint32_t *)wptr;
1855 		tsp++;		/* Skip past 'originate time' */
1856 		/* Compute # of milliseconds since midnight */
1857 		gethrestime(&now);
1858 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1859 		    now.tv_nsec / (NANOSEC / MILLISEC);
1860 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1861 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1862 		BUMP_MIB(&icmp_mib, icmpOutTimestampReps);
1863 		break;
1864 	}
1865 	default:
1866 		ipha = (ipha_t *)&icmph[1];
1867 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1868 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1869 				BUMP_MIB(&ip_mib, ipInDiscards);
1870 				freemsg(first_mp);
1871 				return;
1872 			}
1873 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1874 			ipha = (ipha_t *)&icmph[1];
1875 		}
1876 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1877 			BUMP_MIB(&ip_mib, ipInDiscards);
1878 			freemsg(first_mp);
1879 			return;
1880 		}
1881 		hdr_length = IPH_HDR_LENGTH(ipha);
1882 		if (hdr_length < sizeof (ipha_t)) {
1883 			BUMP_MIB(&ip_mib, ipInDiscards);
1884 			freemsg(first_mp);
1885 			return;
1886 		}
1887 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1888 			if (!pullupmsg(mp,
1889 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1890 				BUMP_MIB(&ip_mib, ipInDiscards);
1891 				freemsg(first_mp);
1892 				return;
1893 			}
1894 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1895 			ipha = (ipha_t *)&icmph[1];
1896 		}
1897 		switch (icmph->icmph_type) {
1898 		case ICMP_REDIRECT:
1899 			/*
1900 			 * As there is no upper client to deliver, we don't
1901 			 * need the first_mp any more.
1902 			 */
1903 			if (mctl_present) {
1904 				freeb(first_mp);
1905 			}
1906 			icmp_redirect(mp);
1907 			return;
1908 		case ICMP_DEST_UNREACHABLE:
1909 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1910 				if (!icmp_inbound_too_big(icmph, ipha)) {
1911 					freemsg(first_mp);
1912 					return;
1913 				}
1914 			}
1915 			/* FALLTHRU */
1916 		default :
1917 			/*
1918 			 * IPQoS notes: Since we have already done IPQoS
1919 			 * processing we don't want to do it again in
1920 			 * the fanout routines called by
1921 			 * icmp_inbound_error_fanout, hence the last
1922 			 * argument, ip_policy, is B_FALSE.
1923 			 */
1924 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1925 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1926 			    B_FALSE, recv_ill, zoneid);
1927 		}
1928 		return;
1929 	}
1930 	/* Send out an ICMP packet */
1931 	icmph->icmph_checksum = 0;
1932 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1933 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1934 		ipif_t	*ipif_chosen;
1935 		/*
1936 		 * Make it look like it was directed to us, so we don't look
1937 		 * like a fool with a broadcast or multicast source address.
1938 		 */
1939 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1940 		/*
1941 		 * Make sure that we haven't grabbed an interface that's DOWN.
1942 		 */
1943 		if (ipif != NULL) {
1944 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1945 			    ipha->ipha_src, zoneid);
1946 			if (ipif_chosen != NULL) {
1947 				ipif_refrele(ipif);
1948 				ipif = ipif_chosen;
1949 			}
1950 		}
1951 		if (ipif == NULL) {
1952 			ip0dbg(("icmp_inbound: "
1953 			    "No source for broadcast/multicast:\n"
1954 			    "\tsrc 0x%x dst 0x%x ill %p "
1955 			    "ipif_lcl_addr 0x%x\n",
1956 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1957 			    (void *)ill,
1958 			    ill->ill_ipif->ipif_lcl_addr));
1959 			freemsg(first_mp);
1960 			return;
1961 		}
1962 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1963 		ipha->ipha_dst = ipif->ipif_src_addr;
1964 		ipif_refrele(ipif);
1965 	}
1966 	/* Reset time to live. */
1967 	ipha->ipha_ttl = ip_def_ttl;
1968 	{
1969 		/* Swap source and destination addresses */
1970 		ipaddr_t tmp;
1971 
1972 		tmp = ipha->ipha_src;
1973 		ipha->ipha_src = ipha->ipha_dst;
1974 		ipha->ipha_dst = tmp;
1975 	}
1976 	ipha->ipha_ident = 0;
1977 	if (!IS_SIMPLE_IPH(ipha))
1978 		icmp_options_update(ipha);
1979 
1980 	/*
1981 	 * ICMP echo replies should go out on the same interface
1982 	 * the request came on as probes used by in.mpathd for detecting
1983 	 * NIC failures are ECHO packets. We turn-off load spreading
1984 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
1985 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
1986 	 * function. This is in turn handled by ip_wput and ip_newroute
1987 	 * to make sure that the packet goes out on the interface it came
1988 	 * in on. If we don't turnoff load spreading, the packets might get
1989 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
1990 	 * to go out and in.mpathd would wrongly detect a failure or
1991 	 * mis-detect a NIC failure for link failure. As load spreading
1992 	 * can happen only if ill_group is not NULL, we do only for
1993 	 * that case and this does not affect the normal case.
1994 	 *
1995 	 * We turn off load spreading only on echo packets that came from
1996 	 * on-link hosts. If the interface route has been deleted, this will
1997 	 * not be enforced as we can't do much. For off-link hosts, as the
1998 	 * default routes in IPv4 does not typically have an ire_ipif
1999 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2000 	 * Moreover, expecting a default route through this interface may
2001 	 * not be correct. We use ipha_dst because of the swap above.
2002 	 */
2003 	onlink = B_FALSE;
2004 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2005 		/*
2006 		 * First, we need to make sure that it is not one of our
2007 		 * local addresses. If we set onlink when it is one of
2008 		 * our local addresses, we will end up creating IRE_CACHES
2009 		 * for one of our local addresses. Then, we will never
2010 		 * accept packets for them afterwards.
2011 		 */
2012 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2013 		    NULL, ALL_ZONES, MATCH_IRE_TYPE);
2014 		if (src_ire == NULL) {
2015 			ipif = ipif_get_next_ipif(NULL, ill);
2016 			if (ipif == NULL) {
2017 				BUMP_MIB(&ip_mib, ipInDiscards);
2018 				freemsg(mp);
2019 				return;
2020 			}
2021 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2022 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2023 			    MATCH_IRE_ILL | MATCH_IRE_TYPE);
2024 			ipif_refrele(ipif);
2025 			if (src_ire != NULL) {
2026 				onlink = B_TRUE;
2027 				ire_refrele(src_ire);
2028 			}
2029 		} else {
2030 			ire_refrele(src_ire);
2031 		}
2032 	}
2033 	if (!mctl_present) {
2034 		/*
2035 		 * This packet should go out the same way as it
2036 		 * came in i.e in clear. To make sure that global
2037 		 * policy will not be applied to this in ip_wput_ire,
2038 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2039 		 */
2040 		ASSERT(first_mp == mp);
2041 		if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
2042 			BUMP_MIB(&ip_mib, ipInDiscards);
2043 			freemsg(mp);
2044 			return;
2045 		}
2046 		ii = (ipsec_in_t *)first_mp->b_rptr;
2047 
2048 		/* This is not a secure packet */
2049 		ii->ipsec_in_secure = B_FALSE;
2050 		if (onlink) {
2051 			ii->ipsec_in_attach_if = B_TRUE;
2052 			ii->ipsec_in_ill_index =
2053 			    ill->ill_phyint->phyint_ifindex;
2054 			ii->ipsec_in_rill_index =
2055 			    recv_ill->ill_phyint->phyint_ifindex;
2056 		}
2057 		first_mp->b_cont = mp;
2058 	} else if (onlink) {
2059 		ii = (ipsec_in_t *)first_mp->b_rptr;
2060 		ii->ipsec_in_attach_if = B_TRUE;
2061 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2062 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2063 	} else {
2064 		ii = (ipsec_in_t *)first_mp->b_rptr;
2065 	}
2066 	ii->ipsec_in_zoneid = zoneid;
2067 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2068 		BUMP_MIB(&ip_mib, ipInDiscards);
2069 		return;
2070 	}
2071 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
2072 	put(WR(q), first_mp);
2073 }
2074 
2075 /* Table from RFC 1191 */
2076 static int icmp_frag_size_table[] =
2077 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2078 
2079 /*
2080  * Process received ICMP Packet too big.
2081  * After updating any IRE it does the fanout to any matching transport streams.
2082  * Assumes the message has been pulled up till the IP header that caused
2083  * the error.
2084  *
2085  * Returns B_FALSE on failure and B_TRUE on success.
2086  */
2087 static boolean_t
2088 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha)
2089 {
2090 	ire_t	*ire, *first_ire;
2091 	int	mtu;
2092 	int	hdr_length;
2093 
2094 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2095 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2096 
2097 	hdr_length = IPH_HDR_LENGTH(ipha);
2098 
2099 	first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE, NULL,
2100 	    ALL_ZONES, MATCH_IRE_TYPE);
2101 
2102 	if (!first_ire) {
2103 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2104 		    ntohl(ipha->ipha_dst)));
2105 		return (B_FALSE);
2106 	}
2107 	/* Drop if the original packet contained a source route */
2108 	if (ip_source_route_included(ipha)) {
2109 		ire_refrele(first_ire);
2110 		return (B_FALSE);
2111 	}
2112 	/* Check for MTU discovery advice as described in RFC 1191 */
2113 	mtu = ntohs(icmph->icmph_du_mtu);
2114 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2115 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2116 	    ire = ire->ire_next) {
2117 		mutex_enter(&ire->ire_lock);
2118 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2119 			/* Reduce the IRE max frag value as advised. */
2120 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2121 			ip1dbg(("Received mtu from router: %d\n", mtu));
2122 		} else {
2123 			uint32_t length;
2124 			int	i;
2125 
2126 			/*
2127 			 * Use the table from RFC 1191 to figure out
2128 			 * the next "plateau" based on the length in
2129 			 * the original IP packet.
2130 			 */
2131 			length = ntohs(ipha->ipha_length);
2132 			if (ire->ire_max_frag <= length &&
2133 			    ire->ire_max_frag >= length - hdr_length) {
2134 				/*
2135 				 * Handle broken BSD 4.2 systems that
2136 				 * return the wrong iph_length in ICMP
2137 				 * errors.
2138 				 */
2139 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2140 				    length, ire->ire_max_frag));
2141 				length -= hdr_length;
2142 			}
2143 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2144 				if (length > icmp_frag_size_table[i])
2145 					break;
2146 			}
2147 			if (i == A_CNT(icmp_frag_size_table)) {
2148 				/* Smaller than 68! */
2149 				ip1dbg(("Too big for packet size %d\n",
2150 				    length));
2151 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2152 				ire->ire_frag_flag = 0;
2153 			} else {
2154 				mtu = icmp_frag_size_table[i];
2155 				ip1dbg(("Calculated mtu %d, packet size %d, "
2156 				    "before %d", mtu, length,
2157 				    ire->ire_max_frag));
2158 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2159 				ip1dbg((", after %d\n", ire->ire_max_frag));
2160 			}
2161 			/* Record the new max frag size for the ULP. */
2162 			icmph->icmph_du_zero = 0;
2163 			icmph->icmph_du_mtu =
2164 			    htons((uint16_t)ire->ire_max_frag);
2165 		}
2166 		mutex_exit(&ire->ire_lock);
2167 	}
2168 	rw_exit(&first_ire->ire_bucket->irb_lock);
2169 	ire_refrele(first_ire);
2170 	return (B_TRUE);
2171 }
2172 
2173 /*
2174  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2175  * calls this function.
2176  */
2177 static mblk_t *
2178 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2179 {
2180 	ipha_t *ipha;
2181 	icmph_t *icmph;
2182 	ipha_t *in_ipha;
2183 	int length;
2184 
2185 	ASSERT(mp->b_datap->db_type == M_DATA);
2186 
2187 	/*
2188 	 * For Self-encapsulated packets, we added an extra IP header
2189 	 * without the options. Inner IP header is the one from which
2190 	 * the outer IP header was formed. Thus, we need to remove the
2191 	 * outer IP header. To do this, we pullup the whole message
2192 	 * and overlay whatever follows the outer IP header over the
2193 	 * outer IP header.
2194 	 */
2195 
2196 	if (!pullupmsg(mp, -1)) {
2197 		BUMP_MIB(&ip_mib, ipInDiscards);
2198 		return (NULL);
2199 	}
2200 
2201 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2202 	ipha = (ipha_t *)&icmph[1];
2203 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2204 
2205 	/*
2206 	 * The length that we want to overlay is following the inner
2207 	 * IP header. Subtracting the IP header + icmp header + outer
2208 	 * IP header's length should give us the length that we want to
2209 	 * overlay.
2210 	 */
2211 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2212 	    hdr_length;
2213 	/*
2214 	 * Overlay whatever follows the inner header over the
2215 	 * outer header.
2216 	 */
2217 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2218 
2219 	/* Set the wptr to account for the outer header */
2220 	mp->b_wptr -= hdr_length;
2221 	return (mp);
2222 }
2223 
2224 /*
2225  * Try to pass the ICMP message upstream in case the ULP cares.
2226  *
2227  * If the packet that caused the ICMP error is secure, we send
2228  * it to AH/ESP to make sure that the attached packet has a
2229  * valid association. ipha in the code below points to the
2230  * IP header of the packet that caused the error.
2231  *
2232  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2233  * in the context of IPSEC. Normally we tell the upper layer
2234  * whenever we send the ire (including ip_bind), the IPSEC header
2235  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2236  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2237  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2238  * same thing. As TCP has the IPSEC options size that needs to be
2239  * adjusted, we just pass the MTU unchanged.
2240  *
2241  * IFN could have been generated locally or by some router.
2242  *
2243  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2244  *	    This happens because IP adjusted its value of MTU on an
2245  *	    earlier IFN message and could not tell the upper layer,
2246  *	    the new adjusted value of MTU e.g. Packet was encrypted
2247  *	    or there was not enough information to fanout to upper
2248  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2249  *	    generates the IFN, where IPSEC processing has *not* been
2250  *	    done.
2251  *
2252  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2253  *	    could have generated this. This happens because ire_max_frag
2254  *	    value in IP was set to a new value, while the IPSEC processing
2255  *	    was being done and after we made the fragmentation check in
2256  *	    ip_wput_ire. Thus on return from IPSEC processing,
2257  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2258  *	    and generates the IFN. As IPSEC processing is over, we fanout
2259  *	    to AH/ESP to remove the header.
2260  *
2261  *	    In both these cases, ipsec_in_loopback will be set indicating
2262  *	    that IFN was generated locally.
2263  *
2264  * ROUTER : IFN could be secure or non-secure.
2265  *
2266  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2267  *	      packet in error has AH/ESP headers to validate the AH/ESP
2268  *	      headers. AH/ESP will verify whether there is a valid SA or
2269  *	      not and send it back. We will fanout again if we have more
2270  *	      data in the packet.
2271  *
2272  *	      If the packet in error does not have AH/ESP, we handle it
2273  *	      like any other case.
2274  *
2275  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2276  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2277  *	      for validation. AH/ESP will verify whether there is a
2278  *	      valid SA or not and send it back. We will fanout again if
2279  *	      we have more data in the packet.
2280  *
2281  *	      If the packet in error does not have AH/ESP, we handle it
2282  *	      like any other case.
2283  */
2284 static void
2285 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2286     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2287     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2288     zoneid_t zoneid)
2289 {
2290 	uint16_t *up;	/* Pointer to ports in ULP header */
2291 	uint32_t ports;	/* reversed ports for fanout */
2292 	ipha_t ripha;	/* With reversed addresses */
2293 	mblk_t *first_mp;
2294 	ipsec_in_t *ii;
2295 	tcph_t	*tcph;
2296 	conn_t	*connp;
2297 
2298 	first_mp = mp;
2299 	if (mctl_present) {
2300 		mp = first_mp->b_cont;
2301 		ASSERT(mp != NULL);
2302 
2303 		ii = (ipsec_in_t *)first_mp->b_rptr;
2304 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2305 	} else {
2306 		ii = NULL;
2307 	}
2308 
2309 	switch (ipha->ipha_protocol) {
2310 	case IPPROTO_UDP:
2311 		/*
2312 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2313 		 * transport header.
2314 		 */
2315 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2316 		    mp->b_wptr) {
2317 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2318 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2319 				BUMP_MIB(&ip_mib, ipInDiscards);
2320 				goto drop_pkt;
2321 			}
2322 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2323 			ipha = (ipha_t *)&icmph[1];
2324 		}
2325 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2326 
2327 		/*
2328 		 * Attempt to find a client stream based on port.
2329 		 * Note that we do a reverse lookup since the header is
2330 		 * in the form we sent it out.
2331 		 * The ripha header is only used for the IP_UDP_MATCH and we
2332 		 * only set the src and dst addresses and protocol.
2333 		 */
2334 		ripha.ipha_src = ipha->ipha_dst;
2335 		ripha.ipha_dst = ipha->ipha_src;
2336 		ripha.ipha_protocol = ipha->ipha_protocol;
2337 		((uint16_t *)&ports)[0] = up[1];
2338 		((uint16_t *)&ports)[1] = up[0];
2339 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2340 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2341 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2342 		    icmph->icmph_type, icmph->icmph_code));
2343 
2344 		/* Have to change db_type after any pullupmsg */
2345 		DB_TYPE(mp) = M_CTL;
2346 
2347 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2348 		    mctl_present, ip_policy, recv_ill, zoneid);
2349 		return;
2350 
2351 	case IPPROTO_TCP:
2352 		/*
2353 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2354 		 * transport header.
2355 		 */
2356 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2357 		    mp->b_wptr) {
2358 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2359 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2360 				BUMP_MIB(&ip_mib, ipInDiscards);
2361 				goto drop_pkt;
2362 			}
2363 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2364 			ipha = (ipha_t *)&icmph[1];
2365 		}
2366 		/*
2367 		 * Find a TCP client stream for this packet.
2368 		 * Note that we do a reverse lookup since the header is
2369 		 * in the form we sent it out.
2370 		 */
2371 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2372 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN);
2373 		if (connp == NULL) {
2374 			BUMP_MIB(&ip_mib, ipInDiscards);
2375 			goto drop_pkt;
2376 		}
2377 
2378 		/* Have to change db_type after any pullupmsg */
2379 		DB_TYPE(mp) = M_CTL;
2380 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2381 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2382 		return;
2383 
2384 	case IPPROTO_SCTP:
2385 		/*
2386 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2387 		 * transport header.
2388 		 */
2389 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2390 		    mp->b_wptr) {
2391 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2392 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2393 				BUMP_MIB(&ip_mib, ipInDiscards);
2394 				goto drop_pkt;
2395 			}
2396 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2397 			ipha = (ipha_t *)&icmph[1];
2398 		}
2399 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2400 		/*
2401 		 * Find a SCTP client stream for this packet.
2402 		 * Note that we do a reverse lookup since the header is
2403 		 * in the form we sent it out.
2404 		 * The ripha header is only used for the matching and we
2405 		 * only set the src and dst addresses, protocol, and version.
2406 		 */
2407 		ripha.ipha_src = ipha->ipha_dst;
2408 		ripha.ipha_dst = ipha->ipha_src;
2409 		ripha.ipha_protocol = ipha->ipha_protocol;
2410 		ripha.ipha_version_and_hdr_length =
2411 		    ipha->ipha_version_and_hdr_length;
2412 		((uint16_t *)&ports)[0] = up[1];
2413 		((uint16_t *)&ports)[1] = up[0];
2414 
2415 		/* Have to change db_type after any pullupmsg */
2416 		DB_TYPE(mp) = M_CTL;
2417 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2418 		    mctl_present, ip_policy, 0, zoneid);
2419 		return;
2420 
2421 	case IPPROTO_ESP:
2422 	case IPPROTO_AH: {
2423 		int ipsec_rc;
2424 
2425 		/*
2426 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2427 		 * We will re-use the IPSEC_IN if it is already present as
2428 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2429 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2430 		 * one and attach it in the front.
2431 		 */
2432 		if (ii != NULL) {
2433 			/*
2434 			 * ip_fanout_proto_again converts the ICMP errors
2435 			 * that come back from AH/ESP to M_DATA so that
2436 			 * if it is non-AH/ESP and we do a pullupmsg in
2437 			 * this function, it would work. Convert it back
2438 			 * to M_CTL before we send up as this is a ICMP
2439 			 * error. This could have been generated locally or
2440 			 * by some router. Validate the inner IPSEC
2441 			 * headers.
2442 			 *
2443 			 * NOTE : ill_index is used by ip_fanout_proto_again
2444 			 * to locate the ill.
2445 			 */
2446 			ASSERT(ill != NULL);
2447 			ii->ipsec_in_ill_index =
2448 			    ill->ill_phyint->phyint_ifindex;
2449 			ii->ipsec_in_rill_index =
2450 			    recv_ill->ill_phyint->phyint_ifindex;
2451 			DB_TYPE(first_mp->b_cont) = M_CTL;
2452 		} else {
2453 			/*
2454 			 * IPSEC_IN is not present. We attach a ipsec_in
2455 			 * message and send up to IPSEC for validating
2456 			 * and removing the IPSEC headers. Clear
2457 			 * ipsec_in_secure so that when we return
2458 			 * from IPSEC, we don't mistakenly think that this
2459 			 * is a secure packet came from the network.
2460 			 *
2461 			 * NOTE : ill_index is used by ip_fanout_proto_again
2462 			 * to locate the ill.
2463 			 */
2464 			ASSERT(first_mp == mp);
2465 			first_mp = ipsec_in_alloc(B_TRUE);
2466 			if (first_mp == NULL) {
2467 				freemsg(mp);
2468 				BUMP_MIB(&ip_mib, ipInDiscards);
2469 				return;
2470 			}
2471 			ii = (ipsec_in_t *)first_mp->b_rptr;
2472 
2473 			/* This is not a secure packet */
2474 			ii->ipsec_in_secure = B_FALSE;
2475 			first_mp->b_cont = mp;
2476 			DB_TYPE(mp) = M_CTL;
2477 			ASSERT(ill != NULL);
2478 			ii->ipsec_in_ill_index =
2479 			    ill->ill_phyint->phyint_ifindex;
2480 			ii->ipsec_in_rill_index =
2481 			    recv_ill->ill_phyint->phyint_ifindex;
2482 		}
2483 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2484 
2485 		if (!ipsec_loaded()) {
2486 			ip_proto_not_sup(q, first_mp, 0, zoneid);
2487 			return;
2488 		}
2489 
2490 		if (ipha->ipha_protocol == IPPROTO_ESP)
2491 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2492 		else
2493 			ipsec_rc = ipsecah_icmp_error(first_mp);
2494 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2495 			return;
2496 
2497 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2498 		return;
2499 	}
2500 	default:
2501 		/*
2502 		 * The ripha header is only used for the lookup and we
2503 		 * only set the src and dst addresses and protocol.
2504 		 */
2505 		ripha.ipha_src = ipha->ipha_dst;
2506 		ripha.ipha_dst = ipha->ipha_src;
2507 		ripha.ipha_protocol = ipha->ipha_protocol;
2508 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2509 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2510 		    ntohl(ipha->ipha_dst),
2511 		    icmph->icmph_type, icmph->icmph_code));
2512 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2513 			ipha_t *in_ipha;
2514 
2515 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2516 			    mp->b_wptr) {
2517 				if (!pullupmsg(mp, (uchar_t *)ipha +
2518 				    hdr_length + sizeof (ipha_t) -
2519 				    mp->b_rptr)) {
2520 
2521 					BUMP_MIB(&ip_mib, ipInDiscards);
2522 					goto drop_pkt;
2523 				}
2524 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2525 				ipha = (ipha_t *)&icmph[1];
2526 			}
2527 			/*
2528 			 * Caller has verified that length has to be
2529 			 * at least the size of IP header.
2530 			 */
2531 			ASSERT(hdr_length >= sizeof (ipha_t));
2532 			/*
2533 			 * Check the sanity of the inner IP header like
2534 			 * we did for the outer header.
2535 			 */
2536 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2537 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2538 				BUMP_MIB(&ip_mib, ipInDiscards);
2539 				goto drop_pkt;
2540 			}
2541 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2542 				BUMP_MIB(&ip_mib, ipInDiscards);
2543 				goto drop_pkt;
2544 			}
2545 			/* Check for Self-encapsulated tunnels */
2546 			if (in_ipha->ipha_src == ipha->ipha_src &&
2547 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2548 
2549 				mp = icmp_inbound_self_encap_error(mp,
2550 				    iph_hdr_length, hdr_length);
2551 				if (mp == NULL)
2552 					goto drop_pkt;
2553 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2554 				ipha = (ipha_t *)&icmph[1];
2555 				hdr_length = IPH_HDR_LENGTH(ipha);
2556 				/*
2557 				 * The packet in error is self-encapsualted.
2558 				 * And we are finding it further encapsulated
2559 				 * which we could not have possibly generated.
2560 				 */
2561 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2562 					BUMP_MIB(&ip_mib, ipInDiscards);
2563 					goto drop_pkt;
2564 				}
2565 				icmp_inbound_error_fanout(q, ill, first_mp,
2566 				    icmph, ipha, iph_hdr_length, hdr_length,
2567 				    mctl_present, ip_policy, recv_ill, zoneid);
2568 				return;
2569 			}
2570 		}
2571 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2572 			ipha->ipha_protocol == IPPROTO_IPV6) &&
2573 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2574 		    ii != NULL &&
2575 		    ii->ipsec_in_loopback &&
2576 		    ii->ipsec_in_secure) {
2577 			/*
2578 			 * For IP tunnels that get a looped-back
2579 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2580 			 * reported new MTU to take into account the IPsec
2581 			 * headers protecting this configured tunnel.
2582 			 *
2583 			 * This allows the tunnel module (tun.c) to blindly
2584 			 * accept the MTU reported in an ICMP "too big"
2585 			 * message.
2586 			 *
2587 			 * Non-looped back ICMP messages will just be
2588 			 * handled by the security protocols (if needed),
2589 			 * and the first subsequent packet will hit this
2590 			 * path.
2591 			 */
2592 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2593 			    ipsec_in_extra_length(first_mp));
2594 		}
2595 		/* Have to change db_type after any pullupmsg */
2596 		DB_TYPE(mp) = M_CTL;
2597 
2598 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2599 		    ip_policy, recv_ill, zoneid);
2600 		return;
2601 	}
2602 	/* NOTREACHED */
2603 drop_pkt:;
2604 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2605 	freemsg(first_mp);
2606 }
2607 
2608 /*
2609  * Common IP options parser.
2610  *
2611  * Setup routine: fill in *optp with options-parsing state, then
2612  * tail-call ipoptp_next to return the first option.
2613  */
2614 uint8_t
2615 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2616 {
2617 	uint32_t totallen; /* total length of all options */
2618 
2619 	totallen = ipha->ipha_version_and_hdr_length -
2620 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2621 	totallen <<= 2;
2622 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2623 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2624 	optp->ipoptp_flags = 0;
2625 	return (ipoptp_next(optp));
2626 }
2627 
2628 /*
2629  * Common IP options parser: extract next option.
2630  */
2631 uint8_t
2632 ipoptp_next(ipoptp_t *optp)
2633 {
2634 	uint8_t *end = optp->ipoptp_end;
2635 	uint8_t *cur = optp->ipoptp_next;
2636 	uint8_t opt, len, pointer;
2637 
2638 	/*
2639 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2640 	 * has been corrupted.
2641 	 */
2642 	ASSERT(cur <= end);
2643 
2644 	if (cur == end)
2645 		return (IPOPT_EOL);
2646 
2647 	opt = cur[IPOPT_OPTVAL];
2648 
2649 	/*
2650 	 * Skip any NOP options.
2651 	 */
2652 	while (opt == IPOPT_NOP) {
2653 		cur++;
2654 		if (cur == end)
2655 			return (IPOPT_EOL);
2656 		opt = cur[IPOPT_OPTVAL];
2657 	}
2658 
2659 	if (opt == IPOPT_EOL)
2660 		return (IPOPT_EOL);
2661 
2662 	/*
2663 	 * Option requiring a length.
2664 	 */
2665 	if ((cur + 1) >= end) {
2666 		optp->ipoptp_flags |= IPOPTP_ERROR;
2667 		return (IPOPT_EOL);
2668 	}
2669 	len = cur[IPOPT_OLEN];
2670 	if (len < 2) {
2671 		optp->ipoptp_flags |= IPOPTP_ERROR;
2672 		return (IPOPT_EOL);
2673 	}
2674 	optp->ipoptp_cur = cur;
2675 	optp->ipoptp_len = len;
2676 	optp->ipoptp_next = cur + len;
2677 	if (cur + len > end) {
2678 		optp->ipoptp_flags |= IPOPTP_ERROR;
2679 		return (IPOPT_EOL);
2680 	}
2681 
2682 	/*
2683 	 * For the options which require a pointer field, make sure
2684 	 * its there, and make sure it points to either something
2685 	 * inside this option, or the end of the option.
2686 	 */
2687 	switch (opt) {
2688 	case IPOPT_RR:
2689 	case IPOPT_TS:
2690 	case IPOPT_LSRR:
2691 	case IPOPT_SSRR:
2692 		if (len <= IPOPT_OFFSET) {
2693 			optp->ipoptp_flags |= IPOPTP_ERROR;
2694 			return (opt);
2695 		}
2696 		pointer = cur[IPOPT_OFFSET];
2697 		if (pointer - 1 > len) {
2698 			optp->ipoptp_flags |= IPOPTP_ERROR;
2699 			return (opt);
2700 		}
2701 		break;
2702 	}
2703 
2704 	/*
2705 	 * Sanity check the pointer field based on the type of the
2706 	 * option.
2707 	 */
2708 	switch (opt) {
2709 	case IPOPT_RR:
2710 	case IPOPT_SSRR:
2711 	case IPOPT_LSRR:
2712 		if (pointer < IPOPT_MINOFF_SR)
2713 			optp->ipoptp_flags |= IPOPTP_ERROR;
2714 		break;
2715 	case IPOPT_TS:
2716 		if (pointer < IPOPT_MINOFF_IT)
2717 			optp->ipoptp_flags |= IPOPTP_ERROR;
2718 		/*
2719 		 * Note that the Internet Timestamp option also
2720 		 * contains two four bit fields (the Overflow field,
2721 		 * and the Flag field), which follow the pointer
2722 		 * field.  We don't need to check that these fields
2723 		 * fall within the length of the option because this
2724 		 * was implicitely done above.  We've checked that the
2725 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2726 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2727 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2728 		 */
2729 		ASSERT(len > IPOPT_POS_OV_FLG);
2730 		break;
2731 	}
2732 
2733 	return (opt);
2734 }
2735 
2736 /*
2737  * Update any record route or timestamp options to include this host.
2738  * Reverse any source route option.
2739  * This routine assumes that the options are well formed i.e. that they
2740  * have already been checked.
2741  */
2742 static void
2743 icmp_options_update(ipha_t *ipha)
2744 {
2745 	ipoptp_t	opts;
2746 	uchar_t		*opt;
2747 	uint8_t		optval;
2748 	ipaddr_t	src;		/* Our local address */
2749 	ipaddr_t	dst;
2750 
2751 	ip2dbg(("icmp_options_update\n"));
2752 	src = ipha->ipha_src;
2753 	dst = ipha->ipha_dst;
2754 
2755 	for (optval = ipoptp_first(&opts, ipha);
2756 	    optval != IPOPT_EOL;
2757 	    optval = ipoptp_next(&opts)) {
2758 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2759 		opt = opts.ipoptp_cur;
2760 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2761 		    optval, opts.ipoptp_len));
2762 		switch (optval) {
2763 			int off1, off2;
2764 		case IPOPT_SSRR:
2765 		case IPOPT_LSRR:
2766 			/*
2767 			 * Reverse the source route.  The first entry
2768 			 * should be the next to last one in the current
2769 			 * source route (the last entry is our address).
2770 			 * The last entry should be the final destination.
2771 			 */
2772 			off1 = IPOPT_MINOFF_SR - 1;
2773 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2774 			if (off2 < 0) {
2775 				/* No entries in source route */
2776 				ip1dbg((
2777 				    "icmp_options_update: bad src route\n"));
2778 				break;
2779 			}
2780 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
2781 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
2782 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
2783 			off2 -= IP_ADDR_LEN;
2784 
2785 			while (off1 < off2) {
2786 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
2787 				bcopy((char *)opt + off2, (char *)opt + off1,
2788 				    IP_ADDR_LEN);
2789 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
2790 				off1 += IP_ADDR_LEN;
2791 				off2 -= IP_ADDR_LEN;
2792 			}
2793 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
2794 			break;
2795 		}
2796 	}
2797 }
2798 
2799 /*
2800  * Process received ICMP Redirect messages.
2801  */
2802 /* ARGSUSED */
2803 static void
2804 icmp_redirect(mblk_t *mp)
2805 {
2806 	ipha_t	*ipha;
2807 	int	iph_hdr_length;
2808 	icmph_t	*icmph;
2809 	ipha_t	*ipha_err;
2810 	ire_t	*ire;
2811 	ire_t	*prev_ire;
2812 	ire_t	*save_ire;
2813 	ipaddr_t  src, dst, gateway;
2814 	iulp_t	ulp_info = { 0 };
2815 	int	error;
2816 
2817 	ipha = (ipha_t *)mp->b_rptr;
2818 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
2819 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
2820 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
2821 		BUMP_MIB(&icmp_mib, icmpInErrors);
2822 		freemsg(mp);
2823 		return;
2824 	}
2825 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2826 	ipha_err = (ipha_t *)&icmph[1];
2827 	src = ipha->ipha_src;
2828 	dst = ipha_err->ipha_dst;
2829 	gateway = icmph->icmph_rd_gateway;
2830 	/* Make sure the new gateway is reachable somehow. */
2831 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
2832 	    ALL_ZONES, MATCH_IRE_TYPE);
2833 	/*
2834 	 * Make sure we had a route for the dest in question and that
2835 	 * that route was pointing to the old gateway (the source of the
2836 	 * redirect packet.)
2837 	 */
2838 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
2839 	    MATCH_IRE_GW);
2840 	/*
2841 	 * Check that
2842 	 *	the redirect was not from ourselves
2843 	 *	the new gateway and the old gateway are directly reachable
2844 	 */
2845 	if (!prev_ire ||
2846 	    !ire ||
2847 	    ire->ire_type == IRE_LOCAL) {
2848 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
2849 		freemsg(mp);
2850 		if (ire != NULL)
2851 			ire_refrele(ire);
2852 		if (prev_ire != NULL)
2853 			ire_refrele(prev_ire);
2854 		return;
2855 	}
2856 
2857 	/*
2858 	 * Should we use the old ULP info to create the new gateway?  From
2859 	 * a user's perspective, we should inherit the info so that it
2860 	 * is a "smooth" transition.  If we do not do that, then new
2861 	 * connections going thru the new gateway will have no route metrics,
2862 	 * which is counter-intuitive to user.  From a network point of
2863 	 * view, this may or may not make sense even though the new gateway
2864 	 * is still directly connected to us so the route metrics should not
2865 	 * change much.
2866 	 *
2867 	 * But if the old ire_uinfo is not initialized, we do another
2868 	 * recursive lookup on the dest using the new gateway.  There may
2869 	 * be a route to that.  If so, use it to initialize the redirect
2870 	 * route.
2871 	 */
2872 	if (prev_ire->ire_uinfo.iulp_set) {
2873 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
2874 	} else {
2875 		ire_t *tmp_ire;
2876 		ire_t *sire;
2877 
2878 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
2879 		    ALL_ZONES, 0,
2880 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT));
2881 		if (sire != NULL) {
2882 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
2883 			/*
2884 			 * If sire != NULL, ire_ftable_lookup() should not
2885 			 * return a NULL value.
2886 			 */
2887 			ASSERT(tmp_ire != NULL);
2888 			ire_refrele(tmp_ire);
2889 			ire_refrele(sire);
2890 		} else if (tmp_ire != NULL) {
2891 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
2892 			    sizeof (iulp_t));
2893 			ire_refrele(tmp_ire);
2894 		}
2895 	}
2896 	if (prev_ire->ire_type == IRE_CACHE)
2897 		ire_delete(prev_ire);
2898 	ire_refrele(prev_ire);
2899 	/*
2900 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
2901 	 * require TOS routing
2902 	 */
2903 	switch (icmph->icmph_code) {
2904 	case 0:
2905 	case 1:
2906 		/* TODO: TOS specificity for cases 2 and 3 */
2907 	case 2:
2908 	case 3:
2909 		break;
2910 	default:
2911 		freemsg(mp);
2912 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
2913 		ire_refrele(ire);
2914 		return;
2915 	}
2916 	/*
2917 	 * Create a Route Association.  This will allow us to remember that
2918 	 * someone we believe told us to use the particular gateway.
2919 	 */
2920 	save_ire = ire;
2921 	ire = ire_create(
2922 		(uchar_t *)&dst,			/* dest addr */
2923 		(uchar_t *)&ip_g_all_ones,		/* mask */
2924 		(uchar_t *)&save_ire->ire_src_addr,	/* source addr */
2925 		(uchar_t *)&gateway,			/* gateway addr */
2926 		NULL,					/* no in_srcaddr */
2927 		&save_ire->ire_max_frag,		/* max frag */
2928 		NULL,					/* Fast Path header */
2929 		NULL,					/* no rfq */
2930 		NULL,					/* no stq */
2931 		IRE_HOST_REDIRECT,
2932 		NULL,
2933 		NULL,
2934 		NULL,
2935 		0,
2936 		0,
2937 		0,
2938 		(RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
2939 		&ulp_info);
2940 
2941 	if (ire == NULL) {
2942 		freemsg(mp);
2943 		ire_refrele(save_ire);
2944 		return;
2945 	}
2946 	error = ire_add(&ire, NULL, NULL, NULL);
2947 	ire_refrele(save_ire);
2948 	if (error == 0) {
2949 		ire_refrele(ire);		/* Held in ire_add_v4 */
2950 		/* tell routing sockets that we received a redirect */
2951 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
2952 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
2953 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR));
2954 	}
2955 
2956 	/*
2957 	 * Delete any existing IRE_HOST_REDIRECT for this destination.
2958 	 * This together with the added IRE has the effect of
2959 	 * modifying an existing redirect.
2960 	 */
2961 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST_REDIRECT, NULL, NULL,
2962 	    ALL_ZONES, 0, (MATCH_IRE_GW | MATCH_IRE_TYPE));
2963 	if (prev_ire) {
2964 		ire_delete(prev_ire);
2965 		ire_refrele(prev_ire);
2966 	}
2967 
2968 	freemsg(mp);
2969 }
2970 
2971 /*
2972  * Generate an ICMP parameter problem message.
2973  */
2974 static void
2975 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr)
2976 {
2977 	icmph_t	icmph;
2978 	boolean_t mctl_present;
2979 	mblk_t *first_mp;
2980 
2981 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
2982 
2983 	if (!(mp = icmp_pkt_err_ok(mp))) {
2984 		if (mctl_present)
2985 			freeb(first_mp);
2986 		return;
2987 	}
2988 
2989 	bzero(&icmph, sizeof (icmph_t));
2990 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
2991 	icmph.icmph_pp_ptr = ptr;
2992 	BUMP_MIB(&icmp_mib, icmpOutParmProbs);
2993 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present);
2994 }
2995 
2996 /*
2997  * Build and ship an IPv4 ICMP message using the packet data in mp, and
2998  * the ICMP header pointed to by "stuff".  (May be called as writer.)
2999  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3000  * an icmp error packet can be sent.
3001  * Assigns an appropriate source address to the packet. If ipha_dst is
3002  * one of our addresses use it for source. Otherwise pick a source based
3003  * on a route lookup back to ipha_src.
3004  * Note that ipha_src must be set here since the
3005  * packet is likely to arrive on an ill queue in ip_wput() which will
3006  * not set a source address.
3007  */
3008 static void
3009 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3010     boolean_t mctl_present)
3011 {
3012 	ipaddr_t dst;
3013 	icmph_t	*icmph;
3014 	ipha_t	*ipha;
3015 	uint_t	len_needed;
3016 	size_t	msg_len;
3017 	mblk_t	*mp1;
3018 	ipaddr_t src;
3019 	ire_t	*ire;
3020 	mblk_t *ipsec_mp;
3021 	ipsec_out_t	*io = NULL;
3022 	boolean_t xmit_if_on = B_FALSE;
3023 	zoneid_t	zoneid;
3024 
3025 	if (mctl_present) {
3026 		/*
3027 		 * If it is :
3028 		 *
3029 		 * 1) a IPSEC_OUT, then this is caused by outbound
3030 		 *    datagram originating on this host. IPSEC processing
3031 		 *    may or may not have been done. Refer to comments above
3032 		 *    icmp_inbound_error_fanout for details.
3033 		 *
3034 		 * 2) a IPSEC_IN if we are generating a icmp_message
3035 		 *    for an incoming datagram destined for us i.e called
3036 		 *    from ip_fanout_send_icmp.
3037 		 */
3038 		ipsec_info_t *in;
3039 		ipsec_mp = mp;
3040 		mp = ipsec_mp->b_cont;
3041 
3042 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3043 		ipha = (ipha_t *)mp->b_rptr;
3044 
3045 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3046 		    in->ipsec_info_type == IPSEC_IN);
3047 
3048 		if (in->ipsec_info_type == IPSEC_IN) {
3049 			/*
3050 			 * Convert the IPSEC_IN to IPSEC_OUT.
3051 			 */
3052 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3053 				BUMP_MIB(&ip_mib, ipOutDiscards);
3054 				return;
3055 			}
3056 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3057 		} else {
3058 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3059 			io = (ipsec_out_t *)in;
3060 			if (io->ipsec_out_xmit_if)
3061 				xmit_if_on = B_TRUE;
3062 			/*
3063 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3064 			 * ire lookup.
3065 			 */
3066 			io->ipsec_out_proc_begin = B_FALSE;
3067 		}
3068 		zoneid = io->ipsec_out_zoneid;
3069 		ASSERT(zoneid != ALL_ZONES);
3070 	} else {
3071 		/*
3072 		 * This is in clear. The icmp message we are building
3073 		 * here should go out in clear.
3074 		 *
3075 		 * Pardon the convolution of it all, but it's easier to
3076 		 * allocate a "use cleartext" IPSEC_IN message and convert
3077 		 * it than it is to allocate a new one.
3078 		 */
3079 		ipsec_in_t *ii;
3080 		ASSERT(DB_TYPE(mp) == M_DATA);
3081 		if ((ipsec_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
3082 			freemsg(mp);
3083 			BUMP_MIB(&ip_mib, ipOutDiscards);
3084 			return;
3085 		}
3086 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3087 
3088 		/* This is not a secure packet */
3089 		ii->ipsec_in_secure = B_FALSE;
3090 		if (CONN_Q(q)) {
3091 			zoneid = Q_TO_CONN(q)->conn_zoneid;
3092 		} else {
3093 			zoneid = GLOBAL_ZONEID;
3094 		}
3095 		ii->ipsec_in_zoneid = zoneid;
3096 		ipsec_mp->b_cont = mp;
3097 		ipha = (ipha_t *)mp->b_rptr;
3098 		/*
3099 		 * Convert the IPSEC_IN to IPSEC_OUT.
3100 		 */
3101 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3102 			BUMP_MIB(&ip_mib, ipOutDiscards);
3103 			return;
3104 		}
3105 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3106 	}
3107 
3108 	/* Remember our eventual destination */
3109 	dst = ipha->ipha_src;
3110 
3111 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3112 	    NULL, NULL, zoneid, MATCH_IRE_TYPE);
3113 	if (ire != NULL && ire->ire_zoneid == zoneid) {
3114 		src = ipha->ipha_dst;
3115 	} else if (!xmit_if_on) {
3116 		if (ire != NULL)
3117 			ire_refrele(ire);
3118 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid,
3119 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY));
3120 		if (ire == NULL) {
3121 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3122 			freemsg(ipsec_mp);
3123 			return;
3124 		}
3125 		src = ire->ire_src_addr;
3126 	} else {
3127 		ipif_t	*ipif = NULL;
3128 		ill_t	*ill;
3129 		/*
3130 		 * This must be an ICMP error coming from
3131 		 * ip_mrtun_forward(). The src addr should
3132 		 * be equal to the IP-addr of the outgoing
3133 		 * interface.
3134 		 */
3135 		if (io == NULL) {
3136 			/* This is not a IPSEC_OUT type control msg */
3137 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3138 			freemsg(ipsec_mp);
3139 			return;
3140 		}
3141 		ill = ill_lookup_on_ifindex(io->ipsec_out_ill_index, B_FALSE,
3142 		    NULL, NULL, NULL, NULL);
3143 		if (ill != NULL) {
3144 			ipif = ipif_get_next_ipif(NULL, ill);
3145 			ill_refrele(ill);
3146 		}
3147 		if (ipif == NULL) {
3148 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3149 			freemsg(ipsec_mp);
3150 			return;
3151 		}
3152 		src = ipif->ipif_src_addr;
3153 		ipif_refrele(ipif);
3154 	}
3155 
3156 	if (ire != NULL)
3157 		ire_refrele(ire);
3158 
3159 	/*
3160 	 * Check if we can send back more then 8 bytes in addition
3161 	 * to the IP header. We will include as much as 64 bytes.
3162 	 */
3163 	len_needed = IPH_HDR_LENGTH(ipha) + ip_icmp_return;
3164 	msg_len = msgdsize(mp);
3165 	if (msg_len > len_needed) {
3166 		(void) adjmsg(mp, len_needed - msg_len);
3167 		msg_len = len_needed;
3168 	}
3169 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_HI);
3170 	if (!mp1) {
3171 		BUMP_MIB(&icmp_mib, icmpOutErrors);
3172 		freemsg(ipsec_mp);
3173 		return;
3174 	}
3175 	mp1->b_cont = mp;
3176 	mp = mp1;
3177 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3178 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3179 	    io->ipsec_out_type == IPSEC_OUT);
3180 	ipsec_mp->b_cont = mp;
3181 
3182 	/*
3183 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3184 	 * node generates be accepted in peace by all on-host destinations.
3185 	 * If we do NOT assume that all on-host destinations trust
3186 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3187 	 * (Look for ipsec_out_icmp_loopback).
3188 	 */
3189 	io->ipsec_out_icmp_loopback = B_TRUE;
3190 
3191 	ipha = (ipha_t *)mp->b_rptr;
3192 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3193 	*ipha = icmp_ipha;
3194 	ipha->ipha_src = src;
3195 	ipha->ipha_dst = dst;
3196 	ipha->ipha_ttl = ip_def_ttl;
3197 	msg_len += sizeof (icmp_ipha) + len;
3198 	if (msg_len > IP_MAXPACKET) {
3199 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3200 		msg_len = IP_MAXPACKET;
3201 	}
3202 	ipha->ipha_length = htons((uint16_t)msg_len);
3203 	icmph = (icmph_t *)&ipha[1];
3204 	bcopy(stuff, icmph, len);
3205 	icmph->icmph_checksum = 0;
3206 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3207 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
3208 	put(q, ipsec_mp);
3209 }
3210 
3211 /*
3212  * Determine if an ICMP error packet can be sent given the rate limit.
3213  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3214  * in milliseconds) and a burst size. Burst size number of packets can
3215  * be sent arbitrarely closely spaced.
3216  * The state is tracked using two variables to implement an approximate
3217  * token bucket filter:
3218  *	icmp_pkt_err_last - lbolt value when the last burst started
3219  *	icmp_pkt_err_sent - number of packets sent in current burst
3220  */
3221 boolean_t
3222 icmp_err_rate_limit(void)
3223 {
3224 	clock_t now = TICK_TO_MSEC(lbolt);
3225 	uint_t refilled; /* Number of packets refilled in tbf since last */
3226 	uint_t err_interval = ip_icmp_err_interval; /* Guard against changes */
3227 
3228 	if (err_interval == 0)
3229 		return (B_FALSE);
3230 
3231 	if (icmp_pkt_err_last > now) {
3232 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3233 		icmp_pkt_err_last = 0;
3234 		icmp_pkt_err_sent = 0;
3235 	}
3236 	/*
3237 	 * If we are in a burst update the token bucket filter.
3238 	 * Update the "last" time to be close to "now" but make sure
3239 	 * we don't loose precision.
3240 	 */
3241 	if (icmp_pkt_err_sent != 0) {
3242 		refilled = (now - icmp_pkt_err_last)/err_interval;
3243 		if (refilled > icmp_pkt_err_sent) {
3244 			icmp_pkt_err_sent = 0;
3245 		} else {
3246 			icmp_pkt_err_sent -= refilled;
3247 			icmp_pkt_err_last += refilled * err_interval;
3248 		}
3249 	}
3250 	if (icmp_pkt_err_sent == 0) {
3251 		/* Start of new burst */
3252 		icmp_pkt_err_last = now;
3253 	}
3254 	if (icmp_pkt_err_sent < ip_icmp_err_burst) {
3255 		icmp_pkt_err_sent++;
3256 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3257 		    icmp_pkt_err_sent));
3258 		return (B_FALSE);
3259 	}
3260 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3261 	return (B_TRUE);
3262 }
3263 
3264 /*
3265  * Check if it is ok to send an IPv4 ICMP error packet in
3266  * response to the IPv4 packet in mp.
3267  * Free the message and return null if no
3268  * ICMP error packet should be sent.
3269  */
3270 static mblk_t *
3271 icmp_pkt_err_ok(mblk_t *mp)
3272 {
3273 	icmph_t	*icmph;
3274 	ipha_t	*ipha;
3275 	uint_t	len_needed;
3276 	ire_t	*src_ire;
3277 	ire_t	*dst_ire;
3278 
3279 	if (!mp)
3280 		return (NULL);
3281 	ipha = (ipha_t *)mp->b_rptr;
3282 	if (ip_csum_hdr(ipha)) {
3283 		BUMP_MIB(&ip_mib, ipInCksumErrs);
3284 		freemsg(mp);
3285 		return (NULL);
3286 	}
3287 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3288 	    NULL, ALL_ZONES, MATCH_IRE_TYPE);
3289 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3290 	    NULL, ALL_ZONES, MATCH_IRE_TYPE);
3291 	if (src_ire != NULL || dst_ire != NULL ||
3292 	    CLASSD(ipha->ipha_dst) ||
3293 	    CLASSD(ipha->ipha_src) ||
3294 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3295 		/* Note: only errors to the fragment with offset 0 */
3296 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3297 		freemsg(mp);
3298 		if (src_ire != NULL)
3299 			ire_refrele(src_ire);
3300 		if (dst_ire != NULL)
3301 			ire_refrele(dst_ire);
3302 		return (NULL);
3303 	}
3304 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3305 		/*
3306 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3307 		 * errors in response to any ICMP errors.
3308 		 */
3309 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3310 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3311 			if (!pullupmsg(mp, len_needed)) {
3312 				BUMP_MIB(&icmp_mib, icmpInErrors);
3313 				freemsg(mp);
3314 				return (NULL);
3315 			}
3316 			ipha = (ipha_t *)mp->b_rptr;
3317 		}
3318 		icmph = (icmph_t *)
3319 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3320 		switch (icmph->icmph_type) {
3321 		case ICMP_DEST_UNREACHABLE:
3322 		case ICMP_SOURCE_QUENCH:
3323 		case ICMP_TIME_EXCEEDED:
3324 		case ICMP_PARAM_PROBLEM:
3325 		case ICMP_REDIRECT:
3326 			BUMP_MIB(&icmp_mib, icmpOutDrops);
3327 			freemsg(mp);
3328 			return (NULL);
3329 		default:
3330 			break;
3331 		}
3332 	}
3333 	if (icmp_err_rate_limit()) {
3334 		/*
3335 		 * Only send ICMP error packets every so often.
3336 		 * This should be done on a per port/source basis,
3337 		 * but for now this will suffice.
3338 		 */
3339 		freemsg(mp);
3340 		return (NULL);
3341 	}
3342 	return (mp);
3343 }
3344 
3345 /*
3346  * Generate an ICMP redirect message.
3347  */
3348 static void
3349 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway)
3350 {
3351 	icmph_t	icmph;
3352 
3353 	/*
3354 	 * We are called from ip_rput where we could
3355 	 * not have attached an IPSEC_IN.
3356 	 */
3357 	ASSERT(mp->b_datap->db_type == M_DATA);
3358 
3359 	if (!(mp = icmp_pkt_err_ok(mp))) {
3360 		return;
3361 	}
3362 
3363 	bzero(&icmph, sizeof (icmph_t));
3364 	icmph.icmph_type = ICMP_REDIRECT;
3365 	icmph.icmph_code = 1;
3366 	icmph.icmph_rd_gateway = gateway;
3367 	BUMP_MIB(&icmp_mib, icmpOutRedirects);
3368 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE);
3369 }
3370 
3371 /*
3372  * Generate an ICMP time exceeded message.
3373  */
3374 void
3375 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code)
3376 {
3377 	icmph_t	icmph;
3378 	boolean_t mctl_present;
3379 	mblk_t *first_mp;
3380 
3381 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3382 
3383 	if (!(mp = icmp_pkt_err_ok(mp))) {
3384 		if (mctl_present)
3385 			freeb(first_mp);
3386 		return;
3387 	}
3388 
3389 	bzero(&icmph, sizeof (icmph_t));
3390 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3391 	icmph.icmph_code = code;
3392 	BUMP_MIB(&icmp_mib, icmpOutTimeExcds);
3393 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present);
3394 }
3395 
3396 /*
3397  * Generate an ICMP unreachable message.
3398  */
3399 void
3400 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code)
3401 {
3402 	icmph_t	icmph;
3403 	mblk_t *first_mp;
3404 	boolean_t mctl_present;
3405 
3406 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3407 
3408 	if (!(mp = icmp_pkt_err_ok(mp))) {
3409 		if (mctl_present)
3410 			freeb(first_mp);
3411 		return;
3412 	}
3413 
3414 	bzero(&icmph, sizeof (icmph_t));
3415 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3416 	icmph.icmph_code = code;
3417 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
3418 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3419 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present);
3420 }
3421 
3422 /*
3423  * News from ARP.  ARP sends notification of interesting events down
3424  * to its clients using M_CTL messages with the interesting ARP packet
3425  * attached via b_cont.
3426  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3427  * queue as opposed to ARP sending the message to all the clients, i.e. all
3428  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3429  * table if a cache IRE is found to delete all the entries for the address in
3430  * the packet.
3431  */
3432 static void
3433 ip_arp_news(queue_t *q, mblk_t *mp)
3434 {
3435 	arcn_t		*arcn;
3436 	arh_t		*arh;
3437 	char		*cp1;
3438 	uchar_t		*cp2;
3439 	ire_t		*ire = NULL;
3440 	int		i1;
3441 	char		hbuf[128];
3442 	char		sbuf[16];
3443 	ipaddr_t	src;
3444 	in6_addr_t	v6src;
3445 	boolean_t	isv6 = B_FALSE;
3446 
3447 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3448 		if (q->q_next) {
3449 			putnext(q, mp);
3450 		} else
3451 			freemsg(mp);
3452 		return;
3453 	}
3454 	arh = (arh_t *)mp->b_cont->b_rptr;
3455 	/* Is it one we are interested in? */
3456 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3457 		isv6 = B_TRUE;
3458 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3459 		    IPV6_ADDR_LEN);
3460 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3461 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3462 		    IP_ADDR_LEN);
3463 	} else {
3464 		freemsg(mp);
3465 		return;
3466 	}
3467 
3468 	arcn = (arcn_t *)mp->b_rptr;
3469 	switch (arcn->arcn_code) {
3470 	case AR_CN_BOGON:
3471 		/*
3472 		 * Someone is sending ARP packets with a source protocol
3473 		 * address which we have published.  Either they are
3474 		 * pretending to be us, or we have been asked to proxy
3475 		 * for a machine that can do fine for itself, or two
3476 		 * different machines are providing proxy service for the
3477 		 * same protocol address, or something.  We try and do
3478 		 * something appropriate here.
3479 		 */
3480 		cp2 = (uchar_t *)&arh[1];
3481 		cp1 = hbuf;
3482 		*cp1 = '\0';
3483 		for (i1 = arh->arh_hlen; i1--; cp1 += 3)
3484 			(void) sprintf(cp1, "%02x:", *cp2++ & 0xff);
3485 		if (cp1 != hbuf)
3486 			cp1[-1] = '\0';
3487 		(void) ip_dot_addr(src, sbuf);
3488 		if (isv6)
3489 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES);
3490 		else
3491 			ire = ire_cache_lookup(src, ALL_ZONES);
3492 
3493 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3494 			cmn_err(CE_WARN,
3495 			    "IP: Hardware address '%s' trying"
3496 			    " to be our address %s!",
3497 			    hbuf, sbuf);
3498 		} else {
3499 			cmn_err(CE_WARN,
3500 			    "IP: Proxy ARP problem?  "
3501 			    "Hardware address '%s' thinks it is %s",
3502 			    hbuf, sbuf);
3503 		}
3504 		if (ire != NULL)
3505 			ire_refrele(ire);
3506 		break;
3507 	case AR_CN_ANNOUNCE:
3508 		if (isv6) {
3509 			/*
3510 			 * For XRESOLV interfaces.
3511 			 * Delete the IRE cache entry and NCE for this
3512 			 * v6 address
3513 			 */
3514 			ip_ire_clookup_and_delete_v6(&v6src);
3515 			/*
3516 			 * If v6src is a non-zero, it's a router address
3517 			 * as below. Do the same sort of thing to clean
3518 			 * out off-net IRE_CACHE entries that go through
3519 			 * the router.
3520 			 */
3521 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
3522 				ire_walk_v6(ire_delete_cache_gw_v6,
3523 				    (char *)&v6src, ALL_ZONES);
3524 			}
3525 			break;
3526 		}
3527 		/*
3528 		 * ARP gives us a copy of any broadcast packet with identical
3529 		 * sender and receiver protocol address, in
3530 		 * case we want to intuit something from it.  Such a packet
3531 		 * usually means that a machine has just come up on the net.
3532 		 * If we have an IRE_CACHE, we blow it away.  This way we will
3533 		 * immediately pick up the rare case of a host changing
3534 		 * hardware address. ip_ire_clookup_and_delete achieves this.
3535 		 *
3536 		 * The address in "src" may be an entry for a router.
3537 		 * (Default router, or non-default router.)  If
3538 		 * that's true, then any off-net IRE_CACHE entries
3539 		 * that go through the router with address "src"
3540 		 * must be clobbered.  Use ire_walk to achieve this
3541 		 * goal.
3542 		 *
3543 		 * It should be possible to determine if the address
3544 		 * in src is or is not for a router.  This way,
3545 		 * the ire_walk() isn't called all of the time here.
3546 		 * Do not pass 'src' value of 0 to ire_delete_cache_gw,
3547 		 * as it would remove all IRE_CACHE entries for onlink
3548 		 * destinations. All onlink destinations have
3549 		 * ire_gateway_addr == 0.
3550 		 */
3551 		if ((ip_ire_clookup_and_delete(src, NULL) ||
3552 		    (ire = ire_ftable_lookup(src, 0, 0, 0, NULL, NULL, NULL,
3553 		    0, MATCH_IRE_DSTONLY)) != NULL) && src != 0) {
3554 			ire_walk_v4(ire_delete_cache_gw, (char *)&src,
3555 			    ALL_ZONES);
3556 		}
3557 		/* From ire_ftable_lookup */
3558 		if (ire != NULL)
3559 			ire_refrele(ire);
3560 		break;
3561 	default:
3562 		if (ire != NULL)
3563 			ire_refrele(ire);
3564 		break;
3565 	}
3566 	freemsg(mp);
3567 }
3568 
3569 /*
3570  * Create a mblk suitable for carrying the interface index and/or source link
3571  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
3572  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
3573  * application.
3574  */
3575 mblk_t *
3576 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags)
3577 {
3578 	mblk_t		*mp;
3579 	in_pktinfo_t	*pinfo;
3580 	ipha_t *ipha;
3581 	struct ether_header *pether;
3582 
3583 	mp = allocb(sizeof (in_pktinfo_t), BPRI_MED);
3584 	if (mp == NULL) {
3585 		ip1dbg(("ip_add_info: allocation failure.\n"));
3586 		return (data_mp);
3587 	}
3588 
3589 	ipha	= (ipha_t *)data_mp->b_rptr;
3590 	pinfo = (in_pktinfo_t *)mp->b_rptr;
3591 	bzero(pinfo, sizeof (in_pktinfo_t));
3592 	pinfo->in_pkt_flags = (uchar_t)flags;
3593 	pinfo->in_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
3594 
3595 	if (flags & IPF_RECVIF)
3596 		pinfo->in_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
3597 
3598 	pether = (struct ether_header *)((char *)ipha
3599 	    - sizeof (struct ether_header));
3600 	/*
3601 	 * Make sure the interface is an ethernet type, since this option
3602 	 * is currently supported only on this type of interface. Also make
3603 	 * sure we are pointing correctly above db_base.
3604 	 */
3605 
3606 	if ((flags & IPF_RECVSLLA) &&
3607 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
3608 	    (ill->ill_type == IFT_ETHER) &&
3609 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
3610 
3611 		pinfo->in_pkt_slla.sdl_type = IFT_ETHER;
3612 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
3613 		    (uchar_t *)pinfo->in_pkt_slla.sdl_data, ETHERADDRL);
3614 	} else {
3615 		/*
3616 		 * Clear the bit. Indicate to upper layer that IP is not
3617 		 * sending this ancillary info.
3618 		 */
3619 		pinfo->in_pkt_flags = pinfo->in_pkt_flags & ~IPF_RECVSLLA;
3620 	}
3621 
3622 	mp->b_datap->db_type = M_CTL;
3623 	mp->b_wptr += sizeof (in_pktinfo_t);
3624 	mp->b_cont = data_mp;
3625 
3626 	return (mp);
3627 }
3628 
3629 /*
3630  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
3631  * part of the bind request.
3632  */
3633 
3634 boolean_t
3635 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
3636 {
3637 	ipsec_in_t *ii;
3638 
3639 	ASSERT(policy_mp != NULL);
3640 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
3641 
3642 	ii = (ipsec_in_t *)policy_mp->b_rptr;
3643 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
3644 
3645 	connp->conn_policy = ii->ipsec_in_policy;
3646 	ii->ipsec_in_policy = NULL;
3647 
3648 	if (ii->ipsec_in_action != NULL) {
3649 		if (connp->conn_latch == NULL) {
3650 			connp->conn_latch = iplatch_create();
3651 			if (connp->conn_latch == NULL)
3652 				return (B_FALSE);
3653 		}
3654 		ipsec_latch_inbound(connp->conn_latch, ii);
3655 	}
3656 	return (B_TRUE);
3657 }
3658 
3659 /*
3660  * Upper level protocols (ULP) pass through bind requests to IP for inspection
3661  * and to arrange for power-fanout assist.  The ULP is identified by
3662  * adding a single byte at the end of the original bind message.
3663  * A ULP other than UDP or TCP that wishes to be recognized passes
3664  * down a bind with a zero length address.
3665  *
3666  * The binding works as follows:
3667  * - A zero byte address means just bind to the protocol.
3668  * - A four byte address is treated as a request to validate
3669  *   that the address is a valid local address, appropriate for
3670  *   an application to bind to. This does not affect any fanout
3671  *   information in IP.
3672  * - A sizeof sin_t byte address is used to bind to only the local address
3673  *   and port.
3674  * - A sizeof ipa_conn_t byte address contains complete fanout information
3675  *   consisting of local and remote addresses and ports.  In
3676  *   this case, the addresses are both validated as appropriate
3677  *   for this operation, and, if so, the information is retained
3678  *   for use in the inbound fanout.
3679  *
3680  * The ULP (except in the zero-length bind) can append an
3681  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
3682  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
3683  * a copy of the source or destination IRE (source for local bind;
3684  * destination for complete bind). IPSEC_POLICY_SET indicates that the
3685  * policy information contained should be copied on to the conn.
3686  *
3687  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
3688  */
3689 mblk_t *
3690 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
3691 {
3692 	ssize_t		len;
3693 	struct T_bind_req	*tbr;
3694 	sin_t		*sin;
3695 	ipa_conn_t	*ac;
3696 	uchar_t		*ucp;
3697 	mblk_t		*mp1;
3698 	boolean_t	ire_requested;
3699 	boolean_t	ipsec_policy_set = B_FALSE;
3700 	int		error = 0;
3701 	int		protocol;
3702 	ipa_conn_x_t	*acx;
3703 
3704 	ASSERT(!connp->conn_af_isv6);
3705 	connp->conn_pkt_isv6 = B_FALSE;
3706 
3707 	len = mp->b_wptr - mp->b_rptr;
3708 	if (len < (sizeof (*tbr) + 1)) {
3709 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
3710 		    "ip_bind: bogus msg, len %ld", len);
3711 		/* XXX: Need to return something better */
3712 		goto bad_addr;
3713 	}
3714 	/* Back up and extract the protocol identifier. */
3715 	mp->b_wptr--;
3716 	protocol = *mp->b_wptr & 0xFF;
3717 	tbr = (struct T_bind_req *)mp->b_rptr;
3718 	/* Reset the message type in preparation for shipping it back. */
3719 	mp->b_datap->db_type = M_PCPROTO;
3720 
3721 	connp->conn_ulp = (uint8_t)protocol;
3722 
3723 	/*
3724 	 * Check for a zero length address.  This is from a protocol that
3725 	 * wants to register to receive all packets of its type.
3726 	 */
3727 	if (tbr->ADDR_length == 0) {
3728 		/*
3729 		 * These protocols are now intercepted in ip_bind_v6().
3730 		 * Reject protocol-level binds here for now.
3731 		 *
3732 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
3733 		 * so that the protocol type cannot be SCTP.
3734 		 */
3735 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
3736 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
3737 			goto bad_addr;
3738 		}
3739 
3740 		/* No hash here really.  The table is big enough. */
3741 		connp->conn_srcv6 = ipv6_all_zeros;
3742 
3743 		ipcl_proto_insert(connp, protocol);
3744 
3745 		tbr->PRIM_type = T_BIND_ACK;
3746 		return (mp);
3747 	}
3748 
3749 	/* Extract the address pointer from the message. */
3750 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
3751 	    tbr->ADDR_length);
3752 	if (ucp == NULL) {
3753 		ip1dbg(("ip_bind: no address\n"));
3754 		goto bad_addr;
3755 	}
3756 	if (!OK_32PTR(ucp)) {
3757 		ip1dbg(("ip_bind: unaligned address\n"));
3758 		goto bad_addr;
3759 	}
3760 	/*
3761 	 * Check for trailing mps.
3762 	 */
3763 
3764 	mp1 = mp->b_cont;
3765 	ire_requested = (mp1 && mp1->b_datap->db_type == IRE_DB_REQ_TYPE);
3766 	ipsec_policy_set = (mp1 && mp1->b_datap->db_type == IPSEC_POLICY_SET);
3767 
3768 	switch (tbr->ADDR_length) {
3769 	default:
3770 		ip1dbg(("ip_bind: bad address length %d\n",
3771 		    (int)tbr->ADDR_length));
3772 		goto bad_addr;
3773 
3774 	case IP_ADDR_LEN:
3775 		/* Verification of local address only */
3776 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
3777 		    ire_requested, ipsec_policy_set, B_FALSE);
3778 		break;
3779 
3780 	case sizeof (sin_t):
3781 		sin = (sin_t *)ucp;
3782 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
3783 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
3784 		if (protocol == IPPROTO_TCP)
3785 			connp->conn_recv = tcp_conn_request;
3786 		break;
3787 
3788 	case sizeof (ipa_conn_t):
3789 		ac = (ipa_conn_t *)ucp;
3790 		/* For raw socket, the local port is not set. */
3791 		if (ac->ac_lport == 0)
3792 			ac->ac_lport = connp->conn_lport;
3793 		/* Always verify destination reachability. */
3794 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
3795 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
3796 		    ipsec_policy_set, B_TRUE, B_TRUE);
3797 		if (protocol == IPPROTO_TCP)
3798 			connp->conn_recv = tcp_input;
3799 		break;
3800 
3801 	case sizeof (ipa_conn_x_t):
3802 		acx = (ipa_conn_x_t *)ucp;
3803 		/*
3804 		 * Whether or not to verify destination reachability depends
3805 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
3806 		 */
3807 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
3808 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
3809 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
3810 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
3811 		if (protocol == IPPROTO_TCP)
3812 			connp->conn_recv = tcp_input;
3813 		break;
3814 	}
3815 	if (error == EINPROGRESS)
3816 		return (NULL);
3817 	else if (error != 0)
3818 		goto bad_addr;
3819 	/*
3820 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
3821 	 * We can't do this in ip_bind_insert_ire because the policy
3822 	 * may not have been inherited at that point in time and hence
3823 	 * conn_out_enforce_policy may not be set.
3824 	 */
3825 	mp1 = mp->b_cont;
3826 	if (ire_requested && connp->conn_out_enforce_policy &&
3827 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
3828 		ire_t *ire = (ire_t *)mp1->b_rptr;
3829 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
3830 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
3831 	}
3832 
3833 	/* Send it home. */
3834 	mp->b_datap->db_type = M_PCPROTO;
3835 	tbr->PRIM_type = T_BIND_ACK;
3836 	return (mp);
3837 
3838 bad_addr:
3839 	/*
3840 	 * If error = -1 then we generate a TBADADDR - otherwise error is
3841 	 * a unix errno.
3842 	 */
3843 	if (error > 0)
3844 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
3845 	else
3846 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
3847 	return (mp);
3848 }
3849 
3850 /*
3851  * Here address is verified to be a valid local address.
3852  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
3853  * address is also considered a valid local address.
3854  * In the case of a broadcast/multicast address, however, the
3855  * upper protocol is expected to reset the src address
3856  * to 0 if it sees a IRE_BROADCAST type returned so that
3857  * no packets are emitted with broadcast/multicast address as
3858  * source address (that violates hosts requirements RFC1122)
3859  * The addresses valid for bind are:
3860  *	(1) - INADDR_ANY (0)
3861  *	(2) - IP address of an UP interface
3862  *	(3) - IP address of a DOWN interface
3863  *	(4) - valid local IP broadcast addresses. In this case
3864  *	the conn will only receive packets destined to
3865  *	the specified broadcast address.
3866  *	(5) - a multicast address. In this case
3867  *	the conn will only receive packets destined to
3868  *	the specified multicast address. Note: the
3869  *	application still has to issue an
3870  *	IP_ADD_MEMBERSHIP socket option.
3871  *
3872  * On error, return -1 for TBADADDR otherwise pass the
3873  * errno with TSYSERR reply.
3874  *
3875  * In all the above cases, the bound address must be valid in the current zone.
3876  * When the address is loopback, multicast or broadcast, there might be many
3877  * matching IREs so bind has to look up based on the zone.
3878  */
3879 int
3880 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
3881     boolean_t ire_requested, boolean_t ipsec_policy_set,
3882     boolean_t fanout_insert)
3883 {
3884 	int		error = 0;
3885 	ire_t		*src_ire;
3886 	mblk_t		*policy_mp;
3887 	ipif_t		*ipif;
3888 	zoneid_t	zoneid;
3889 
3890 	if (ipsec_policy_set) {
3891 		policy_mp = mp->b_cont;
3892 	}
3893 
3894 	/*
3895 	 * If it was previously connected, conn_fully_bound would have
3896 	 * been set.
3897 	 */
3898 	connp->conn_fully_bound = B_FALSE;
3899 
3900 	src_ire = NULL;
3901 	ipif = NULL;
3902 
3903 	zoneid = connp->conn_zoneid;
3904 
3905 	if (src_addr) {
3906 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
3907 		    NULL, NULL, zoneid, MATCH_IRE_ZONEONLY);
3908 		/*
3909 		 * If an address other than 0.0.0.0 is requested,
3910 		 * we verify that it is a valid address for bind
3911 		 * Note: Following code is in if-else-if form for
3912 		 * readability compared to a condition check.
3913 		 */
3914 		/* LINTED - statement has no consequent */
3915 		if (IRE_IS_LOCAL(src_ire)) {
3916 			/*
3917 			 * (2) Bind to address of local UP interface
3918 			 */
3919 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
3920 			/*
3921 			 * (4) Bind to broadcast address
3922 			 * Note: permitted only from transports that
3923 			 * request IRE
3924 			 */
3925 			if (!ire_requested)
3926 				error = EADDRNOTAVAIL;
3927 		} else {
3928 			/*
3929 			 * (3) Bind to address of local DOWN interface
3930 			 * (ipif_lookup_addr() looks up all interfaces
3931 			 * but we do not get here for UP interfaces
3932 			 * - case (2) above)
3933 			 * We put the protocol byte back into the mblk
3934 			 * since we may come back via ip_wput_nondata()
3935 			 * later with this mblk if ipif_lookup_addr chooses
3936 			 * to defer processing.
3937 			 */
3938 			*mp->b_wptr++ = (char)connp->conn_ulp;
3939 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
3940 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
3941 			    &error)) != NULL) {
3942 				ipif_refrele(ipif);
3943 			} else if (error == EINPROGRESS) {
3944 				if (src_ire != NULL)
3945 					ire_refrele(src_ire);
3946 				return (EINPROGRESS);
3947 			} else if (CLASSD(src_addr)) {
3948 				error = 0;
3949 				if (src_ire != NULL)
3950 					ire_refrele(src_ire);
3951 				/*
3952 				 * (5) bind to multicast address.
3953 				 * Fake out the IRE returned to upper
3954 				 * layer to be a broadcast IRE.
3955 				 */
3956 				src_ire = ire_ctable_lookup(
3957 				    INADDR_BROADCAST, INADDR_ANY,
3958 				    IRE_BROADCAST, NULL, zoneid,
3959 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY));
3960 				if (src_ire == NULL || !ire_requested)
3961 					error = EADDRNOTAVAIL;
3962 			} else {
3963 				/*
3964 				 * Not a valid address for bind
3965 				 */
3966 				error = EADDRNOTAVAIL;
3967 			}
3968 			/*
3969 			 * Just to keep it consistent with the processing in
3970 			 * ip_bind_v4()
3971 			 */
3972 			mp->b_wptr--;
3973 		}
3974 		if (error) {
3975 			/* Red Alert!  Attempting to be a bogon! */
3976 			ip1dbg(("ip_bind: bad src address 0x%x\n",
3977 			    ntohl(src_addr)));
3978 			goto bad_addr;
3979 		}
3980 	}
3981 
3982 	/*
3983 	 * Allow setting new policies. For example, disconnects come
3984 	 * down as ipa_t bind. As we would have set conn_policy_cached
3985 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
3986 	 * can change after the disconnect.
3987 	 */
3988 	connp->conn_policy_cached = B_FALSE;
3989 
3990 	/*
3991 	 * If not fanout_insert this was just an address verification
3992 	 */
3993 	if (fanout_insert) {
3994 		/*
3995 		 * The addresses have been verified. Time to insert in
3996 		 * the correct fanout list.
3997 		 */
3998 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
3999 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4000 		connp->conn_lport = lport;
4001 		connp->conn_fport = 0;
4002 		/*
4003 		 * Do we need to add a check to reject Multicast packets
4004 		 */
4005 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4006 	}
4007 done:
4008 	if (error == 0) {
4009 		if (ire_requested) {
4010 			if (!ip_bind_insert_ire(mp, src_ire, NULL)) {
4011 				error = -1;
4012 				/* Falls through to bad_addr */
4013 			}
4014 		} else if (ipsec_policy_set) {
4015 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4016 				error = -1;
4017 				/* Falls through to bad_addr */
4018 			}
4019 		}
4020 	}
4021 bad_addr:
4022 	if (src_ire != NULL)
4023 		IRE_REFRELE(src_ire);
4024 	if (ipsec_policy_set) {
4025 		ASSERT(policy_mp == mp->b_cont);
4026 		ASSERT(policy_mp != NULL);
4027 		freeb(policy_mp);
4028 		/*
4029 		 * As of now assume that nothing else accompanies
4030 		 * IPSEC_POLICY_SET.
4031 		 */
4032 		mp->b_cont = NULL;
4033 	}
4034 	return (error);
4035 }
4036 
4037 /*
4038  * Verify that both the source and destination addresses
4039  * are valid.  If verify_dst is false, then the destination address may be
4040  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4041  * destination reachability, while tunnels do not.
4042  * Note that we allow connect to broadcast and multicast
4043  * addresses when ire_requested is set. Thus the ULP
4044  * has to check for IRE_BROADCAST and multicast.
4045  *
4046  * Returns zero if ok.
4047  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4048  * (for use with TSYSERR reply).
4049  */
4050 int
4051 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4052     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4053     boolean_t ire_requested, boolean_t ipsec_policy_set,
4054     boolean_t fanout_insert, boolean_t verify_dst)
4055 {
4056 	ire_t		*src_ire;
4057 	ire_t		*dst_ire;
4058 	int		error = 0;
4059 	int 		protocol;
4060 	mblk_t		*policy_mp;
4061 	ire_t		*sire = NULL;
4062 	ire_t		*md_dst_ire = NULL;
4063 	ill_t		*md_ill = NULL;
4064 	zoneid_t	zoneid;
4065 	ipaddr_t	src_addr = *src_addrp;
4066 
4067 	src_ire = dst_ire = NULL;
4068 	protocol = *mp->b_wptr & 0xFF;
4069 
4070 	/*
4071 	 * If we never got a disconnect before, clear it now.
4072 	 */
4073 	connp->conn_fully_bound = B_FALSE;
4074 
4075 	if (ipsec_policy_set) {
4076 		policy_mp = mp->b_cont;
4077 	}
4078 
4079 	zoneid = connp->conn_zoneid;
4080 
4081 	if (CLASSD(dst_addr)) {
4082 		/* Pick up an IRE_BROADCAST */
4083 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4084 		    NULL, zoneid, (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4085 		    MATCH_IRE_RJ_BHOLE));
4086 	} else {
4087 		/*
4088 		 * If conn_dontroute is set, and onlink ipif is not found
4089 		 * set ENETUNREACH error
4090 		 */
4091 		if (connp->conn_dontroute) {
4092 			ipif_t *ipif;
4093 
4094 			ipif = ipif_lookup_onlink_addr(dst_addr, zoneid);
4095 			if (ipif == NULL) {
4096 				error = ENETUNREACH;
4097 				goto bad_addr;
4098 			}
4099 			ipif_refrele(ipif);
4100 		}
4101 		dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL, &sire,
4102 		    zoneid,
4103 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4104 		    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE));
4105 	}
4106 	/*
4107 	 * dst_ire can't be a broadcast when not ire_requested.
4108 	 * We also prevent ire's with src address INADDR_ANY to
4109 	 * be used, which are created temporarily for
4110 	 * sending out packets from endpoints that have
4111 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4112 	 * reachable.  If verify_dst is false, the destination needn't be
4113 	 * reachable.
4114 	 *
4115 	 * If we match on a reject or black hole, then we've got a
4116 	 * local failure.  May as well fail out the connect() attempt,
4117 	 * since it's never going to succeed.
4118 	 */
4119 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4120 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4121 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4122 		/*
4123 		 * If we're verifying destination reachability, we always want
4124 		 * to complain here.
4125 		 *
4126 		 * If we're not verifying destination reachability but the
4127 		 * destination has a route, we still want to fail on the
4128 		 * temporary address and broadcast address tests.
4129 		 */
4130 		if (verify_dst || (dst_ire != NULL)) {
4131 			if (ip_debug > 2) {
4132 				pr_addr_dbg("ip_bind_connected: bad connected "
4133 				    "dst %s\n", AF_INET, &dst_addr);
4134 			}
4135 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4136 				error = ENETUNREACH;
4137 			else
4138 				error = EHOSTUNREACH;
4139 			goto bad_addr;
4140 		}
4141 	}
4142 	/*
4143 	 * If the app does a connect(), it means that it will most likely
4144 	 * send more than 1 packet to the destination.  It makes sense
4145 	 * to clear the temporary flag.
4146 	 */
4147 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4148 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4149 		irb_t *irb = dst_ire->ire_bucket;
4150 
4151 		rw_enter(&irb->irb_lock, RW_WRITER);
4152 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4153 		irb->irb_tmp_ire_cnt--;
4154 		rw_exit(&irb->irb_lock);
4155 	}
4156 
4157 	/*
4158 	 * See if we should notify ULP about MDT; we do this whether or not
4159 	 * ire_requested is TRUE, in order to handle active connects; MDT
4160 	 * eligibility tests for passive connects are handled separately
4161 	 * through tcp_adapt_ire().  We do this before the source address
4162 	 * selection, because dst_ire may change after a call to
4163 	 * ipif_select_source().  This is a best-effort check, as the
4164 	 * packet for this connection may not actually go through
4165 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4166 	 * calling ip_newroute().  This is why we further check on the
4167 	 * IRE during Multidata packet transmission in tcp_multisend().
4168 	 */
4169 	if (ip_multidata_outbound && !ipsec_policy_set && dst_ire != NULL &&
4170 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4171 	    (md_ill = ire_to_ill(dst_ire), md_ill != NULL) &&
4172 	    (md_ill->ill_capabilities & ILL_CAPAB_MDT)) {
4173 		md_dst_ire = dst_ire;
4174 		IRE_REFHOLD(md_dst_ire);
4175 	}
4176 
4177 	if (dst_ire != NULL &&
4178 	    dst_ire->ire_type == IRE_LOCAL &&
4179 	    dst_ire->ire_zoneid != zoneid) {
4180 		/*
4181 		 * If the IRE belongs to a different zone, look for a matching
4182 		 * route in the forwarding table and use the source address from
4183 		 * that route.
4184 		 */
4185 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4186 		    zoneid, 0,
4187 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4188 		    MATCH_IRE_RJ_BHOLE);
4189 		if (src_ire == NULL) {
4190 			error = EHOSTUNREACH;
4191 			goto bad_addr;
4192 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4193 			if (!(src_ire->ire_type & IRE_HOST))
4194 				error = ENETUNREACH;
4195 			else
4196 				error = EHOSTUNREACH;
4197 			goto bad_addr;
4198 		}
4199 		if (src_addr == INADDR_ANY)
4200 			src_addr = src_ire->ire_src_addr;
4201 		ire_refrele(src_ire);
4202 		src_ire = NULL;
4203 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4204 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4205 			src_addr = sire->ire_src_addr;
4206 			ire_refrele(dst_ire);
4207 			dst_ire = sire;
4208 			sire = NULL;
4209 		} else {
4210 			/*
4211 			 * Pick a source address so that a proper inbound
4212 			 * load spreading would happen.
4213 			 */
4214 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4215 			ipif_t *src_ipif = NULL;
4216 			ire_t *ipif_ire;
4217 
4218 			/*
4219 			 * Supply a local source address such that inbound
4220 			 * load spreading happens.
4221 			 *
4222 			 * Determine the best source address on this ill for
4223 			 * the destination.
4224 			 *
4225 			 * 1) For broadcast, we should return a broadcast ire
4226 			 *    found above so that upper layers know that the
4227 			 *    destination address is a broadcast address.
4228 			 *
4229 			 * 2) If this is part of a group, select a better
4230 			 *    source address so that better inbound load
4231 			 *    balancing happens. Do the same if the ipif
4232 			 *    is DEPRECATED.
4233 			 *
4234 			 * 3) If the outgoing interface is part of a usesrc
4235 			 *    group, then try selecting a source address from
4236 			 *    the usesrc ILL.
4237 			 */
4238 			if (!(dst_ire->ire_type & IRE_BROADCAST) &&
4239 			    ((dst_ill->ill_group != NULL) ||
4240 			    (dst_ire->ire_ipif->ipif_flags &
4241 			    IPIF_DEPRECATED) ||
4242 			    (dst_ill->ill_usesrc_ifindex != 0))) {
4243 				src_ipif = ipif_select_source(dst_ill,
4244 				    dst_addr, zoneid);
4245 				if (src_ipif != NULL) {
4246 					if (IS_VNI(src_ipif->ipif_ill)) {
4247 						/*
4248 						 * For VNI there is no
4249 						 * interface route
4250 						 */
4251 						src_addr =
4252 						    src_ipif->ipif_src_addr;
4253 					} else {
4254 						ipif_ire =
4255 						    ipif_to_ire(src_ipif);
4256 						if (ipif_ire != NULL) {
4257 							IRE_REFRELE(dst_ire);
4258 							dst_ire = ipif_ire;
4259 						}
4260 						src_addr =
4261 						    dst_ire->ire_src_addr;
4262 					}
4263 					ipif_refrele(src_ipif);
4264 				} else {
4265 					src_addr = dst_ire->ire_src_addr;
4266 				}
4267 			} else {
4268 				src_addr = dst_ire->ire_src_addr;
4269 			}
4270 		}
4271 	}
4272 
4273 	/*
4274 	 * We do ire_route_lookup() here (and not
4275 	 * interface lookup as we assert that
4276 	 * src_addr should only come from an
4277 	 * UP interface for hard binding.
4278 	 */
4279 	ASSERT(src_ire == NULL);
4280 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
4281 	    NULL, zoneid, MATCH_IRE_ZONEONLY);
4282 	/* src_ire must be a local|loopback */
4283 	if (!IRE_IS_LOCAL(src_ire)) {
4284 		if (ip_debug > 2) {
4285 			pr_addr_dbg("ip_bind_connected: bad connected "
4286 			    "src %s\n", AF_INET, &src_addr);
4287 		}
4288 		error = EADDRNOTAVAIL;
4289 		goto bad_addr;
4290 	}
4291 
4292 	/*
4293 	 * If the source address is a loopback address, the
4294 	 * destination had best be local or multicast.
4295 	 * The transports that can't handle multicast will reject
4296 	 * those addresses.
4297 	 */
4298 	if (src_ire->ire_type == IRE_LOOPBACK &&
4299 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
4300 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
4301 		error = -1;
4302 		goto bad_addr;
4303 	}
4304 
4305 	/*
4306 	 * Allow setting new policies. For example, disconnects come
4307 	 * down as ipa_t bind. As we would have set conn_policy_cached
4308 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4309 	 * can change after the disconnect.
4310 	 */
4311 	connp->conn_policy_cached = B_FALSE;
4312 
4313 	/*
4314 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
4315 	 * can handle their passed-in conn's.
4316 	 */
4317 
4318 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4319 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
4320 	connp->conn_lport = lport;
4321 	connp->conn_fport = fport;
4322 	*src_addrp = src_addr;
4323 
4324 	ASSERT(!(ipsec_policy_set && ire_requested));
4325 	if (ire_requested) {
4326 		iulp_t *ulp_info = NULL;
4327 
4328 		/*
4329 		 * Note that sire will not be NULL if this is an off-link
4330 		 * connection and there is not cache for that dest yet.
4331 		 *
4332 		 * XXX Because of an existing bug, if there are multiple
4333 		 * default routes, the IRE returned now may not be the actual
4334 		 * default route used (default routes are chosen in a
4335 		 * round robin fashion).  So if the metrics for different
4336 		 * default routes are different, we may return the wrong
4337 		 * metrics.  This will not be a problem if the existing
4338 		 * bug is fixed.
4339 		 */
4340 		if (sire != NULL) {
4341 			ulp_info = &(sire->ire_uinfo);
4342 		}
4343 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info)) {
4344 			error = -1;
4345 			goto bad_addr;
4346 		}
4347 	} else if (ipsec_policy_set) {
4348 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4349 			error = -1;
4350 			goto bad_addr;
4351 		}
4352 	}
4353 
4354 	/*
4355 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
4356 	 * we'll cache that.  If we don't, we'll inherit global policy.
4357 	 *
4358 	 * We can't insert until the conn reflects the policy. Note that
4359 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
4360 	 * connections where we don't have a policy. This is to prevent
4361 	 * global policy lookups in the inbound path.
4362 	 *
4363 	 * If we insert before we set conn_policy_cached,
4364 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
4365 	 * because global policy cound be non-empty. We normally call
4366 	 * ipsec_check_policy() for conn_policy_cached connections only if
4367 	 * ipc_in_enforce_policy is set. But in this case,
4368 	 * conn_policy_cached can get set anytime since we made the
4369 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
4370 	 * called, which will make the above assumption false.  Thus, we
4371 	 * need to insert after we set conn_policy_cached.
4372 	 */
4373 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
4374 		goto bad_addr;
4375 
4376 	if (fanout_insert) {
4377 		/*
4378 		 * The addresses have been verified. Time to insert in
4379 		 * the correct fanout list.
4380 		 */
4381 		error = ipcl_conn_insert(connp, protocol, src_addr,
4382 		    dst_addr, connp->conn_ports);
4383 	}
4384 
4385 	if (error == 0) {
4386 		connp->conn_fully_bound = B_TRUE;
4387 		/*
4388 		 * Our initial checks for MDT have passed; the IRE is not
4389 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
4390 		 * be supporting MDT.  Pass the IRE, IPC and ILL into
4391 		 * ip_mdinfo_return(), which performs further checks
4392 		 * against them and upon success, returns the MDT info
4393 		 * mblk which we will attach to the bind acknowledgment.
4394 		 */
4395 		if (md_dst_ire != NULL) {
4396 			mblk_t *mdinfo_mp;
4397 
4398 			ASSERT(md_ill != NULL);
4399 			ASSERT(md_ill->ill_mdt_capab != NULL);
4400 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
4401 			    md_ill->ill_name, md_ill->ill_mdt_capab)) != NULL)
4402 				linkb(mp, mdinfo_mp);
4403 		}
4404 	}
4405 bad_addr:
4406 	if (ipsec_policy_set) {
4407 		ASSERT(policy_mp == mp->b_cont);
4408 		ASSERT(policy_mp != NULL);
4409 		freeb(policy_mp);
4410 		/*
4411 		 * As of now assume that nothing else accompanies
4412 		 * IPSEC_POLICY_SET.
4413 		 */
4414 		mp->b_cont = NULL;
4415 	}
4416 	if (src_ire != NULL)
4417 		IRE_REFRELE(src_ire);
4418 	if (dst_ire != NULL)
4419 		IRE_REFRELE(dst_ire);
4420 	if (sire != NULL)
4421 		IRE_REFRELE(sire);
4422 	if (md_dst_ire != NULL)
4423 		IRE_REFRELE(md_dst_ire);
4424 	return (error);
4425 }
4426 
4427 /*
4428  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
4429  * Prefers dst_ire over src_ire.
4430  */
4431 static boolean_t
4432 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info)
4433 {
4434 	mblk_t	*mp1;
4435 	ire_t *ret_ire = NULL;
4436 
4437 	mp1 = mp->b_cont;
4438 	ASSERT(mp1 != NULL);
4439 
4440 	if (ire != NULL) {
4441 		/*
4442 		 * mp1 initialized above to IRE_DB_REQ_TYPE
4443 		 * appended mblk. Its <upper protocol>'s
4444 		 * job to make sure there is room.
4445 		 */
4446 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
4447 			return (0);
4448 
4449 		mp1->b_datap->db_type = IRE_DB_TYPE;
4450 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
4451 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
4452 		ret_ire = (ire_t *)mp1->b_rptr;
4453 		/*
4454 		 * Pass the latest setting of the ip_path_mtu_discovery and
4455 		 * copy the ulp info if any.
4456 		 */
4457 		ret_ire->ire_frag_flag |= (ip_path_mtu_discovery) ?
4458 		    IPH_DF : 0;
4459 		if (ulp_info != NULL) {
4460 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
4461 			    sizeof (iulp_t));
4462 		}
4463 		ret_ire->ire_mp = mp1;
4464 	} else {
4465 		/*
4466 		 * No IRE was found. Remove IRE mblk.
4467 		 */
4468 		mp->b_cont = mp1->b_cont;
4469 		freeb(mp1);
4470 	}
4471 
4472 	return (1);
4473 }
4474 
4475 /*
4476  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
4477  * the final piece where we don't.  Return a pointer to the first mblk in the
4478  * result, and update the pointer to the next mblk to chew on.  If anything
4479  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
4480  * NULL pointer.
4481  */
4482 mblk_t *
4483 ip_carve_mp(mblk_t **mpp, ssize_t len)
4484 {
4485 	mblk_t	*mp0;
4486 	mblk_t	*mp1;
4487 	mblk_t	*mp2;
4488 
4489 	if (!len || !mpp || !(mp0 = *mpp))
4490 		return (NULL);
4491 	/* If we aren't going to consume the first mblk, we need a dup. */
4492 	if (mp0->b_wptr - mp0->b_rptr > len) {
4493 		mp1 = dupb(mp0);
4494 		if (mp1) {
4495 			/* Partition the data between the two mblks. */
4496 			mp1->b_wptr = mp1->b_rptr + len;
4497 			mp0->b_rptr = mp1->b_wptr;
4498 			/*
4499 			 * after adjustments if mblk not consumed is now
4500 			 * unaligned, try to align it. If this fails free
4501 			 * all messages and let upper layer recover.
4502 			 */
4503 			if (!OK_32PTR(mp0->b_rptr)) {
4504 				if (!pullupmsg(mp0, -1)) {
4505 					freemsg(mp0);
4506 					freemsg(mp1);
4507 					*mpp = NULL;
4508 					return (NULL);
4509 				}
4510 			}
4511 		}
4512 		return (mp1);
4513 	}
4514 	/* Eat through as many mblks as we need to get len bytes. */
4515 	len -= mp0->b_wptr - mp0->b_rptr;
4516 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
4517 		if (mp2->b_wptr - mp2->b_rptr > len) {
4518 			/*
4519 			 * We won't consume the entire last mblk.  Like
4520 			 * above, dup and partition it.
4521 			 */
4522 			mp1->b_cont = dupb(mp2);
4523 			mp1 = mp1->b_cont;
4524 			if (!mp1) {
4525 				/*
4526 				 * Trouble.  Rather than go to a lot of
4527 				 * trouble to clean up, we free the messages.
4528 				 * This won't be any worse than losing it on
4529 				 * the wire.
4530 				 */
4531 				freemsg(mp0);
4532 				freemsg(mp2);
4533 				*mpp = NULL;
4534 				return (NULL);
4535 			}
4536 			mp1->b_wptr = mp1->b_rptr + len;
4537 			mp2->b_rptr = mp1->b_wptr;
4538 			/*
4539 			 * after adjustments if mblk not consumed is now
4540 			 * unaligned, try to align it. If this fails free
4541 			 * all messages and let upper layer recover.
4542 			 */
4543 			if (!OK_32PTR(mp2->b_rptr)) {
4544 				if (!pullupmsg(mp2, -1)) {
4545 					freemsg(mp0);
4546 					freemsg(mp2);
4547 					*mpp = NULL;
4548 					return (NULL);
4549 				}
4550 			}
4551 			*mpp = mp2;
4552 			return (mp0);
4553 		}
4554 		/* Decrement len by the amount we just got. */
4555 		len -= mp2->b_wptr - mp2->b_rptr;
4556 	}
4557 	/*
4558 	 * len should be reduced to zero now.  If not our caller has
4559 	 * screwed up.
4560 	 */
4561 	if (len) {
4562 		/* Shouldn't happen! */
4563 		freemsg(mp0);
4564 		*mpp = NULL;
4565 		return (NULL);
4566 	}
4567 	/*
4568 	 * We consumed up to exactly the end of an mblk.  Detach the part
4569 	 * we are returning from the rest of the chain.
4570 	 */
4571 	mp1->b_cont = NULL;
4572 	*mpp = mp2;
4573 	return (mp0);
4574 }
4575 
4576 /* The ill stream is being unplumbed. Called from ip_close */
4577 int
4578 ip_modclose(ill_t *ill)
4579 {
4580 
4581 	boolean_t success;
4582 	ipsq_t	*ipsq;
4583 	ipif_t	*ipif;
4584 	queue_t	*q = ill->ill_rq;
4585 
4586 	/*
4587 	 * Forcibly enter the ipsq after some delay. This is to take
4588 	 * care of the case when some ioctl does not complete because
4589 	 * we sent a control message to the driver and it did not
4590 	 * send us a reply. We want to be able to at least unplumb
4591 	 * and replumb rather than force the user to reboot the system.
4592 	 */
4593 	success = ipsq_enter(ill, B_FALSE);
4594 
4595 	/*
4596 	 * Open/close/push/pop is guaranteed to be single threaded
4597 	 * per stream by STREAMS. FS guarantees that all references
4598 	 * from top are gone before close is called. So there can't
4599 	 * be another close thread that has set CONDEMNED on this ill.
4600 	 * and cause ipsq_enter to return failure.
4601 	 */
4602 	ASSERT(success);
4603 	ipsq = ill->ill_phyint->phyint_ipsq;
4604 
4605 	/*
4606 	 * Mark it condemned. No new reference will be made to this ill.
4607 	 * Lookup functions will return an error. Threads that try to
4608 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
4609 	 * that the refcnt will drop down to zero.
4610 	 */
4611 	mutex_enter(&ill->ill_lock);
4612 	ill->ill_state_flags |= ILL_CONDEMNED;
4613 	for (ipif = ill->ill_ipif; ipif != NULL;
4614 	    ipif = ipif->ipif_next) {
4615 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
4616 	}
4617 	/*
4618 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
4619 	 * returns  error if ILL_CONDEMNED is set
4620 	 */
4621 	cv_broadcast(&ill->ill_cv);
4622 	mutex_exit(&ill->ill_lock);
4623 
4624 	/*
4625 	 * Shut down fragmentation reassembly.
4626 	 * ill_frag_timer won't start a timer again.
4627 	 * Now cancel any existing timer
4628 	 */
4629 	(void) untimeout(ill->ill_frag_timer_id);
4630 	(void) ill_frag_timeout(ill, 0);
4631 
4632 	/*
4633 	 * If MOVE was in progress, clear the
4634 	 * move_in_progress fields also.
4635 	 */
4636 	if (ill->ill_move_in_progress) {
4637 		ILL_CLEAR_MOVE(ill);
4638 	}
4639 
4640 	/*
4641 	 * Call ill_delete to bring down the ipifs, ilms and ill on
4642 	 * this ill. Then wait for the refcnts to drop to zero.
4643 	 * ill_is_quiescent checks whether the ill is really quiescent.
4644 	 * Then make sure that threads that are waiting to enter the
4645 	 * ipsq have seen the error returned by ipsq_enter and have
4646 	 * gone away. Then we call ill_delete_tail which does the
4647 	 * DL_UNBIND and DL_DETACH with the driver and then qprocsoff.
4648 	 */
4649 	ill_delete(ill);
4650 	mutex_enter(&ill->ill_lock);
4651 	while (!ill_is_quiescent(ill))
4652 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4653 	while (ill->ill_waiters)
4654 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4655 
4656 	mutex_exit(&ill->ill_lock);
4657 
4658 	/* qprocsoff is called in ill_delete_tail */
4659 	ill_delete_tail(ill);
4660 
4661 	/*
4662 	 * Walk through all upper (conn) streams and qenable
4663 	 * those that have queued data.
4664 	 * close synchronization needs this to
4665 	 * be done to ensure that all upper layers blocked
4666 	 * due to flow control to the closing device
4667 	 * get unblocked.
4668 	 */
4669 	ip1dbg(("ip_wsrv: walking\n"));
4670 	conn_walk_drain();
4671 
4672 	mutex_enter(&ip_mi_lock);
4673 	mi_close_unlink(&ip_g_head, (IDP)ill);
4674 	mutex_exit(&ip_mi_lock);
4675 
4676 	/*
4677 	 * credp could be null if the open didn't succeed and ip_modopen
4678 	 * itself calls ip_close.
4679 	 */
4680 	if (ill->ill_credp != NULL)
4681 		crfree(ill->ill_credp);
4682 
4683 	mi_close_free((IDP)ill);
4684 	q->q_ptr = WR(q)->q_ptr = NULL;
4685 
4686 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
4687 
4688 	return (0);
4689 }
4690 
4691 /*
4692  * IP has been configured as _D_QNEXTLESS for the client side i.e the driver
4693  * instance. This implies that
4694  * 1. IP cannot access the read side q_next pointer directly - it must
4695  *    use routines like putnext and canputnext.
4696  * 2. ip_close must ensure that all sources of messages being putnext upstream
4697  *    are gone before qprocsoff is called.
4698  *
4699  * #2 is handled by having ip_close do the ipcl_hash_remove and wait for
4700  * conn_ref to drop to zero before calling qprocsoff.
4701  */
4702 
4703 /* ARGSUSED */
4704 int
4705 ip_close(queue_t *q, int flags)
4706 {
4707 	conn_t		*connp;
4708 	boolean_t	drain_cleanup_reqd = B_FALSE;
4709 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
4710 	boolean_t	ilg_cleanup_reqd = B_FALSE;
4711 
4712 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
4713 
4714 	/*
4715 	 * Call the appropriate delete routine depending on whether this is
4716 	 * a module or device.
4717 	 */
4718 	if (WR(q)->q_next != NULL) {
4719 		/* This is a module close */
4720 		return (ip_modclose((ill_t *)q->q_ptr));
4721 	}
4722 
4723 	connp = Q_TO_CONN(q);
4724 	ASSERT(connp->conn_tcp == NULL);
4725 
4726 	/*
4727 	 * We are being closed as /dev/ip or /dev/ip6.
4728 	 *
4729 	 * Mark the conn as closing, and this conn must not be
4730 	 * inserted in future into any list. Eg. conn_drain_insert(),
4731 	 * won't insert this conn into the conn_drain_list.
4732 	 * Similarly ill_pending_mp_add() will not add any mp to
4733 	 * the pending mp list, after this conn has started closing.
4734 	 *
4735 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
4736 	 * cannot get set henceforth.
4737 	 */
4738 	mutex_enter(&connp->conn_lock);
4739 	connp->conn_state_flags |= CONN_CLOSING;
4740 	if (connp->conn_idl != NULL)
4741 		drain_cleanup_reqd = B_TRUE;
4742 	if (connp->conn_oper_pending_ill != NULL)
4743 		conn_ioctl_cleanup_reqd = B_TRUE;
4744 	if (connp->conn_ilg_inuse != 0)
4745 		ilg_cleanup_reqd = B_TRUE;
4746 	mutex_exit(&connp->conn_lock);
4747 
4748 	if (conn_ioctl_cleanup_reqd)
4749 		conn_ioctl_cleanup(connp);
4750 
4751 	/*
4752 	 * Remove this conn from any fanout list it is on.
4753 	 * Then wait until the number of pending putnexts from
4754 	 * the fanout code drops to zero, before calling qprocsoff.
4755 	 * This is the guarantee a QNEXTLESS driver provides to
4756 	 * STREAMS, and is mentioned at the top of this function.
4757 	 */
4758 
4759 	ipcl_hash_remove(connp);
4760 
4761 	/*
4762 	 * Remove this conn from the drain list, and do
4763 	 * any other cleanup that may be required.
4764 	 * (Only non-tcp streams may have a non-null conn_idl.
4765 	 * TCP streams are never flow controlled, and
4766 	 * conn_idl will be null)
4767 	 */
4768 	if (drain_cleanup_reqd)
4769 		conn_drain_tail(connp, B_TRUE);
4770 
4771 	if (connp->conn_rq == ip_g_mrouter || connp->conn_wq == ip_g_mrouter)
4772 		(void) ip_mrouter_done(NULL);
4773 
4774 	if (ilg_cleanup_reqd)
4775 		ilg_delete_all(connp);
4776 
4777 	conn_delete_ire(connp, NULL);
4778 
4779 
4780 	/*
4781 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
4782 	 * callers from write side can't be there now because close
4783 	 * is in progress. The only other caller is ipcl_walk
4784 	 * which checks for the condemned flag.
4785 	 */
4786 	mutex_enter(&connp->conn_lock);
4787 	connp->conn_state_flags |= CONN_CONDEMNED;
4788 	while (connp->conn_ref != 1)
4789 		cv_wait(&connp->conn_cv, &connp->conn_lock);
4790 	mutex_exit(&connp->conn_lock);
4791 
4792 	qprocsoff(q);
4793 
4794 	/*
4795 	 * Now we are truly single threaded on this stream, and can
4796 	 * delete the things hanging off the connp, and finally the connp.
4797 	 * We removed this connp from the fanout list, it cannot be
4798 	 * accessed thru the fanouts, and we already waited for the
4799 	 * conn_ref to drop to 0. We are already in close, so
4800 	 * there cannot be any other thread from the top. qprocsoff
4801 	 * has completed, and service has completed or won't run in
4802 	 * future.
4803 	 */
4804 	if (connp->conn_latch != NULL) {
4805 		IPLATCH_REFRELE(connp->conn_latch);
4806 		connp->conn_latch = NULL;
4807 	}
4808 	if (connp->conn_policy != NULL) {
4809 		IPPH_REFRELE(connp->conn_policy);
4810 		connp->conn_policy = NULL;
4811 	}
4812 	if (connp->conn_ipsec_opt_mp != NULL) {
4813 		freemsg(connp->conn_ipsec_opt_mp);
4814 		connp->conn_ipsec_opt_mp = NULL;
4815 	}
4816 	if (connp->conn_cred != NULL) {
4817 		crfree(connp->conn_cred);
4818 		connp->conn_cred = NULL;
4819 	}
4820 
4821 	inet_minor_free(ip_minor_arena, connp->conn_dev);
4822 
4823 	connp->conn_ref--;
4824 	ipcl_conn_destroy(connp);
4825 
4826 	q->q_ptr = WR(q)->q_ptr = NULL;
4827 	return (0);
4828 }
4829 
4830 /* Return the IP checksum for the IP header at "iph". */
4831 uint16_t
4832 ip_csum_hdr(ipha_t *ipha)
4833 {
4834 	uint16_t	*uph;
4835 	uint32_t	sum;
4836 	int		opt_len;
4837 
4838 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
4839 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
4840 	uph = (uint16_t *)ipha;
4841 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
4842 		uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
4843 	if (opt_len > 0) {
4844 		do {
4845 			sum += uph[10];
4846 			sum += uph[11];
4847 			uph += 2;
4848 		} while (--opt_len);
4849 	}
4850 	sum = (sum & 0xFFFF) + (sum >> 16);
4851 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
4852 	if (sum == 0xffff)
4853 		sum = 0;
4854 	return ((uint16_t)sum);
4855 }
4856 
4857 void
4858 ip_ddi_destroy(void)
4859 {
4860 	tcp_ddi_destroy();
4861 	sctp_ddi_destroy();
4862 	ipsec_loader_destroy();
4863 	ipsec_policy_destroy();
4864 	ipsec_kstat_destroy();
4865 	nd_free(&ip_g_nd);
4866 	mutex_destroy(&igmp_timer_lock);
4867 	mutex_destroy(&mld_timer_lock);
4868 	mutex_destroy(&igmp_slowtimeout_lock);
4869 	mutex_destroy(&mld_slowtimeout_lock);
4870 	mutex_destroy(&ip_mi_lock);
4871 	mutex_destroy(&rts_clients.connf_lock);
4872 	ip_ire_fini();
4873 	ip6_asp_free();
4874 	conn_drain_fini();
4875 	ipcl_destroy();
4876 	inet_minor_destroy(ip_minor_arena);
4877 	icmp_kstat_fini();
4878 	ip_kstat_fini();
4879 	rw_destroy(&ipsec_capab_ills_lock);
4880 	rw_destroy(&ill_g_usesrc_lock);
4881 	ip_drop_unregister(&ip_dropper);
4882 }
4883 
4884 
4885 void
4886 ip_ddi_init(void)
4887 {
4888 	TCP6_MAJ = ddi_name_to_major(TCP6);
4889 	TCP_MAJ	= ddi_name_to_major(TCP);
4890 	SCTP_MAJ = ddi_name_to_major(SCTP);
4891 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
4892 
4893 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
4894 
4895 	/* IP's IPsec code calls the packet dropper */
4896 	ip_drop_register(&ip_dropper, "IP IPsec processing");
4897 
4898 	if (!ip_g_nd) {
4899 		if (!ip_param_register(lcl_param_arr, A_CNT(lcl_param_arr),
4900 		    lcl_ndp_arr, A_CNT(lcl_ndp_arr))) {
4901 			nd_free(&ip_g_nd);
4902 		}
4903 	}
4904 
4905 	ipsec_loader_init();
4906 	ipsec_policy_init();
4907 	ipsec_kstat_init();
4908 	rw_init(&ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
4909 	mutex_init(&igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4910 	mutex_init(&mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4911 	mutex_init(&igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4912 	mutex_init(&mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4913 	mutex_init(&ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
4914 	mutex_init(&ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
4915 	rw_init(&ill_g_lock, NULL, RW_DEFAULT, NULL);
4916 	rw_init(&ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
4917 	rw_init(&ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
4918 
4919 	/*
4920 	 * For IP and TCP the minor numbers should start from 2 since we have 4
4921 	 * initial devices: ip, ip6, tcp, tcp6.
4922 	 */
4923 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
4924 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
4925 		cmn_err(CE_PANIC,
4926 		    "ip_ddi_init: ip_minor_arena creation failed\n");
4927 	}
4928 
4929 	ipcl_init();
4930 	mutex_init(&rts_clients.connf_lock, NULL, MUTEX_DEFAULT, NULL);
4931 	ip_ire_init();
4932 	ip6_asp_init();
4933 	ipif_init();
4934 	conn_drain_init();
4935 	tcp_ddi_init();
4936 	sctp_ddi_init();
4937 
4938 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
4939 
4940 	if ((ip_kstat = kstat_create("ip", 0, "ipstat",
4941 		"net", KSTAT_TYPE_NAMED,
4942 		sizeof (ip_statistics) / sizeof (kstat_named_t),
4943 		KSTAT_FLAG_VIRTUAL)) != NULL) {
4944 		ip_kstat->ks_data = &ip_statistics;
4945 		kstat_install(ip_kstat);
4946 	}
4947 	ip_kstat_init();
4948 	ip6_kstat_init();
4949 	icmp_kstat_init();
4950 
4951 	ipsec_loader_start();
4952 }
4953 
4954 /*
4955  * Allocate and initialize a DLPI template of the specified length.  (May be
4956  * called as writer.)
4957  */
4958 mblk_t *
4959 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
4960 {
4961 	mblk_t	*mp;
4962 
4963 	mp = allocb(len, BPRI_MED);
4964 	if (!mp)
4965 		return (NULL);
4966 
4967 	/*
4968 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
4969 	 * of which we don't seem to use) are sent with M_PCPROTO, and
4970 	 * that other DLPI are M_PROTO.
4971 	 */
4972 	if (prim == DL_INFO_REQ) {
4973 		mp->b_datap->db_type = M_PCPROTO;
4974 	} else {
4975 		mp->b_datap->db_type = M_PROTO;
4976 	}
4977 
4978 	mp->b_wptr = mp->b_rptr + len;
4979 	bzero(mp->b_rptr, len);
4980 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
4981 	return (mp);
4982 }
4983 
4984 const char *
4985 dlpi_prim_str(int prim)
4986 {
4987 	switch (prim) {
4988 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
4989 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
4990 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
4991 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
4992 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
4993 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
4994 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
4995 	case DL_OK_ACK:		return ("DL_OK_ACK");
4996 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
4997 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
4998 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
4999 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
5000 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
5001 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
5002 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
5003 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
5004 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
5005 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
5006 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
5007 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
5008 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
5009 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
5010 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
5011 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
5012 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
5013 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
5014 	default:		return ("<unknown primitive>");
5015 	}
5016 }
5017 
5018 const char *
5019 dlpi_err_str(int err)
5020 {
5021 	switch (err) {
5022 	case DL_ACCESS:		return ("DL_ACCESS");
5023 	case DL_BADADDR:	return ("DL_BADADDR");
5024 	case DL_BADCORR:	return ("DL_BADCORR");
5025 	case DL_BADDATA:	return ("DL_BADDATA");
5026 	case DL_BADPPA:		return ("DL_BADPPA");
5027 	case DL_BADPRIM:	return ("DL_BADPRIM");
5028 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
5029 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
5030 	case DL_BADSAP:		return ("DL_BADSAP");
5031 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
5032 	case DL_BOUND:		return ("DL_BOUND");
5033 	case DL_INITFAILED:	return ("DL_INITFAILED");
5034 	case DL_NOADDR:		return ("DL_NOADDR");
5035 	case DL_NOTINIT:	return ("DL_NOTINIT");
5036 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
5037 	case DL_SYSERR:		return ("DL_SYSERR");
5038 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
5039 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
5040 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
5041 	case DL_TOOMANY:	return ("DL_TOOMANY");
5042 	case DL_NOTENAB:	return ("DL_NOTENAB");
5043 	case DL_BUSY:		return ("DL_BUSY");
5044 	case DL_NOAUTO:		return ("DL_NOAUTO");
5045 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
5046 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
5047 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
5048 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
5049 	case DL_PENDING:	return ("DL_PENDING");
5050 	default:		return ("<unknown error>");
5051 	}
5052 }
5053 
5054 /*
5055  * Debug formatting routine.  Returns a character string representation of the
5056  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5057  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
5058  */
5059 char *
5060 ip_dot_addr(ipaddr_t addr, char *buf)
5061 {
5062 	return (ip_dot_saddr((uchar_t *)&addr, buf));
5063 }
5064 
5065 /*
5066  * Debug formatting routine.  Returns a character string representation of the
5067  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5068  * as a pointer.  The "xxx" parts including left zero padding so the final
5069  * string will fit easily in tables.  It would be nice to take a padding
5070  * length argument instead.
5071  */
5072 static char *
5073 ip_dot_saddr(uchar_t *addr, char *buf)
5074 {
5075 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
5076 	    addr[0] & 0xFF, addr[1] & 0xFF, addr[2] & 0xFF, addr[3] & 0xFF);
5077 	return (buf);
5078 }
5079 
5080 /*
5081  * Send an ICMP error after patching up the packet appropriately.  Returns
5082  * non-zero if the appropriate MIB should be bumped; zero otherwise.
5083  */
5084 static int
5085 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
5086     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present, zoneid_t zoneid)
5087 {
5088 	ipha_t *ipha;
5089 	mblk_t *first_mp;
5090 	boolean_t secure;
5091 	unsigned char db_type;
5092 
5093 	first_mp = mp;
5094 	if (mctl_present) {
5095 		mp = mp->b_cont;
5096 		secure = ipsec_in_is_secure(first_mp);
5097 		ASSERT(mp != NULL);
5098 	} else {
5099 		/*
5100 		 * If this is an ICMP error being reported - which goes
5101 		 * up as M_CTLs, we need to convert them to M_DATA till
5102 		 * we finish checking with global policy because
5103 		 * ipsec_check_global_policy() assumes M_DATA as clear
5104 		 * and M_CTL as secure.
5105 		 */
5106 		db_type = mp->b_datap->db_type;
5107 		mp->b_datap->db_type = M_DATA;
5108 		secure = B_FALSE;
5109 	}
5110 	/*
5111 	 * We are generating an icmp error for some inbound packet.
5112 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
5113 	 * Before we generate an error, check with global policy
5114 	 * to see whether this is allowed to enter the system. As
5115 	 * there is no "conn", we are checking with global policy.
5116 	 */
5117 	ipha = (ipha_t *)mp->b_rptr;
5118 	if (secure || ipsec_inbound_v4_policy_present) {
5119 		first_mp = ipsec_check_global_policy(first_mp, NULL,
5120 		    ipha, NULL, mctl_present);
5121 		if (first_mp == NULL)
5122 			return (0);
5123 	}
5124 
5125 	if (!mctl_present)
5126 		mp->b_datap->db_type = db_type;
5127 
5128 	if (flags & IP_FF_SEND_ICMP) {
5129 		if (flags & IP_FF_HDR_COMPLETE) {
5130 			if (ip_hdr_complete(ipha, zoneid)) {
5131 				freemsg(first_mp);
5132 				return (1);
5133 			}
5134 		}
5135 		if (flags & IP_FF_CKSUM) {
5136 			/*
5137 			 * Have to correct checksum since
5138 			 * the packet might have been
5139 			 * fragmented and the reassembly code in ip_rput
5140 			 * does not restore the IP checksum.
5141 			 */
5142 			ipha->ipha_hdr_checksum = 0;
5143 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
5144 		}
5145 		switch (icmp_type) {
5146 		case ICMP_DEST_UNREACHABLE:
5147 			icmp_unreachable(WR(q), first_mp, icmp_code);
5148 			break;
5149 		default:
5150 			freemsg(first_mp);
5151 			break;
5152 		}
5153 	} else {
5154 		freemsg(first_mp);
5155 		return (0);
5156 	}
5157 
5158 	return (1);
5159 }
5160 
5161 #ifdef DEBUG
5162 /*
5163  * Copy the header into the IPSEC_IN message.
5164  */
5165 static void
5166 ipsec_inbound_debug_tag(mblk_t *ipsec_mp)
5167 {
5168 	mblk_t *data_mp = ipsec_mp->b_cont;
5169 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
5170 	ipha_t *ipha;
5171 
5172 	if (ii->ipsec_in_type != IPSEC_IN)
5173 		return;
5174 	ASSERT(data_mp != NULL);
5175 
5176 	ipha = (ipha_t *)data_mp->b_rptr;
5177 	bcopy(ipha, ii->ipsec_in_saved_hdr,
5178 	    (IPH_HDR_VERSION(ipha) == IP_VERSION) ?
5179 	    sizeof (ipha_t) : sizeof (ip6_t));
5180 }
5181 #else
5182 #define	ipsec_inbound_debug_tag(x)	/* NOP */
5183 #endif	/* DEBUG */
5184 
5185 /*
5186  * Used to send an ICMP error message when a packet is received for
5187  * a protocol that is not supported. The mblk passed as argument
5188  * is consumed by this function.
5189  */
5190 void
5191 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid)
5192 {
5193 	mblk_t *mp;
5194 	ipha_t *ipha;
5195 	ill_t *ill;
5196 	ipsec_in_t *ii;
5197 
5198 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
5199 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
5200 
5201 	mp = ipsec_mp->b_cont;
5202 	ipsec_mp->b_cont = NULL;
5203 	ipha = (ipha_t *)mp->b_rptr;
5204 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
5205 		if (ip_fanout_send_icmp(q, mp, flags, ICMP_DEST_UNREACHABLE,
5206 		    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid)) {
5207 			BUMP_MIB(&ip_mib, ipInUnknownProtos);
5208 		}
5209 	} else {
5210 		/* Get ill from index in ipsec_in_t. */
5211 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
5212 		    B_TRUE, NULL, NULL, NULL, NULL);
5213 		if (ill != NULL) {
5214 			if (ip_fanout_send_icmp_v6(q, mp, flags,
5215 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
5216 			    0, B_FALSE, zoneid)) {
5217 				BUMP_MIB(ill->ill_ip6_mib, ipv6InUnknownProtos);
5218 			}
5219 
5220 			ill_refrele(ill);
5221 		} else { /* re-link for the freemsg() below. */
5222 			ipsec_mp->b_cont = mp;
5223 		}
5224 	}
5225 
5226 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
5227 	freemsg(ipsec_mp);
5228 }
5229 
5230 /*
5231  * See if the inbound datagram has had IPsec processing applied to it.
5232  */
5233 boolean_t
5234 ipsec_in_is_secure(mblk_t *ipsec_mp)
5235 {
5236 	ipsec_in_t *ii;
5237 
5238 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
5239 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
5240 
5241 	if (ii->ipsec_in_loopback) {
5242 		return (ii->ipsec_in_secure);
5243 	} else {
5244 		return (ii->ipsec_in_ah_sa != NULL ||
5245 		    ii->ipsec_in_esp_sa != NULL ||
5246 		    ii->ipsec_in_decaps);
5247 	}
5248 }
5249 
5250 /*
5251  * Handle protocols with which IP is less intimate.  There
5252  * can be more than one stream bound to a particular
5253  * protocol.  When this is the case, normally each one gets a copy
5254  * of any incoming packets.
5255  *
5256  * IPSEC NOTE :
5257  *
5258  * Don't allow a secure packet going up a non-secure connection.
5259  * We don't allow this because
5260  *
5261  * 1) Reply might go out in clear which will be dropped at
5262  *    the sending side.
5263  * 2) If the reply goes out in clear it will give the
5264  *    adversary enough information for getting the key in
5265  *    most of the cases.
5266  *
5267  * Moreover getting a secure packet when we expect clear
5268  * implies that SA's were added without checking for
5269  * policy on both ends. This should not happen once ISAKMP
5270  * is used to negotiate SAs as SAs will be added only after
5271  * verifying the policy.
5272  *
5273  * NOTE : If the packet was tunneled and not multicast we only send
5274  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
5275  * back to delivering packets to AF_INET6 raw sockets.
5276  *
5277  * IPQoS Notes:
5278  * Once we have determined the client, invoke IPPF processing.
5279  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
5280  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
5281  * ip_policy will be false.
5282  *
5283  * Zones notes:
5284  * Currently only applications in the global zone can create raw sockets for
5285  * protocols other than ICMP. So unlike the broadcast / multicast case of
5286  * ip_fanout_udp(), we only send a copy of the packet to streams in the
5287  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
5288  */
5289 static void
5290 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
5291     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
5292     zoneid_t zoneid)
5293 {
5294 	queue_t	*rq;
5295 	mblk_t	*mp1, *first_mp1;
5296 	uint_t	protocol = ipha->ipha_protocol;
5297 	ipaddr_t dst;
5298 	boolean_t one_only;
5299 	mblk_t *first_mp = mp;
5300 	boolean_t secure;
5301 	uint32_t ill_index;
5302 	conn_t	*connp, *first_connp, *next_connp;
5303 	connf_t	*connfp;
5304 
5305 	if (mctl_present) {
5306 		mp = first_mp->b_cont;
5307 		secure = ipsec_in_is_secure(first_mp);
5308 		ASSERT(mp != NULL);
5309 	} else {
5310 		secure = B_FALSE;
5311 	}
5312 	dst = ipha->ipha_dst;
5313 	/*
5314 	 * If the packet was tunneled and not multicast we only send to it
5315 	 * the first match.
5316 	 */
5317 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
5318 	    !CLASSD(dst));
5319 
5320 	connfp = &ipcl_proto_fanout[protocol];
5321 	mutex_enter(&connfp->connf_lock);
5322 	connp = connfp->connf_head;
5323 	for (connp = connfp->connf_head; connp != NULL;
5324 		connp = connp->conn_next) {
5325 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags, zoneid))
5326 			break;
5327 	}
5328 
5329 	if (connp == NULL || connp->conn_upq == NULL) {
5330 		/*
5331 		 * No one bound to these addresses.  Is
5332 		 * there a client that wants all
5333 		 * unclaimed datagrams?
5334 		 */
5335 		mutex_exit(&connfp->connf_lock);
5336 		/*
5337 		 * Check for IPPROTO_ENCAP...
5338 		 */
5339 		if (protocol == IPPROTO_ENCAP && ip_g_mrouter) {
5340 			/*
5341 			 * XXX If an IPsec mblk is here on a multicast
5342 			 * tunnel (using ip_mroute stuff), what should
5343 			 * I do?
5344 			 *
5345 			 * For now, just free the IPsec mblk before
5346 			 * passing it up to the multicast routing
5347 			 * stuff.
5348 			 *
5349 			 * BTW,  If I match a configured IP-in-IP
5350 			 * tunnel, ip_mroute_decap will never be
5351 			 * called.
5352 			 */
5353 			if (mp != first_mp)
5354 				freeb(first_mp);
5355 			ip_mroute_decap(q, mp);
5356 		} else {
5357 			/*
5358 			 * Otherwise send an ICMP protocol unreachable.
5359 			 */
5360 			if (ip_fanout_send_icmp(q, first_mp, flags,
5361 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
5362 			    mctl_present, zoneid)) {
5363 				BUMP_MIB(&ip_mib, ipInUnknownProtos);
5364 			}
5365 		}
5366 		return;
5367 	}
5368 	CONN_INC_REF(connp);
5369 	first_connp = connp;
5370 
5371 	/*
5372 	 * Only send message to one tunnel driver by immediately
5373 	 * terminating the loop.
5374 	 */
5375 	connp = one_only ? NULL : connp->conn_next;
5376 
5377 	for (;;) {
5378 		while (connp != NULL) {
5379 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
5380 			    flags, zoneid))
5381 				break;
5382 			connp = connp->conn_next;
5383 		}
5384 
5385 		/*
5386 		 * Copy the packet.
5387 		 */
5388 		if (connp == NULL || connp->conn_upq == NULL ||
5389 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
5390 			((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
5391 			/*
5392 			 * No more interested clients or memory
5393 			 * allocation failed
5394 			 */
5395 			connp = first_connp;
5396 			break;
5397 		}
5398 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
5399 		CONN_INC_REF(connp);
5400 		mutex_exit(&connfp->connf_lock);
5401 		rq = connp->conn_rq;
5402 		if (!canputnext(rq)) {
5403 			if (flags & IP_FF_RAWIP) {
5404 				BUMP_MIB(&ip_mib, rawipInOverflows);
5405 			} else {
5406 				BUMP_MIB(&icmp_mib, icmpInOverflows);
5407 			}
5408 
5409 			freemsg(first_mp1);
5410 		} else {
5411 			if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5412 				first_mp1 = ipsec_check_inbound_policy
5413 				    (first_mp1, connp, ipha, NULL,
5414 				    mctl_present);
5415 			}
5416 			if (first_mp1 != NULL) {
5417 				/*
5418 				 * ip_fanout_proto also gets called from
5419 				 * icmp_inbound_error_fanout, in which case
5420 				 * the msg type is M_CTL.  Don't add info
5421 				 * in this case for the time being. In future
5422 				 * when there is a need for knowing the
5423 				 * inbound iface index for ICMP error msgs,
5424 				 * then this can be changed.
5425 				 */
5426 				if ((connp->conn_recvif != 0) &&
5427 				    (mp->b_datap->db_type != M_CTL)) {
5428 					/*
5429 					 * the actual data will be
5430 					 * contained in b_cont upon
5431 					 * successful return of the
5432 					 * following call else
5433 					 * original mblk is returned
5434 					 */
5435 					ASSERT(recv_ill != NULL);
5436 					mp1 = ip_add_info(mp1, recv_ill,
5437 						IPF_RECVIF);
5438 				}
5439 				BUMP_MIB(&ip_mib, ipInDelivers);
5440 				if (mctl_present)
5441 					freeb(first_mp1);
5442 				putnext(rq, mp1);
5443 			}
5444 		}
5445 		mutex_enter(&connfp->connf_lock);
5446 		/* Follow the next pointer before releasing the conn. */
5447 		next_connp = connp->conn_next;
5448 		CONN_DEC_REF(connp);
5449 		connp = next_connp;
5450 	}
5451 
5452 	/* Last one.  Send it upstream. */
5453 	mutex_exit(&connfp->connf_lock);
5454 
5455 	/*
5456 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
5457 	 * will be set to false.
5458 	 */
5459 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
5460 		ill_index = ill->ill_phyint->phyint_ifindex;
5461 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
5462 		if (mp == NULL) {
5463 			CONN_DEC_REF(connp);
5464 			if (mctl_present) {
5465 				freeb(first_mp);
5466 			}
5467 			return;
5468 		}
5469 	}
5470 
5471 	rq = connp->conn_rq;
5472 	if (!canputnext(rq)) {
5473 		if (flags & IP_FF_RAWIP) {
5474 			BUMP_MIB(&ip_mib, rawipInOverflows);
5475 		} else {
5476 			BUMP_MIB(&icmp_mib, icmpInOverflows);
5477 		}
5478 
5479 		freemsg(first_mp);
5480 	} else {
5481 		if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5482 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
5483 			    ipha, NULL, mctl_present);
5484 		}
5485 		if (first_mp != NULL) {
5486 			/*
5487 			 * ip_fanout_proto also gets called
5488 			 * from icmp_inbound_error_fanout, in
5489 			 * which case the msg type is M_CTL.
5490 			 * Don't add info in this case for time
5491 			 * being. In future when there is a
5492 			 * need for knowing the inbound iface
5493 			 * index for ICMP error msgs, then this
5494 			 * can be changed
5495 			 */
5496 			if ((connp->conn_recvif != 0) &&
5497 			    (mp->b_datap->db_type != M_CTL)) {
5498 				/*
5499 				 * the actual data will be contained in
5500 				 * b_cont upon successful return
5501 				 * of the following call else original
5502 				 * mblk is returned
5503 				 */
5504 				ASSERT(recv_ill != NULL);
5505 				mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
5506 			}
5507 			BUMP_MIB(&ip_mib, ipInDelivers);
5508 			putnext(rq, mp);
5509 			if (mctl_present)
5510 				freeb(first_mp);
5511 		}
5512 	}
5513 	CONN_DEC_REF(connp);
5514 }
5515 
5516 /*
5517  * Fanout for TCP packets
5518  * The caller puts <fport, lport> in the ports parameter.
5519  *
5520  * IPQoS Notes
5521  * Before sending it to the client, invoke IPPF processing.
5522  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
5523  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
5524  * ip_policy is false.
5525  */
5526 static void
5527 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
5528     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
5529 {
5530 	mblk_t  *first_mp;
5531 	boolean_t secure;
5532 	uint32_t ill_index;
5533 	int	ip_hdr_len;
5534 	tcph_t	*tcph;
5535 	boolean_t syn_present = B_FALSE;
5536 	conn_t	*connp;
5537 
5538 	first_mp = mp;
5539 	if (mctl_present) {
5540 		ASSERT(first_mp->b_datap->db_type == M_CTL);
5541 		mp = first_mp->b_cont;
5542 		secure = ipsec_in_is_secure(first_mp);
5543 		ASSERT(mp != NULL);
5544 	} else {
5545 		secure = B_FALSE;
5546 	}
5547 
5548 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
5549 
5550 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
5551 	    NULL) {
5552 		/*
5553 		 * No connected connection or listener. Send a
5554 		 * TH_RST via tcp_xmit_listeners_reset.
5555 		 */
5556 
5557 		/* Initiate IPPf processing, if needed. */
5558 		if (IPP_ENABLED(IPP_LOCAL_IN)) {
5559 			uint32_t ill_index;
5560 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
5561 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
5562 			if (first_mp == NULL)
5563 				return;
5564 		}
5565 		BUMP_MIB(&ip_mib, ipInDelivers);
5566 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
5567 		return;
5568 	}
5569 
5570 	/*
5571 	 * Allocate the SYN for the TCP connection here itself
5572 	 */
5573 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5574 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
5575 		if (IPCL_IS_TCP(connp)) {
5576 			squeue_t *sqp;
5577 
5578 			/*
5579 			 * For fused tcp loopback, assign the eager's
5580 			 * squeue to be that of the active connect's.
5581 			 * Note that we don't check for IP_FF_LOOPBACK
5582 			 * here since this routine gets called only
5583 			 * for loopback (unlike the IPv6 counterpart).
5584 			 */
5585 			if (do_tcp_fusion &&
5586 			    !CONN_INBOUND_POLICY_PRESENT(connp) && !secure &&
5587 			    !IPP_ENABLED(IPP_LOCAL_IN) && !ip_policy) {
5588 				ASSERT(Q_TO_CONN(q) != NULL);
5589 				sqp = Q_TO_CONN(q)->conn_sqp;
5590 			} else {
5591 				sqp = IP_SQUEUE_GET(lbolt);
5592 			}
5593 
5594 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
5595 			mp->b_datap->db_cksumstart = (intptr_t)sqp;
5596 			syn_present = B_TRUE;
5597 		}
5598 	}
5599 
5600 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
5601 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
5602 		if ((flags & TH_RST) || (flags & TH_URG)) {
5603 			CONN_DEC_REF(connp);
5604 			freemsg(first_mp);
5605 			return;
5606 		}
5607 		if (flags & TH_ACK) {
5608 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
5609 			CONN_DEC_REF(connp);
5610 			return;
5611 		}
5612 
5613 		CONN_DEC_REF(connp);
5614 		freemsg(first_mp);
5615 		return;
5616 	}
5617 
5618 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5619 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
5620 		    NULL, mctl_present);
5621 		if (first_mp == NULL) {
5622 			CONN_DEC_REF(connp);
5623 			return;
5624 		}
5625 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
5626 			ASSERT(syn_present);
5627 			if (mctl_present) {
5628 				ASSERT(first_mp != mp);
5629 				first_mp->b_datap->db_struioflag |=
5630 				    STRUIO_POLICY;
5631 			} else {
5632 				ASSERT(first_mp == mp);
5633 				mp->b_datap->db_struioflag &=
5634 				    ~STRUIO_EAGER;
5635 				mp->b_datap->db_struioflag |=
5636 				    STRUIO_POLICY;
5637 			}
5638 		} else {
5639 			/*
5640 			 * Discard first_mp early since we're dealing with a
5641 			 * fully-connected conn_t and tcp doesn't do policy in
5642 			 * this case.
5643 			 */
5644 			if (mctl_present) {
5645 				freeb(first_mp);
5646 				mctl_present = B_FALSE;
5647 			}
5648 			first_mp = mp;
5649 		}
5650 	}
5651 
5652 	/*
5653 	 * Initiate policy processing here if needed. If we get here from
5654 	 * icmp_inbound_error_fanout, ip_policy is false.
5655 	 */
5656 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
5657 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
5658 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
5659 		if (mp == NULL) {
5660 			CONN_DEC_REF(connp);
5661 			if (mctl_present)
5662 				freeb(first_mp);
5663 			return;
5664 		} else if (mctl_present) {
5665 			ASSERT(first_mp != mp);
5666 			first_mp->b_cont = mp;
5667 		} else {
5668 			first_mp = mp;
5669 		}
5670 	}
5671 
5672 
5673 
5674 	/* Handle IPv6 socket options. */
5675 	if (!syn_present &&
5676 	    connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO)) {
5677 		/* Add header */
5678 		ASSERT(recv_ill != NULL);
5679 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
5680 		if (mp == NULL) {
5681 			CONN_DEC_REF(connp);
5682 			if (mctl_present)
5683 				freeb(first_mp);
5684 			return;
5685 		} else if (mctl_present) {
5686 			/*
5687 			 * ip_add_info might return a new mp.
5688 			 */
5689 			ASSERT(first_mp != mp);
5690 			first_mp->b_cont = mp;
5691 		} else {
5692 			first_mp = mp;
5693 		}
5694 	}
5695 
5696 	BUMP_MIB(&ip_mib, ipInDelivers);
5697 	if (IPCL_IS_TCP(connp)) {
5698 		(*ip_input_proc)(connp->conn_sqp, first_mp,
5699 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
5700 	} else {
5701 		putnext(connp->conn_rq, first_mp);
5702 		CONN_DEC_REF(connp);
5703 	}
5704 }
5705 
5706 /*
5707  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
5708  * We are responsible for disposing of mp, such as by freemsg() or putnext()
5709  * Caller is responsible for dropping references to the conn, and freeing
5710  * first_mp.
5711  *
5712  * IPQoS Notes
5713  * Before sending it to the client, invoke IPPF processing. Policy processing
5714  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
5715  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
5716  * ip_wput_local, ip_policy is false.
5717  */
5718 static void
5719 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
5720     boolean_t secure, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
5721     boolean_t ip_policy)
5722 {
5723 	queue_t		*rq = connp->conn_rq;
5724 	boolean_t	mctl_present = (first_mp != NULL);
5725 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
5726 	uint32_t	ill_index;
5727 
5728 	if (mctl_present)
5729 		first_mp->b_cont = mp;
5730 	else
5731 		first_mp = mp;
5732 
5733 	if (!canputnext(rq)) {
5734 		BUMP_MIB(&ip_mib, udpInOverflows);
5735 		freemsg(first_mp);
5736 		return;
5737 	}
5738 
5739 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5740 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
5741 		    NULL, mctl_present);
5742 		if (first_mp == NULL)
5743 			return;	/* Freed by ipsec_check_inbound_policy(). */
5744 	}
5745 	if (mctl_present)
5746 		freeb(first_mp);
5747 
5748 	if (connp->conn_recvif)
5749 		in_flags = IPF_RECVIF;
5750 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
5751 		in_flags |= IPF_RECVSLLA;
5752 
5753 	/* Handle IPv6 options. */
5754 	if (connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO))
5755 		in_flags |= IPF_RECVIF;
5756 
5757 	/*
5758 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
5759 	 * freed if the packet is dropped. The caller will do so.
5760 	 */
5761 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
5762 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
5763 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
5764 		if (mp == NULL) {
5765 			return;
5766 		}
5767 	}
5768 	if ((in_flags != 0) &&
5769 	    (mp->b_datap->db_type != M_CTL)) {
5770 		/*
5771 		 * The actual data will be contained in b_cont
5772 		 * upon successful return of the following call
5773 		 * else original mblk is returned
5774 		 */
5775 		ASSERT(recv_ill != NULL);
5776 		mp = ip_add_info(mp, recv_ill, in_flags);
5777 	}
5778 	BUMP_MIB(&ip_mib, ipInDelivers);
5779 	putnext(rq, mp);
5780 }
5781 
5782 /*
5783  * Fanout for UDP packets.
5784  * The caller puts <fport, lport> in the ports parameter.
5785  *
5786  * If SO_REUSEADDR is set all multicast and broadcast packets
5787  * will be delivered to all streams bound to the same port.
5788  *
5789  * Zones notes:
5790  * Multicast and broadcast packets will be distributed to streams in all zones.
5791  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
5792  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
5793  * packets. To maintain this behavior with multiple zones, the conns are grouped
5794  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
5795  * each zone. If unset, all the following conns in the same zone are skipped.
5796  */
5797 static void
5798 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
5799     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
5800     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
5801 {
5802 	uint32_t	dstport, srcport;
5803 	ipaddr_t	dst;
5804 	mblk_t		*first_mp;
5805 	boolean_t	secure;
5806 	in6_addr_t	v6src;
5807 	conn_t		*connp;
5808 	connf_t		*connfp;
5809 	conn_t		*first_connp;
5810 	conn_t		*next_connp;
5811 	mblk_t		*mp1, *first_mp1;
5812 	ipaddr_t	src;
5813 	zoneid_t	last_zoneid;
5814 	boolean_t	reuseaddr;
5815 
5816 	first_mp = mp;
5817 	if (mctl_present) {
5818 		mp = first_mp->b_cont;
5819 		first_mp->b_cont = NULL;
5820 		secure = ipsec_in_is_secure(first_mp);
5821 		ASSERT(mp != NULL);
5822 	} else {
5823 		first_mp = NULL;
5824 		secure = B_FALSE;
5825 	}
5826 
5827 	/* Extract ports in net byte order */
5828 	dstport = htons(ntohl(ports) & 0xFFFF);
5829 	srcport = htons(ntohl(ports) >> 16);
5830 	dst = ipha->ipha_dst;
5831 	src = ipha->ipha_src;
5832 
5833 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
5834 	mutex_enter(&connfp->connf_lock);
5835 	connp = connfp->connf_head;
5836 	if (!broadcast && !CLASSD(dst)) {
5837 		/*
5838 		 * Not broadcast or multicast. Send to the one (first)
5839 		 * client we find. No need to check conn_wantpacket()
5840 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
5841 		 * IPv4 unicast packets.
5842 		 */
5843 		while ((connp != NULL) &&
5844 		    (!IPCL_UDP_MATCH(connp, dstport, dst,
5845 		    srcport, src) || connp->conn_zoneid != zoneid)) {
5846 			connp = connp->conn_next;
5847 		}
5848 
5849 		if (connp == NULL || connp->conn_upq == NULL)
5850 			goto notfound;
5851 		CONN_INC_REF(connp);
5852 		mutex_exit(&connfp->connf_lock);
5853 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
5854 		    recv_ill, ip_policy);
5855 		IP_STAT(ip_udp_fannorm);
5856 		CONN_DEC_REF(connp);
5857 		return;
5858 	}
5859 
5860 	/*
5861 	 * Broadcast and multicast case
5862 	 *
5863 	 * Need to check conn_wantpacket().
5864 	 * If SO_REUSEADDR has been set on the first we send the
5865 	 * packet to all clients that have joined the group and
5866 	 * match the port.
5867 	 */
5868 
5869 	while (connp != NULL) {
5870 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
5871 		    conn_wantpacket(connp, ill, ipha, flags, zoneid))
5872 			break;
5873 		connp = connp->conn_next;
5874 	}
5875 
5876 	if (connp == NULL || connp->conn_upq == NULL)
5877 		goto notfound;
5878 
5879 	first_connp = connp;
5880 	/*
5881 	 * When SO_REUSEADDR is not set, send the packet only to the first
5882 	 * matching connection in its zone by keeping track of the zoneid.
5883 	 */
5884 	reuseaddr = first_connp->conn_reuseaddr;
5885 	last_zoneid = first_connp->conn_zoneid;
5886 
5887 	CONN_INC_REF(connp);
5888 	connp = connp->conn_next;
5889 	for (;;) {
5890 		while (connp != NULL) {
5891 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
5892 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
5893 			    conn_wantpacket(connp, ill, ipha, flags, zoneid))
5894 				break;
5895 			connp = connp->conn_next;
5896 		}
5897 		/*
5898 		 * Just copy the data part alone. The mctl part is
5899 		 * needed just for verifying policy and it is never
5900 		 * sent up.
5901 		 */
5902 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
5903 		    ((mp1 = copymsg(mp)) == NULL))) {
5904 			/*
5905 			 * No more interested clients or memory
5906 			 * allocation failed
5907 			 */
5908 			connp = first_connp;
5909 			break;
5910 		}
5911 		if (connp->conn_zoneid != last_zoneid) {
5912 			/*
5913 			 * Update the zoneid so that the packet isn't sent to
5914 			 * any more conns in the same zone unless SO_REUSEADDR
5915 			 * is set.
5916 			 */
5917 			reuseaddr = connp->conn_reuseaddr;
5918 			last_zoneid = connp->conn_zoneid;
5919 		}
5920 		if (first_mp != NULL) {
5921 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
5922 			    ipsec_info_type == IPSEC_IN);
5923 			first_mp1 = ipsec_in_tag(first_mp, NULL);
5924 			if (first_mp1 == NULL) {
5925 				freemsg(mp1);
5926 				connp = first_connp;
5927 				break;
5928 			}
5929 		} else {
5930 			first_mp1 = NULL;
5931 		}
5932 		CONN_INC_REF(connp);
5933 		mutex_exit(&connfp->connf_lock);
5934 		/*
5935 		 * IPQoS notes: We don't send the packet for policy
5936 		 * processing here, will do it for the last one (below).
5937 		 * i.e. we do it per-packet now, but if we do policy
5938 		 * processing per-conn, then we would need to do it
5939 		 * here too.
5940 		 */
5941 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
5942 		    ipha, flags, recv_ill, B_FALSE);
5943 		mutex_enter(&connfp->connf_lock);
5944 		/* Follow the next pointer before releasing the conn. */
5945 		next_connp = connp->conn_next;
5946 		IP_STAT(ip_udp_fanmb);
5947 		CONN_DEC_REF(connp);
5948 		connp = next_connp;
5949 	}
5950 
5951 	/* Last one.  Send it upstream. */
5952 	mutex_exit(&connfp->connf_lock);
5953 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
5954 	    ip_policy);
5955 	IP_STAT(ip_udp_fanmb);
5956 	CONN_DEC_REF(connp);
5957 	return;
5958 
5959 notfound:
5960 
5961 	mutex_exit(&connfp->connf_lock);
5962 	IP_STAT(ip_udp_fanothers);
5963 	/*
5964 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
5965 	 * have already been matched above, since they live in the IPv4
5966 	 * fanout tables. This implies we only need to
5967 	 * check for IPv6 in6addr_any endpoints here.
5968 	 * Thus we compare using ipv6_all_zeros instead of the destination
5969 	 * address, except for the multicast group membership lookup which
5970 	 * uses the IPv4 destination.
5971 	 */
5972 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
5973 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
5974 	mutex_enter(&connfp->connf_lock);
5975 	connp = connfp->connf_head;
5976 	if (!broadcast && !CLASSD(dst)) {
5977 		while (connp != NULL) {
5978 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
5979 			    srcport, v6src) && connp->conn_zoneid == zoneid &&
5980 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
5981 			    !connp->conn_ipv6_v6only)
5982 				break;
5983 			connp = connp->conn_next;
5984 		}
5985 
5986 		if (connp == NULL || connp->conn_upq == NULL) {
5987 			/*
5988 			 * No one bound to this port.  Is
5989 			 * there a client that wants all
5990 			 * unclaimed datagrams?
5991 			 */
5992 			mutex_exit(&connfp->connf_lock);
5993 
5994 			if (mctl_present)
5995 				first_mp->b_cont = mp;
5996 			else
5997 				first_mp = mp;
5998 			if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
5999 				ip_fanout_proto(q, first_mp, ill, ipha,
6000 				    flags | IP_FF_RAWIP, mctl_present,
6001 				    ip_policy, recv_ill, zoneid);
6002 			} else {
6003 				if (ip_fanout_send_icmp(q, first_mp, flags,
6004 				    ICMP_DEST_UNREACHABLE,
6005 				    ICMP_PORT_UNREACHABLE,
6006 				    mctl_present, zoneid)) {
6007 					BUMP_MIB(&ip_mib, udpNoPorts);
6008 				}
6009 			}
6010 			return;
6011 		}
6012 		CONN_INC_REF(connp);
6013 		mutex_exit(&connfp->connf_lock);
6014 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6015 		    recv_ill, ip_policy);
6016 		CONN_DEC_REF(connp);
6017 		return;
6018 	}
6019 	/*
6020 	 * IPv4 multicast packet being delivered to an AF_INET6
6021 	 * in6addr_any endpoint.
6022 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
6023 	 * and not conn_wantpacket_v6() since any multicast membership is
6024 	 * for an IPv4-mapped multicast address.
6025 	 * The packet is sent to all clients in all zones that have joined the
6026 	 * group and match the port.
6027 	 */
6028 	while (connp != NULL) {
6029 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6030 		    srcport, v6src) &&
6031 		    conn_wantpacket(connp, ill, ipha, flags, zoneid))
6032 			break;
6033 		connp = connp->conn_next;
6034 	}
6035 
6036 	if (connp == NULL || connp->conn_upq == NULL) {
6037 		/*
6038 		 * No one bound to this port.  Is
6039 		 * there a client that wants all
6040 		 * unclaimed datagrams?
6041 		 */
6042 		mutex_exit(&connfp->connf_lock);
6043 
6044 		if (mctl_present)
6045 			first_mp->b_cont = mp;
6046 		else
6047 			first_mp = mp;
6048 		if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6049 			ip_fanout_proto(q, first_mp, ill, ipha,
6050 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
6051 			    recv_ill, zoneid);
6052 		} else {
6053 			/*
6054 			 * We used to attempt to send an icmp error here, but
6055 			 * since this is known to be a multicast packet
6056 			 * and we don't send icmp errors in response to
6057 			 * multicast, just drop the packet and give up sooner.
6058 			 */
6059 			BUMP_MIB(&ip_mib, udpNoPorts);
6060 			freemsg(first_mp);
6061 		}
6062 		return;
6063 	}
6064 
6065 	first_connp = connp;
6066 
6067 	CONN_INC_REF(connp);
6068 	connp = connp->conn_next;
6069 	for (;;) {
6070 		while (connp != NULL) {
6071 			if (IPCL_UDP_MATCH_V6(connp, dstport,
6072 			    ipv6_all_zeros, srcport, v6src) &&
6073 			    conn_wantpacket(connp, ill, ipha, flags, zoneid))
6074 				break;
6075 			connp = connp->conn_next;
6076 		}
6077 		/*
6078 		 * Just copy the data part alone. The mctl part is
6079 		 * needed just for verifying policy and it is never
6080 		 * sent up.
6081 		 */
6082 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6083 		    ((mp1 = copymsg(mp)) == NULL))) {
6084 			/*
6085 			 * No more intested clients or memory
6086 			 * allocation failed
6087 			 */
6088 			connp = first_connp;
6089 			break;
6090 		}
6091 		if (first_mp != NULL) {
6092 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6093 			    ipsec_info_type == IPSEC_IN);
6094 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6095 			if (first_mp1 == NULL) {
6096 				freemsg(mp1);
6097 				connp = first_connp;
6098 				break;
6099 			}
6100 		} else {
6101 			first_mp1 = NULL;
6102 		}
6103 		CONN_INC_REF(connp);
6104 		mutex_exit(&connfp->connf_lock);
6105 		/*
6106 		 * IPQoS notes: We don't send the packet for policy
6107 		 * processing here, will do it for the last one (below).
6108 		 * i.e. we do it per-packet now, but if we do policy
6109 		 * processing per-conn, then we would need to do it
6110 		 * here too.
6111 		 */
6112 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6113 		    ipha, flags, recv_ill, B_FALSE);
6114 		mutex_enter(&connfp->connf_lock);
6115 		/* Follow the next pointer before releasing the conn. */
6116 		next_connp = connp->conn_next;
6117 		CONN_DEC_REF(connp);
6118 		connp = next_connp;
6119 	}
6120 
6121 	/* Last one.  Send it upstream. */
6122 	mutex_exit(&connfp->connf_lock);
6123 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6124 	    ip_policy);
6125 	CONN_DEC_REF(connp);
6126 }
6127 
6128 /*
6129  * Complete the ip_wput header so that it
6130  * is possible to generate ICMP
6131  * errors.
6132  */
6133 static int
6134 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid)
6135 {
6136 	ire_t *ire;
6137 
6138 	if (ipha->ipha_src == INADDR_ANY) {
6139 		ire = ire_lookup_local(zoneid);
6140 		if (ire == NULL) {
6141 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
6142 			return (1);
6143 		}
6144 		ipha->ipha_src = ire->ire_addr;
6145 		ire_refrele(ire);
6146 	}
6147 	ipha->ipha_ttl = ip_def_ttl;
6148 	ipha->ipha_hdr_checksum = 0;
6149 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6150 	return (0);
6151 }
6152 
6153 /*
6154  * Nobody should be sending
6155  * packets up this stream
6156  */
6157 static void
6158 ip_lrput(queue_t *q, mblk_t *mp)
6159 {
6160 	mblk_t *mp1;
6161 
6162 	switch (mp->b_datap->db_type) {
6163 	case M_FLUSH:
6164 		/* Turn around */
6165 		if (*mp->b_rptr & FLUSHW) {
6166 			*mp->b_rptr &= ~FLUSHR;
6167 			qreply(q, mp);
6168 			return;
6169 		}
6170 		break;
6171 	}
6172 	/* Could receive messages that passed through ar_rput */
6173 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
6174 		mp1->b_prev = mp1->b_next = NULL;
6175 	freemsg(mp);
6176 }
6177 
6178 /* Nobody should be sending packets down this stream */
6179 /* ARGSUSED */
6180 void
6181 ip_lwput(queue_t *q, mblk_t *mp)
6182 {
6183 	freemsg(mp);
6184 }
6185 
6186 /*
6187  * Move the first hop in any source route to ipha_dst and remove that part of
6188  * the source route.  Called by other protocols.  Errors in option formatting
6189  * are ignored - will be handled by ip_wput_options Return the final
6190  * destination (either ipha_dst or the last entry in a source route.)
6191  */
6192 ipaddr_t
6193 ip_massage_options(ipha_t *ipha)
6194 {
6195 	ipoptp_t	opts;
6196 	uchar_t		*opt;
6197 	uint8_t		optval;
6198 	uint8_t		optlen;
6199 	ipaddr_t	dst;
6200 	int		i;
6201 	ire_t		*ire;
6202 
6203 	ip2dbg(("ip_massage_options\n"));
6204 	dst = ipha->ipha_dst;
6205 	for (optval = ipoptp_first(&opts, ipha);
6206 	    optval != IPOPT_EOL;
6207 	    optval = ipoptp_next(&opts)) {
6208 		opt = opts.ipoptp_cur;
6209 		switch (optval) {
6210 			uint8_t off;
6211 		case IPOPT_SSRR:
6212 		case IPOPT_LSRR:
6213 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
6214 				ip1dbg(("ip_massage_options: bad src route\n"));
6215 				break;
6216 			}
6217 			optlen = opts.ipoptp_len;
6218 			off = opt[IPOPT_OFFSET];
6219 			off--;
6220 		redo_srr:
6221 			if (optlen < IP_ADDR_LEN ||
6222 			    off > optlen - IP_ADDR_LEN) {
6223 				/* End of source route */
6224 				ip1dbg(("ip_massage_options: end of SR\n"));
6225 				break;
6226 			}
6227 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
6228 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
6229 			    ntohl(dst)));
6230 			/*
6231 			 * Check if our address is present more than
6232 			 * once as consecutive hops in source route.
6233 			 * XXX verify per-interface ip_forwarding
6234 			 * for source route?
6235 			 */
6236 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
6237 			    ALL_ZONES, MATCH_IRE_TYPE);
6238 			if (ire != NULL) {
6239 				ire_refrele(ire);
6240 				off += IP_ADDR_LEN;
6241 				goto redo_srr;
6242 			}
6243 			if (dst == htonl(INADDR_LOOPBACK)) {
6244 				ip1dbg(("ip_massage_options: loopback addr in "
6245 				    "source route!\n"));
6246 				break;
6247 			}
6248 			/*
6249 			 * Update ipha_dst to be the first hop and remove the
6250 			 * first hop from the source route (by overwriting
6251 			 * part of the option with NOP options).
6252 			 */
6253 			ipha->ipha_dst = dst;
6254 			/* Put the last entry in dst */
6255 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
6256 			    3;
6257 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
6258 
6259 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
6260 			    ntohl(dst)));
6261 			/* Move down and overwrite */
6262 			opt[IP_ADDR_LEN] = opt[0];
6263 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
6264 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
6265 			for (i = 0; i < IP_ADDR_LEN; i++)
6266 				opt[i] = IPOPT_NOP;
6267 			break;
6268 		}
6269 	}
6270 	return (dst);
6271 }
6272 
6273 /*
6274  * This function's job is to forward data to the reverse tunnel (FA->HA)
6275  * after doing a few checks. It is assumed that the incoming interface
6276  * of the packet is always different than the outgoing interface and the
6277  * ire_type of the found ire has to be a non-resolver type.
6278  *
6279  * IPQoS notes
6280  * IP policy is invoked twice for a forwarded packet, once on the read side
6281  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
6282  * enabled.
6283  */
6284 static void
6285 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
6286 {
6287 	ipha_t		*ipha;
6288 	queue_t		*q;
6289 	uint32_t 	pkt_len;
6290 #define	rptr    ((uchar_t *)ipha)
6291 	uint32_t 	sum;
6292 	uint32_t 	max_frag;
6293 	mblk_t		*first_mp;
6294 	uint32_t	ill_index;
6295 
6296 	ASSERT(ire != NULL);
6297 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
6298 	ASSERT(ire->ire_stq != NULL);
6299 
6300 	/* Initiate read side IPPF processing */
6301 	if (IPP_ENABLED(IPP_FWD_IN)) {
6302 		ill_index = in_ill->ill_phyint->phyint_ifindex;
6303 		ip_process(IPP_FWD_IN, &mp, ill_index);
6304 		if (mp == NULL) {
6305 			ip2dbg(("ip_mrtun_forward: inbound pkt "
6306 			    "dropped during IPPF processing\n"));
6307 			return;
6308 		}
6309 	}
6310 
6311 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
6312 		ILLF_ROUTER) == 0) ||
6313 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
6314 		BUMP_MIB(&ip_mib, ipForwProhibits);
6315 		ip0dbg(("ip_mrtun_forward: Can't forward :"
6316 		    "forwarding is not turned on\n"));
6317 		goto drop_pkt;
6318 	}
6319 
6320 	/*
6321 	 * Don't forward if the interface is down
6322 	 */
6323 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
6324 		BUMP_MIB(&ip_mib, ipInDiscards);
6325 		goto drop_pkt;
6326 	}
6327 
6328 	ipha = (ipha_t *)mp->b_rptr;
6329 	pkt_len = ntohs(ipha->ipha_length);
6330 	/* Adjust the checksum to reflect the ttl decrement. */
6331 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
6332 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
6333 	if (ipha->ipha_ttl-- <= 1) {
6334 		if (ip_csum_hdr(ipha)) {
6335 			BUMP_MIB(&ip_mib, ipInCksumErrs);
6336 			goto drop_pkt;
6337 		}
6338 		q = ire->ire_stq;
6339 		if ((first_mp = allocb(sizeof (ipsec_info_t),
6340 		    BPRI_HI)) == NULL) {
6341 			goto drop_pkt;
6342 		}
6343 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
6344 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED);
6345 
6346 		return;
6347 	}
6348 
6349 	/* Get the ill_index of the ILL */
6350 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
6351 
6352 	/*
6353 	 * ip_mrtun_forward is only used by foreign agent to reverse
6354 	 * tunnel the incoming packet. So it does not do any option
6355 	 * processing for source routing.
6356 	 */
6357 	max_frag = ire->ire_max_frag;
6358 	if (pkt_len > max_frag) {
6359 		/*
6360 		 * It needs fragging on its way out.  We haven't
6361 		 * verified the header checksum yet.  Since we
6362 		 * are going to put a surely good checksum in the
6363 		 * outgoing header, we have to make sure that it
6364 		 * was good coming in.
6365 		 */
6366 		if (ip_csum_hdr(ipha)) {
6367 			BUMP_MIB(&ip_mib, ipInCksumErrs);
6368 			goto drop_pkt;
6369 		}
6370 
6371 		/* Initiate write side IPPF processing */
6372 		if (IPP_ENABLED(IPP_FWD_OUT)) {
6373 			ip_process(IPP_FWD_OUT, &mp, ill_index);
6374 			if (mp == NULL) {
6375 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
6376 				    "dropped/deferred during ip policy "\
6377 				    "processing\n"));
6378 				return;
6379 			}
6380 		}
6381 		if ((first_mp = allocb(sizeof (ipsec_info_t),
6382 		    BPRI_HI)) == NULL) {
6383 			goto drop_pkt;
6384 		}
6385 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
6386 		mp = first_mp;
6387 
6388 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0);
6389 		return;
6390 	}
6391 
6392 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
6393 
6394 	ASSERT(ire->ire_ipif != NULL);
6395 
6396 	mp = ip_wput_attach_llhdr(mp, ire, IPP_FWD_OUT, ill_index);
6397 	if (mp == NULL) {
6398 		BUMP_MIB(&ip_mib, ipInDiscards);
6399 		return;
6400 	}
6401 
6402 	/* Now send the packet to the tunnel interface */
6403 	q = ire->ire_stq;
6404 	UPDATE_IB_PKT_COUNT(ire);
6405 	ire->ire_last_used_time = lbolt;
6406 	BUMP_MIB(&ip_mib, ipForwDatagrams);
6407 	putnext(q, mp);
6408 	ip2dbg(("ip_mrtun_forward: sent packet to ill %p\n", q->q_ptr));
6409 	return;
6410 
6411 drop_pkt:;
6412 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
6413 	freemsg(mp);
6414 #undef	rptr
6415 }
6416 
6417 /*
6418  * Fills the ipsec_out_t data structure with appropriate fields and
6419  * prepends it to mp which contains the IP hdr + data that was meant
6420  * to be forwarded. Please note that ipsec_out_info data structure
6421  * is used here to communicate the outgoing ill path at ip_wput()
6422  * for the ICMP error packet. This has nothing to do with ipsec IP
6423  * security. ipsec_out_t is really used to pass the info to the module
6424  * IP where this information cannot be extracted from conn.
6425  * This functions is called by ip_mrtun_forward().
6426  */
6427 void
6428 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
6429 {
6430 	ipsec_out_t	*io;
6431 
6432 	ASSERT(xmit_ill != NULL);
6433 	first_mp->b_datap->db_type = M_CTL;
6434 	first_mp->b_wptr += sizeof (ipsec_info_t);
6435 	/*
6436 	 * This is to pass info to ip_wput in absence of conn.
6437 	 * ipsec_out_secure will be B_FALSE because of this.
6438 	 * Thus ipsec_out_secure being B_FALSE indicates that
6439 	 * this is not IPSEC security related information.
6440 	 */
6441 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
6442 	io = (ipsec_out_t *)first_mp->b_rptr;
6443 	io->ipsec_out_type = IPSEC_OUT;
6444 	io->ipsec_out_len = sizeof (ipsec_out_t);
6445 	first_mp->b_cont = mp;
6446 	io->ipsec_out_ill_index =
6447 	    xmit_ill->ill_phyint->phyint_ifindex;
6448 	io->ipsec_out_xmit_if = B_TRUE;
6449 }
6450 
6451 /*
6452  * Return the network mask
6453  * associated with the specified address.
6454  */
6455 ipaddr_t
6456 ip_net_mask(ipaddr_t addr)
6457 {
6458 	uchar_t	*up = (uchar_t *)&addr;
6459 	ipaddr_t mask = 0;
6460 	uchar_t	*maskp = (uchar_t *)&mask;
6461 
6462 #if defined(__i386) || defined(__amd64)
6463 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
6464 #endif
6465 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
6466 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
6467 #endif
6468 	if (CLASSD(addr)) {
6469 		maskp[0] = 0xF0;
6470 		return (mask);
6471 	}
6472 	if (addr == 0)
6473 		return (0);
6474 	maskp[0] = 0xFF;
6475 	if ((up[0] & 0x80) == 0)
6476 		return (mask);
6477 
6478 	maskp[1] = 0xFF;
6479 	if ((up[0] & 0xC0) == 0x80)
6480 		return (mask);
6481 
6482 	maskp[2] = 0xFF;
6483 	if ((up[0] & 0xE0) == 0xC0)
6484 		return (mask);
6485 
6486 	/* Must be experimental or multicast, indicate as much */
6487 	return ((ipaddr_t)0);
6488 }
6489 
6490 /*
6491  * Select an ill for the packet by considering load spreading across
6492  * a different ill in the group if dst_ill is part of some group.
6493  */
6494 static ill_t *
6495 ip_newroute_get_dst_ill(ill_t *dst_ill)
6496 {
6497 	ill_t *ill;
6498 
6499 	/*
6500 	 * We schedule irrespective of whether the source address is
6501 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
6502 	 */
6503 	ill = illgrp_scheduler(dst_ill);
6504 	if (ill == NULL)
6505 		return (NULL);
6506 
6507 	/*
6508 	 * For groups with names ip_sioctl_groupname ensures that all
6509 	 * ills are of same type. For groups without names, ifgrp_insert
6510 	 * ensures this.
6511 	 */
6512 	ASSERT(dst_ill->ill_type == ill->ill_type);
6513 
6514 	return (ill);
6515 }
6516 
6517 /*
6518  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
6519  */
6520 ill_t *
6521 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6)
6522 {
6523 	ill_t *ret_ill;
6524 
6525 	ASSERT(ifindex != 0);
6526 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL);
6527 	if (ret_ill == NULL ||
6528 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
6529 		if (isv6) {
6530 			if (ill != NULL) {
6531 				BUMP_MIB(ill->ill_ip6_mib, ipv6OutDiscards);
6532 			} else {
6533 				BUMP_MIB(&ip6_mib, ipv6OutDiscards);
6534 			}
6535 			ip1dbg(("ip_grab_attach_ill (IPv6): "
6536 			    "bad ifindex %d.\n", ifindex));
6537 		} else {
6538 			BUMP_MIB(&ip_mib, ipOutDiscards);
6539 			ip1dbg(("ip_grab_attach_ill (IPv4): "
6540 			    "bad ifindex %d.\n", ifindex));
6541 		}
6542 		if (ret_ill != NULL)
6543 			ill_refrele(ret_ill);
6544 		freemsg(first_mp);
6545 		return (NULL);
6546 	}
6547 
6548 	return (ret_ill);
6549 }
6550 
6551 /*
6552  * IPv4 -
6553  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
6554  * out a packet to a destination address for which we do not have specific
6555  * (or sufficient) routing information.
6556  *
6557  * NOTE : These are the scopes of some of the variables that point at IRE,
6558  *	  which needs to be followed while making any future modifications
6559  *	  to avoid memory leaks.
6560  *
6561  *	- ire and sire are the entries looked up initially by
6562  *	  ire_ftable_lookup.
6563  *	- ipif_ire is used to hold the interface ire associated with
6564  *	  the new cache ire. But it's scope is limited, so we always REFRELE
6565  *	  it before branching out to error paths.
6566  *	- save_ire is initialized before ire_create, so that ire returned
6567  *	  by ire_create will not over-write the ire. We REFRELE save_ire
6568  *	  before breaking out of the switch.
6569  *
6570  *	Thus on failures, we have to REFRELE only ire and sire, if they
6571  *	are not NULL.
6572  */
6573 void
6574 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp)
6575 {
6576 	areq_t	*areq;
6577 	ipaddr_t gw = 0;
6578 	ire_t	*ire = NULL;
6579 	mblk_t	*res_mp;
6580 	ipaddr_t *addrp;
6581 	ipif_t  *src_ipif = NULL;
6582 	ill_t	*dst_ill = NULL;
6583 	ipha_t  *ipha;
6584 	ire_t	*sire = NULL;
6585 	mblk_t	*first_mp;
6586 	ire_t	*save_ire;
6587 	mblk_t	*dlureq_mp;
6588 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
6589 	ushort_t ire_marks = 0;
6590 	boolean_t mctl_present;
6591 	ipsec_out_t *io;
6592 	mblk_t	*saved_mp;
6593 	ire_t	*first_sire = NULL;
6594 	mblk_t	*copy_mp = NULL;
6595 	mblk_t	*xmit_mp = NULL;
6596 	ipaddr_t save_dst;
6597 	uint32_t multirt_flags =
6598 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
6599 	boolean_t multirt_is_resolvable;
6600 	boolean_t multirt_resolve_next;
6601 	boolean_t do_attach_ill = B_FALSE;
6602 	zoneid_t zoneid;
6603 
6604 	if (ip_debug > 2) {
6605 		/* ip1dbg */
6606 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
6607 	}
6608 
6609 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
6610 	if (mctl_present) {
6611 		io = (ipsec_out_t *)first_mp->b_rptr;
6612 		zoneid = io->ipsec_out_zoneid;
6613 		ASSERT(zoneid != ALL_ZONES);
6614 	} else if (connp != NULL) {
6615 		zoneid = connp->conn_zoneid;
6616 	} else {
6617 		zoneid = GLOBAL_ZONEID;
6618 	}
6619 
6620 	ipha = (ipha_t *)mp->b_rptr;
6621 
6622 	/* All multicast lookups come through ip_newroute_ipif() */
6623 	if (CLASSD(dst)) {
6624 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
6625 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
6626 		freemsg(first_mp);
6627 		return;
6628 	}
6629 
6630 	if (ip_loopback_src_or_dst(ipha, NULL)) {
6631 		goto icmp_err_ret;
6632 	}
6633 
6634 	if (mctl_present && io->ipsec_out_attach_if) {
6635 		/* ip_grab_attach_ill returns a held ill */
6636 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
6637 		    io->ipsec_out_ill_index, B_FALSE);
6638 
6639 		/* Failure case frees things for us. */
6640 		if (attach_ill == NULL)
6641 			return;
6642 
6643 		/*
6644 		 * Check if we need an ire that will not be
6645 		 * looked up by anybody else i.e. HIDDEN.
6646 		 */
6647 		if (ill_is_probeonly(attach_ill))
6648 			ire_marks = IRE_MARK_HIDDEN;
6649 	}
6650 	/*
6651 	 * If this IRE is created for forwarding or it is not for
6652 	 * traffic for congestion controlled protocols, mark it as temporary.
6653 	 */
6654 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
6655 		ire_marks |= IRE_MARK_TEMPORARY;
6656 
6657 	/*
6658 	 * Get what we can from ire_ftable_lookup which will follow an IRE
6659 	 * chain until it gets the most specific information available.
6660 	 * For example, we know that there is no IRE_CACHE for this dest,
6661 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
6662 	 * ire_ftable_lookup will look up the gateway, etc.
6663 	 * Check if in_ill != NULL. If it is true, the packet must be
6664 	 * from an incoming interface where RTA_SRCIFP is set.
6665 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
6666 	 * to the destination, of equal netmask length in the forward table,
6667 	 * will be recursively explored. If no information is available
6668 	 * for the final gateway of that route, we force the returned ire
6669 	 * to be equal to sire using MATCH_IRE_PARENT.
6670 	 * At least, in this case we have a starting point (in the buckets)
6671 	 * to look for other routes to the destination in the forward table.
6672 	 * This is actually used only for multirouting, where a list
6673 	 * of routes has to be processed in sequence.
6674 	 */
6675 	if (in_ill != NULL) {
6676 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
6677 		    in_ill, MATCH_IRE_TYPE);
6678 	} else if (attach_ill == NULL) {
6679 		ire = ire_ftable_lookup(dst, 0, 0, 0,
6680 		    NULL, &sire, zoneid, 0,
6681 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
6682 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT);
6683 	} else {
6684 		/*
6685 		 * attach_ill is set only for communicating with
6686 		 * on-link hosts. So, don't look for DEFAULT.
6687 		 */
6688 		ipif_t	*attach_ipif;
6689 
6690 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
6691 		if (attach_ipif == NULL) {
6692 			ill_refrele(attach_ill);
6693 			goto icmp_err_ret;
6694 		}
6695 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
6696 		    &sire, zoneid, 0,
6697 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL);
6698 		ipif_refrele(attach_ipif);
6699 	}
6700 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
6701 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
6702 
6703 	/*
6704 	 * This loop is run only once in most cases.
6705 	 * We loop to resolve further routes only when the destination
6706 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
6707 	 */
6708 	do {
6709 		/* Clear the previous iteration's values */
6710 		if (src_ipif != NULL) {
6711 			ipif_refrele(src_ipif);
6712 			src_ipif = NULL;
6713 		}
6714 		if (dst_ill != NULL) {
6715 			ill_refrele(dst_ill);
6716 			dst_ill = NULL;
6717 		}
6718 
6719 		multirt_resolve_next = B_FALSE;
6720 		/*
6721 		 * We check if packets have to be multirouted.
6722 		 * In this case, given the current <ire, sire> couple,
6723 		 * we look for the next suitable <ire, sire>.
6724 		 * This check is done in ire_multirt_lookup(),
6725 		 * which applies various criteria to find the next route
6726 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
6727 		 * unchanged if it detects it has not been tried yet.
6728 		 */
6729 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
6730 			ip3dbg(("ip_newroute: starting next_resolution "
6731 			    "with first_mp %p, tag %d\n",
6732 			    (void *)first_mp,
6733 			    MULTIRT_DEBUG_TAGGED(first_mp)));
6734 
6735 			ASSERT(sire != NULL);
6736 			multirt_is_resolvable =
6737 			    ire_multirt_lookup(&ire, &sire, multirt_flags);
6738 
6739 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
6740 			    "ire %p, sire %p\n",
6741 			    multirt_is_resolvable,
6742 			    (void *)ire, (void *)sire));
6743 
6744 			if (!multirt_is_resolvable) {
6745 				/*
6746 				 * No more multirt route to resolve; give up
6747 				 * (all routes resolved or no more
6748 				 * resolvable routes).
6749 				 */
6750 				if (ire != NULL) {
6751 					ire_refrele(ire);
6752 					ire = NULL;
6753 				}
6754 			} else {
6755 				ASSERT(sire != NULL);
6756 				ASSERT(ire != NULL);
6757 				/*
6758 				 * We simply use first_sire as a flag that
6759 				 * indicates if a resolvable multirt route
6760 				 * has already been found.
6761 				 * If it is not the case, we may have to send
6762 				 * an ICMP error to report that the
6763 				 * destination is unreachable.
6764 				 * We do not IRE_REFHOLD first_sire.
6765 				 */
6766 				if (first_sire == NULL) {
6767 					first_sire = sire;
6768 				}
6769 			}
6770 		}
6771 		if (ire == NULL) {
6772 			if (ip_debug > 3) {
6773 				/* ip2dbg */
6774 				pr_addr_dbg("ip_newroute: "
6775 				    "can't resolve %s\n", AF_INET, &dst);
6776 			}
6777 			ip3dbg(("ip_newroute: "
6778 			    "ire %p, sire %p, first_sire %p\n",
6779 			    (void *)ire, (void *)sire, (void *)first_sire));
6780 
6781 			if (sire != NULL) {
6782 				ire_refrele(sire);
6783 				sire = NULL;
6784 			}
6785 
6786 			if (first_sire != NULL) {
6787 				/*
6788 				 * At least one multirt route has been found
6789 				 * in the same call to ip_newroute();
6790 				 * there is no need to report an ICMP error.
6791 				 * first_sire was not IRE_REFHOLDed.
6792 				 */
6793 				MULTIRT_DEBUG_UNTAG(first_mp);
6794 				freemsg(first_mp);
6795 				return;
6796 			}
6797 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
6798 			    RTA_DST);
6799 			if (attach_ill != NULL)
6800 				ill_refrele(attach_ill);
6801 			goto icmp_err_ret;
6802 		}
6803 
6804 		/*
6805 		 * When RTA_SRCIFP is used to add a route, then an interface
6806 		 * route is added in the source interface's routing table.
6807 		 * If the outgoing interface of this route is of type
6808 		 * IRE_IF_RESOLVER, then upon creation of the ire,
6809 		 * ire_dlureq_mp is set to NULL. Later, when this route is
6810 		 * first used for forwarding packet, ip_newroute() is called
6811 		 * to resolve the hardware address of the outgoing ipif.
6812 		 * We do not come here for IRE_IF_NORESOLVER entries in the
6813 		 * source interface based table. We only come here if the
6814 		 * outgoing interface is a resolver interface and we don't
6815 		 * have the ire_dlureq_mp information yet.
6816 		 * If in_ill is not null that means it is called from
6817 		 * ip_rput.
6818 		 */
6819 
6820 		ASSERT(ire->ire_in_ill == NULL ||
6821 		    (ire->ire_type == IRE_IF_RESOLVER &&
6822 		    ire->ire_dlureq_mp == NULL));
6823 
6824 		/*
6825 		 * Verify that the returned IRE does not have either
6826 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
6827 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
6828 		 */
6829 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
6830 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
6831 			if (attach_ill != NULL)
6832 				ill_refrele(attach_ill);
6833 			goto icmp_err_ret;
6834 		}
6835 		/*
6836 		 * Increment the ire_ob_pkt_count field for ire if it is an
6837 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
6838 		 * increment the same for the parent IRE, sire, if it is some
6839 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
6840 		 * and HOST_REDIRECT).
6841 		 */
6842 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
6843 			UPDATE_OB_PKT_COUNT(ire);
6844 			ire->ire_last_used_time = lbolt;
6845 		}
6846 
6847 		if (sire != NULL) {
6848 			gw = sire->ire_gateway_addr;
6849 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
6850 			    IRE_INTERFACE)) == 0);
6851 			UPDATE_OB_PKT_COUNT(sire);
6852 			sire->ire_last_used_time = lbolt;
6853 		}
6854 		/*
6855 		 * We have a route to reach the destination.
6856 		 *
6857 		 * 1) If the interface is part of ill group, try to get a new
6858 		 *    ill taking load spreading into account.
6859 		 *
6860 		 * 2) After selecting the ill, get a source address that
6861 		 *    might create good inbound load spreading.
6862 		 *    ipif_select_source does this for us.
6863 		 *
6864 		 * If the application specified the ill (ifindex), we still
6865 		 * load spread. Only if the packets needs to go out
6866 		 * specifically on a given ill e.g. binding to
6867 		 * IPIF_NOFAILOVER address, then we don't try to use a
6868 		 * different ill for load spreading.
6869 		 */
6870 		if (attach_ill == NULL) {
6871 			/*
6872 			 * Don't perform outbound load spreading in the
6873 			 * case of an RTF_MULTIRT route, as we actually
6874 			 * typically want to replicate outgoing packets
6875 			 * through particular interfaces.
6876 			 */
6877 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
6878 				dst_ill = ire->ire_ipif->ipif_ill;
6879 				/* for uniformity */
6880 				ill_refhold(dst_ill);
6881 			} else {
6882 				/*
6883 				 * If we are here trying to create an IRE_CACHE
6884 				 * for an offlink destination and have the
6885 				 * IRE_CACHE for the next hop and the latter is
6886 				 * using virtual IP source address selection i.e
6887 				 * it's ire->ire_ipif is pointing to a virtual
6888 				 * network interface (vni) then
6889 				 * ip_newroute_get_dst_ll() will return the vni
6890 				 * interface as the dst_ill. Since the vni is
6891 				 * virtual i.e not associated with any physical
6892 				 * interface, it cannot be the dst_ill, hence
6893 				 * in such a case call ip_newroute_get_dst_ll()
6894 				 * with the stq_ill instead of the ire_ipif ILL.
6895 				 * The function returns a refheld ill.
6896 				 */
6897 				if ((ire->ire_type == IRE_CACHE) &&
6898 				    IS_VNI(ire->ire_ipif->ipif_ill))
6899 					dst_ill = ip_newroute_get_dst_ill(
6900 						ire->ire_stq->q_ptr);
6901 				else
6902 					dst_ill = ip_newroute_get_dst_ill(
6903 						ire->ire_ipif->ipif_ill);
6904 			}
6905 			if (dst_ill == NULL) {
6906 				if (ip_debug > 2) {
6907 					pr_addr_dbg("ip_newroute: "
6908 					    "no dst ill for dst"
6909 					    " %s\n", AF_INET, &dst);
6910 				}
6911 				goto icmp_err_ret;
6912 			}
6913 		} else {
6914 			dst_ill = ire->ire_ipif->ipif_ill;
6915 			/* for uniformity */
6916 			ill_refhold(dst_ill);
6917 			/*
6918 			 * We should have found a route matching ill as we
6919 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
6920 			 * Rather than asserting, when there is a mismatch,
6921 			 * we just drop the packet.
6922 			 */
6923 			if (dst_ill != attach_ill) {
6924 				ip0dbg(("ip_newroute: Packet dropped as "
6925 				    "IPIF_NOFAILOVER ill is %s, "
6926 				    "ire->ire_ipif->ipif_ill is %s\n",
6927 				    attach_ill->ill_name,
6928 				    dst_ill->ill_name));
6929 				ill_refrele(attach_ill);
6930 				goto icmp_err_ret;
6931 			}
6932 		}
6933 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
6934 		if (attach_ill != NULL) {
6935 			ill_refrele(attach_ill);
6936 			attach_ill = NULL;
6937 			do_attach_ill = B_TRUE;
6938 		}
6939 		ASSERT(dst_ill != NULL);
6940 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
6941 
6942 		/*
6943 		 * Pick the best source address from dst_ill.
6944 		 *
6945 		 * 1) If it is part of a multipathing group, we would
6946 		 *    like to spread the inbound packets across different
6947 		 *    interfaces. ipif_select_source picks a random source
6948 		 *    across the different ills in the group.
6949 		 *
6950 		 * 2) If it is not part of a multipathing group, we try
6951 		 *    to pick the source address from the destination
6952 		 *    route. Clustering assumes that when we have multiple
6953 		 *    prefixes hosted on an interface, the prefix of the
6954 		 *    source address matches the prefix of the destination
6955 		 *    route. We do this only if the address is not
6956 		 *    DEPRECATED.
6957 		 *
6958 		 * 3) If the conn is in a different zone than the ire, we
6959 		 *    need to pick a source address from the right zone.
6960 		 *
6961 		 * NOTE : If we hit case (1) above, the prefix of the source
6962 		 *	  address picked may not match the prefix of the
6963 		 *	  destination routes prefix as ipif_select_source
6964 		 *	  does not look at "dst" while picking a source
6965 		 *	  address.
6966 		 *	  If we want the same behavior as (2), we will need
6967 		 *	  to change the behavior of ipif_select_source.
6968 		 */
6969 		ASSERT(src_ipif == NULL);
6970 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
6971 			/*
6972 			 * The RTF_SETSRC flag is set in the parent ire (sire).
6973 			 * Check that the ipif matching the requested source
6974 			 * address still exists.
6975 			 */
6976 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
6977 			    zoneid, NULL, NULL, NULL, NULL);
6978 		}
6979 		if (src_ipif == NULL) {
6980 			ire_marks |= IRE_MARK_USESRC_CHECK;
6981 			if ((dst_ill->ill_group != NULL) ||
6982 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
6983 			    (connp != NULL && ire->ire_zoneid != zoneid) ||
6984 			    (dst_ill->ill_usesrc_ifindex != 0)) {
6985 				src_ipif = ipif_select_source(dst_ill, dst,
6986 				    zoneid);
6987 				if (src_ipif == NULL) {
6988 					if (ip_debug > 2) {
6989 						pr_addr_dbg("ip_newroute: "
6990 						    "no src for dst %s ",
6991 						    AF_INET, &dst);
6992 						printf("through interface %s\n",
6993 						    dst_ill->ill_name);
6994 					}
6995 					goto icmp_err_ret;
6996 				}
6997 			} else {
6998 				src_ipif = ire->ire_ipif;
6999 				ASSERT(src_ipif != NULL);
7000 				/* hold src_ipif for uniformity */
7001 				ipif_refhold(src_ipif);
7002 			}
7003 		}
7004 
7005 		/*
7006 		 * Assign a source address while we have the conn.
7007 		 * We can't have ip_wput_ire pick a source address when the
7008 		 * packet returns from arp since we need to look at
7009 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
7010 		 * going through arp.
7011 		 *
7012 		 * NOTE : ip_newroute_v6 does not have this piece of code as
7013 		 *	  it uses ip6i to store this information.
7014 		 */
7015 		if (ipha->ipha_src == INADDR_ANY &&
7016 		    (connp == NULL || !connp->conn_unspec_src)) {
7017 			ipha->ipha_src = src_ipif->ipif_src_addr;
7018 		}
7019 		if (ip_debug > 3) {
7020 			/* ip2dbg */
7021 			pr_addr_dbg("ip_newroute: first hop %s\n",
7022 			    AF_INET, &gw);
7023 		}
7024 		ip2dbg(("\tire type %s (%d)\n",
7025 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
7026 
7027 		/*
7028 		 * The TTL of multirouted packets is bounded by the
7029 		 * ip_multirt_ttl ndd variable.
7030 		 */
7031 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7032 			/* Force TTL of multirouted packets */
7033 			if ((ip_multirt_ttl > 0) &&
7034 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
7035 				ip2dbg(("ip_newroute: forcing multirt TTL "
7036 				    "to %d (was %d), dst 0x%08x\n",
7037 				    ip_multirt_ttl, ipha->ipha_ttl,
7038 				    ntohl(sire->ire_addr)));
7039 				ipha->ipha_ttl = ip_multirt_ttl;
7040 			}
7041 		}
7042 		/*
7043 		 * At this point in ip_newroute(), ire is either the
7044 		 * IRE_CACHE of the next-hop gateway for an off-subnet
7045 		 * destination or an IRE_INTERFACE type that should be used
7046 		 * to resolve an on-subnet destination or an on-subnet
7047 		 * next-hop gateway.
7048 		 *
7049 		 * In the IRE_CACHE case, we have the following :
7050 		 *
7051 		 * 1) src_ipif - used for getting a source address.
7052 		 *
7053 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
7054 		 *    means packets using this IRE_CACHE will go out on
7055 		 *    dst_ill.
7056 		 *
7057 		 * 3) The IRE sire will point to the prefix that is the
7058 		 *    longest  matching route for the destination. These
7059 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST,
7060 		 *    and IRE_HOST_REDIRECT.
7061 		 *
7062 		 *    The newly created IRE_CACHE entry for the off-subnet
7063 		 *    destination is tied to both the prefix route and the
7064 		 *    interface route used to resolve the next-hop gateway
7065 		 *    via the ire_phandle and ire_ihandle fields,
7066 		 *    respectively.
7067 		 *
7068 		 * In the IRE_INTERFACE case, we have the following :
7069 		 *
7070 		 * 1) src_ipif - used for getting a source address.
7071 		 *
7072 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
7073 		 *    means packets using the IRE_CACHE that we will build
7074 		 *    here will go out on dst_ill.
7075 		 *
7076 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
7077 		 *    to be created will only be tied to the IRE_INTERFACE
7078 		 *    that was derived from the ire_ihandle field.
7079 		 *
7080 		 *    If sire is non-NULL, it means the destination is
7081 		 *    off-link and we will first create the IRE_CACHE for the
7082 		 *    gateway. Next time through ip_newroute, we will create
7083 		 *    the IRE_CACHE for the final destination as described
7084 		 *    above.
7085 		 *
7086 		 * In both cases, after the current resolution has been
7087 		 * completed (or possibly initialised, in the IRE_INTERFACE
7088 		 * case), the loop may be re-entered to attempt the resolution
7089 		 * of another RTF_MULTIRT route.
7090 		 *
7091 		 * When an IRE_CACHE entry for the off-subnet destination is
7092 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
7093 		 * for further processing in emission loops.
7094 		 */
7095 		save_ire = ire;
7096 		switch (ire->ire_type) {
7097 		case IRE_CACHE: {
7098 			ire_t	*ipif_ire;
7099 			mblk_t	*ire_fp_mp;
7100 
7101 			ASSERT(sire != NULL);
7102 			if (gw == 0)
7103 				gw = ire->ire_gateway_addr;
7104 			/*
7105 			 * We need 3 ire's to create a new cache ire for an
7106 			 * off-link destination from the cache ire of the
7107 			 * gateway.
7108 			 *
7109 			 *	1. The prefix ire 'sire'
7110 			 *	2. The cache ire of the gateway 'ire'
7111 			 *	3. The interface ire 'ipif_ire'
7112 			 *
7113 			 * We have (1) and (2). We lookup (3) below.
7114 			 *
7115 			 * If there is no interface route to the gateway,
7116 			 * it is a race condition, where we found the cache
7117 			 * but the inteface route has been deleted.
7118 			 */
7119 			ipif_ire = ire_ihandle_lookup_offlink(ire, sire);
7120 			if (ipif_ire == NULL) {
7121 				ip1dbg(("ip_newroute: "
7122 				    "ire_ihandle_lookup_offlink failed\n"));
7123 				goto icmp_err_ret;
7124 			}
7125 			/*
7126 			 * XXX We are using the same dlureq_mp
7127 			 * (DL_UNITDATA_REQ) though the save_ire is not
7128 			 * pointing at the same ill.
7129 			 * This is incorrect. We need to send it up to the
7130 			 * resolver to get the right dlureq_mp. For ethernets
7131 			 * this may be okay (ill_type == DL_ETHER).
7132 			 */
7133 			dlureq_mp = save_ire->ire_dlureq_mp;
7134 			ire_fp_mp = NULL;
7135 			/*
7136 			 * save_ire's ire_fp_mp can't change since it is
7137 			 * not an IRE_MIPRTUN or IRE_BROADCAST
7138 			 * LOCK_IRE_FP_MP does not do any useful work in
7139 			 * the case of IRE_CACHE. So we don't use it below.
7140 			 */
7141 			if (save_ire->ire_stq == dst_ill->ill_wq)
7142 				ire_fp_mp = save_ire->ire_fp_mp;
7143 
7144 			ire = ire_create(
7145 			    (uchar_t *)&dst,		/* dest address */
7146 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7147 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7148 			    (uchar_t *)&gw,		/* gateway address */
7149 			    NULL,
7150 			    &save_ire->ire_max_frag,
7151 			    ire_fp_mp,			/* Fast Path header */
7152 			    dst_ill->ill_rq,		/* recv-from queue */
7153 			    dst_ill->ill_wq,		/* send-to queue */
7154 			    IRE_CACHE,			/* IRE type */
7155 			    save_ire->ire_dlureq_mp,
7156 			    src_ipif,
7157 			    in_ill,			/* incoming ill */
7158 			    sire->ire_mask,		/* Parent mask */
7159 			    sire->ire_phandle,		/* Parent handle */
7160 			    ipif_ire->ire_ihandle,	/* Interface handle */
7161 			    sire->ire_flags &
7162 				(RTF_SETSRC | RTF_MULTIRT), /* flags if any */
7163 			    &(sire->ire_uinfo));
7164 
7165 			if (ire == NULL) {
7166 				ire_refrele(ipif_ire);
7167 				ire_refrele(save_ire);
7168 				break;
7169 			}
7170 
7171 			ire->ire_marks |= ire_marks;
7172 
7173 			/*
7174 			 * Prevent sire and ipif_ire from getting deleted.
7175 			 * The newly created ire is tied to both of them via
7176 			 * the phandle and ihandle respectively.
7177 			 */
7178 			IRB_REFHOLD(sire->ire_bucket);
7179 			/* Has it been removed already ? */
7180 			if (sire->ire_marks & IRE_MARK_CONDEMNED) {
7181 				IRB_REFRELE(sire->ire_bucket);
7182 				ire_refrele(ipif_ire);
7183 				ire_refrele(save_ire);
7184 				break;
7185 			}
7186 
7187 			IRB_REFHOLD(ipif_ire->ire_bucket);
7188 			/* Has it been removed already ? */
7189 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
7190 				IRB_REFRELE(ipif_ire->ire_bucket);
7191 				IRB_REFRELE(sire->ire_bucket);
7192 				ire_refrele(ipif_ire);
7193 				ire_refrele(save_ire);
7194 				break;
7195 			}
7196 
7197 			xmit_mp = first_mp;
7198 			/*
7199 			 * In the case of multirouting, a copy
7200 			 * of the packet is done before its sending.
7201 			 * The copy is used to attempt another
7202 			 * route resolution, in a next loop.
7203 			 */
7204 			if (ire->ire_flags & RTF_MULTIRT) {
7205 				copy_mp = copymsg(first_mp);
7206 				if (copy_mp != NULL) {
7207 					xmit_mp = copy_mp;
7208 					MULTIRT_DEBUG_TAG(first_mp);
7209 				}
7210 			}
7211 			ire_add_then_send(q, ire, xmit_mp);
7212 			ire_refrele(save_ire);
7213 
7214 			/* Assert that sire is not deleted yet. */
7215 			ASSERT(sire->ire_ptpn != NULL);
7216 			IRB_REFRELE(sire->ire_bucket);
7217 
7218 			/* Assert that ipif_ire is not deleted yet. */
7219 			ASSERT(ipif_ire->ire_ptpn != NULL);
7220 			IRB_REFRELE(ipif_ire->ire_bucket);
7221 			ire_refrele(ipif_ire);
7222 
7223 			/*
7224 			 * If copy_mp is not NULL, multirouting was
7225 			 * requested. We loop to initiate a next
7226 			 * route resolution attempt, starting from sire.
7227 			 */
7228 			if (copy_mp != NULL) {
7229 				/*
7230 				 * Search for the next unresolved
7231 				 * multirt route.
7232 				 */
7233 				copy_mp = NULL;
7234 				ipif_ire = NULL;
7235 				ire = NULL;
7236 				multirt_resolve_next = B_TRUE;
7237 				continue;
7238 			}
7239 
7240 			ire_refrele(sire);
7241 			ipif_refrele(src_ipif);
7242 			ill_refrele(dst_ill);
7243 			return;
7244 		}
7245 		case IRE_IF_NORESOLVER: {
7246 			/*
7247 			 * We have what we need to build an IRE_CACHE.
7248 			 *
7249 			 * Create a new dlureq_mp with the IP gateway address
7250 			 * in destination address in the DLPI hdr if the
7251 			 * physical length is exactly 4 bytes.
7252 			 */
7253 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
7254 				uchar_t *addr;
7255 
7256 				if (gw)
7257 					addr = (uchar_t *)&gw;
7258 				else
7259 					addr = (uchar_t *)&dst;
7260 
7261 				dlureq_mp = ill_dlur_gen(addr,
7262 				    dst_ill->ill_phys_addr_length,
7263 				    dst_ill->ill_sap,
7264 				    dst_ill->ill_sap_length);
7265 			} else {
7266 				dlureq_mp = ire->ire_dlureq_mp;
7267 			}
7268 
7269 			if (dlureq_mp == NULL) {
7270 				ip1dbg(("ip_newroute: dlureq_mp NULL\n"));
7271 				break;
7272 			}
7273 
7274 			ire = ire_create(
7275 			    (uchar_t *)&dst,		/* dest address */
7276 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7277 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7278 			    (uchar_t *)&gw,		/* gateway address */
7279 			    NULL,
7280 			    &save_ire->ire_max_frag,
7281 			    NULL,			/* Fast Path header */
7282 			    dst_ill->ill_rq,		/* recv-from queue */
7283 			    dst_ill->ill_wq,		/* send-to queue */
7284 			    IRE_CACHE,
7285 			    dlureq_mp,
7286 			    src_ipif,
7287 			    in_ill,			/* Incoming ill */
7288 			    save_ire->ire_mask,		/* Parent mask */
7289 			    (sire != NULL) ?		/* Parent handle */
7290 				sire->ire_phandle : 0,
7291 			    save_ire->ire_ihandle,	/* Interface handle */
7292 			    (sire != NULL) ? sire->ire_flags &
7293 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
7294 			    &(save_ire->ire_uinfo));
7295 
7296 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
7297 				freeb(dlureq_mp);
7298 
7299 			if (ire == NULL) {
7300 				ire_refrele(save_ire);
7301 				break;
7302 			}
7303 
7304 			ire->ire_marks |= ire_marks;
7305 
7306 			/* Prevent save_ire from getting deleted */
7307 			IRB_REFHOLD(save_ire->ire_bucket);
7308 			/* Has it been removed already ? */
7309 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
7310 				IRB_REFRELE(save_ire->ire_bucket);
7311 				ire_refrele(save_ire);
7312 				break;
7313 			}
7314 
7315 			/*
7316 			 * In the case of multirouting, a copy
7317 			 * of the packet is made before it is sent.
7318 			 * The copy is used in the next
7319 			 * loop to attempt another resolution.
7320 			 */
7321 			xmit_mp = first_mp;
7322 			if ((sire != NULL) &&
7323 			    (sire->ire_flags & RTF_MULTIRT)) {
7324 				copy_mp = copymsg(first_mp);
7325 				if (copy_mp != NULL) {
7326 					xmit_mp = copy_mp;
7327 					MULTIRT_DEBUG_TAG(first_mp);
7328 				}
7329 			}
7330 			ire_add_then_send(q, ire, xmit_mp);
7331 
7332 			/* Assert that it is not deleted yet. */
7333 			ASSERT(save_ire->ire_ptpn != NULL);
7334 			IRB_REFRELE(save_ire->ire_bucket);
7335 			ire_refrele(save_ire);
7336 
7337 			if (copy_mp != NULL) {
7338 				/*
7339 				 * If we found a (no)resolver, we ignore any
7340 				 * trailing top priority IRE_CACHE in further
7341 				 * loops. This ensures that we do not omit any
7342 				 * (no)resolver.
7343 				 * This IRE_CACHE, if any, will be processed
7344 				 * by another thread entering ip_newroute().
7345 				 * IRE_CACHE entries, if any, will be processed
7346 				 * by another thread entering ip_newroute(),
7347 				 * (upon resolver response, for instance).
7348 				 * This aims to force parallel multirt
7349 				 * resolutions as soon as a packet must be sent.
7350 				 * In the best case, after the tx of only one
7351 				 * packet, all reachable routes are resolved.
7352 				 * Otherwise, the resolution of all RTF_MULTIRT
7353 				 * routes would require several emissions.
7354 				 */
7355 				multirt_flags &= ~MULTIRT_CACHEGW;
7356 
7357 				/*
7358 				 * Search for the next unresolved multirt
7359 				 * route.
7360 				 */
7361 				copy_mp = NULL;
7362 				save_ire = NULL;
7363 				ire = NULL;
7364 				multirt_resolve_next = B_TRUE;
7365 				continue;
7366 			}
7367 
7368 			/*
7369 			 * Don't need sire anymore
7370 			 */
7371 			if (sire != NULL)
7372 				ire_refrele(sire);
7373 
7374 			ipif_refrele(src_ipif);
7375 			ill_refrele(dst_ill);
7376 			return;
7377 		}
7378 		case IRE_IF_RESOLVER:
7379 			/*
7380 			 * We can't build an IRE_CACHE yet, but at least we
7381 			 * found a resolver that can help.
7382 			 */
7383 			res_mp = dst_ill->ill_resolver_mp;
7384 			if (!OK_RESOLVER_MP(res_mp))
7385 				break;
7386 			/*
7387 			 * To be at this point in the code with a non-zero gw
7388 			 * means that dst is reachable through a gateway that
7389 			 * we have never resolved.  By changing dst to the gw
7390 			 * addr we resolve the gateway first.
7391 			 * When ire_add_then_send() tries to put the IP dg
7392 			 * to dst, it will reenter ip_newroute() at which
7393 			 * time we will find the IRE_CACHE for the gw and
7394 			 * create another IRE_CACHE in case IRE_CACHE above.
7395 			 */
7396 			if (gw != INADDR_ANY) {
7397 				/*
7398 				 * The source ipif that was determined above was
7399 				 * relative to the destination address, not the
7400 				 * gateway's. If src_ipif was not taken out of
7401 				 * the IRE_IF_RESOLVER entry, we'll need to call
7402 				 * ipif_select_source() again.
7403 				 */
7404 				if (src_ipif != ire->ire_ipif) {
7405 					ipif_refrele(src_ipif);
7406 					src_ipif = ipif_select_source(dst_ill,
7407 					    gw, zoneid);
7408 					if (src_ipif == NULL) {
7409 						if (ip_debug > 2) {
7410 							pr_addr_dbg(
7411 							    "ip_newroute: no "
7412 							    "src for gw %s ",
7413 							    AF_INET, &gw);
7414 							printf("through "
7415 							    "interface %s\n",
7416 							    dst_ill->ill_name);
7417 						}
7418 						goto icmp_err_ret;
7419 					}
7420 				}
7421 				save_dst = dst;
7422 				dst = gw;
7423 				gw = INADDR_ANY;
7424 			}
7425 			/*
7426 			 * We obtain a partial IRE_CACHE which we will pass
7427 			 * along with the resolver query.  When the response
7428 			 * comes back it will be there ready for us to add.
7429 			 * The ire_max_frag is atomically set under the
7430 			 * irebucket lock in ire_add_v[46].
7431 			 */
7432 			ire = ire_create_mp(
7433 			    (uchar_t *)&dst,		/* dest address */
7434 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7435 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7436 			    (uchar_t *)&gw,		/* gateway address */
7437 			    NULL,			/* no in_src_addr */
7438 			    NULL,			/* ire_max_frag */
7439 			    NULL,			/* Fast Path header */
7440 			    dst_ill->ill_rq,		/* recv-from queue */
7441 			    dst_ill->ill_wq,		/* send-to queue */
7442 			    IRE_CACHE,
7443 			    res_mp,
7444 			    src_ipif,			/* Interface ipif */
7445 			    in_ill,			/* Incoming ILL */
7446 			    save_ire->ire_mask,		/* Parent mask */
7447 			    0,
7448 			    save_ire->ire_ihandle,	/* Interface handle */
7449 			    0,				/* flags if any */
7450 			    &(save_ire->ire_uinfo));
7451 
7452 			if (ire == NULL) {
7453 				ire_refrele(save_ire);
7454 				break;
7455 			}
7456 
7457 			if ((sire != NULL) &&
7458 			    (sire->ire_flags & RTF_MULTIRT)) {
7459 				copy_mp = copymsg(first_mp);
7460 				if (copy_mp != NULL)
7461 					MULTIRT_DEBUG_TAG(copy_mp);
7462 			}
7463 
7464 			ire->ire_marks |= ire_marks;
7465 
7466 			/*
7467 			 * Construct message chain for the resolver
7468 			 * of the form:
7469 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
7470 			 * Packet could contain a IPSEC_OUT mp.
7471 			 *
7472 			 * NOTE : ire will be added later when the response
7473 			 * comes back from ARP. If the response does not
7474 			 * come back, ARP frees the packet. For this reason,
7475 			 * we can't REFHOLD the bucket of save_ire to prevent
7476 			 * deletions. We may not be able to REFRELE the bucket
7477 			 * if the response never comes back. Thus, before
7478 			 * adding the ire, ire_add_v4 will make sure that the
7479 			 * interface route does not get deleted. This is the
7480 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
7481 			 * where we can always prevent deletions because of
7482 			 * the synchronous nature of adding IRES i.e
7483 			 * ire_add_then_send is called after creating the IRE.
7484 			 */
7485 			ASSERT(ire->ire_mp != NULL);
7486 			ire->ire_mp->b_cont = first_mp;
7487 			/* Have saved_mp handy, for cleanup if canput fails */
7488 			saved_mp = mp;
7489 			mp = ire->ire_dlureq_mp;
7490 			ASSERT(mp != NULL);
7491 			ire->ire_dlureq_mp = NULL;
7492 			linkb(mp, ire->ire_mp);
7493 
7494 
7495 			/*
7496 			 * Fill in the source and dest addrs for the resolver.
7497 			 * NOTE: this depends on memory layouts imposed by
7498 			 * ill_init().
7499 			 */
7500 			areq = (areq_t *)mp->b_rptr;
7501 			addrp = (ipaddr_t *)((char *)areq +
7502 			    areq->areq_sender_addr_offset);
7503 			if (do_attach_ill) {
7504 				/*
7505 				 * This is bind to no failover case.
7506 				 * arp packet also must go out on attach_ill.
7507 				 */
7508 				ASSERT(ipha->ipha_src != NULL);
7509 				*addrp = ipha->ipha_src;
7510 			} else {
7511 				*addrp = save_ire->ire_src_addr;
7512 			}
7513 
7514 			ire_refrele(save_ire);
7515 			addrp = (ipaddr_t *)((char *)areq +
7516 			    areq->areq_target_addr_offset);
7517 			*addrp = dst;
7518 			/* Up to the resolver. */
7519 			if (canputnext(dst_ill->ill_rq)) {
7520 				putnext(dst_ill->ill_rq, mp);
7521 				ire = NULL;
7522 				if (copy_mp != NULL) {
7523 					/*
7524 					 * If we found a resolver, we ignore
7525 					 * any trailing top priority IRE_CACHE
7526 					 * in the further loops. This ensures
7527 					 * that we do not omit any resolver.
7528 					 * IRE_CACHE entries, if any, will be
7529 					 * processed next time we enter
7530 					 * ip_newroute().
7531 					 */
7532 					multirt_flags &= ~MULTIRT_CACHEGW;
7533 					/*
7534 					 * Search for the next unresolved
7535 					 * multirt route.
7536 					 */
7537 					first_mp = copy_mp;
7538 					copy_mp = NULL;
7539 					/* Prepare the next resolution loop. */
7540 					mp = first_mp;
7541 					EXTRACT_PKT_MP(mp, first_mp,
7542 					    mctl_present);
7543 					if (mctl_present)
7544 						io = (ipsec_out_t *)
7545 						    first_mp->b_rptr;
7546 					ipha = (ipha_t *)mp->b_rptr;
7547 
7548 					ASSERT(sire != NULL);
7549 
7550 					dst = save_dst;
7551 					multirt_resolve_next = B_TRUE;
7552 					continue;
7553 				}
7554 
7555 				if (sire != NULL)
7556 					ire_refrele(sire);
7557 
7558 				/*
7559 				 * The response will come back in ip_wput
7560 				 * with db_type IRE_DB_TYPE.
7561 				 */
7562 				ipif_refrele(src_ipif);
7563 				ill_refrele(dst_ill);
7564 				return;
7565 			} else {
7566 				/* Prepare for cleanup */
7567 				ire->ire_dlureq_mp = mp;
7568 				mp->b_cont = NULL;
7569 				ire_delete(ire);
7570 				mp = saved_mp;
7571 				ire = NULL;
7572 				if (copy_mp != NULL) {
7573 					MULTIRT_DEBUG_UNTAG(copy_mp);
7574 					freemsg(copy_mp);
7575 					copy_mp = NULL;
7576 				}
7577 				break;
7578 			}
7579 		default:
7580 			break;
7581 		}
7582 	} while (multirt_resolve_next);
7583 
7584 	ip1dbg(("ip_newroute: dropped\n"));
7585 	/* Did this packet originate externally? */
7586 	if (mp->b_prev) {
7587 		mp->b_next = NULL;
7588 		mp->b_prev = NULL;
7589 		BUMP_MIB(&ip_mib, ipInDiscards);
7590 	} else {
7591 		BUMP_MIB(&ip_mib, ipOutDiscards);
7592 	}
7593 	ASSERT(copy_mp == NULL);
7594 	MULTIRT_DEBUG_UNTAG(first_mp);
7595 	freemsg(first_mp);
7596 	if (ire != NULL)
7597 		ire_refrele(ire);
7598 	if (sire != NULL)
7599 		ire_refrele(sire);
7600 	if (src_ipif != NULL)
7601 		ipif_refrele(src_ipif);
7602 	if (dst_ill != NULL)
7603 		ill_refrele(dst_ill);
7604 	return;
7605 
7606 icmp_err_ret:
7607 	ip1dbg(("ip_newroute: no route\n"));
7608 	if (src_ipif != NULL)
7609 		ipif_refrele(src_ipif);
7610 	if (dst_ill != NULL)
7611 		ill_refrele(dst_ill);
7612 	if (sire != NULL)
7613 		ire_refrele(sire);
7614 	/* Did this packet originate externally? */
7615 	if (mp->b_prev) {
7616 		mp->b_next = NULL;
7617 		mp->b_prev = NULL;
7618 		/* XXX ipInNoRoutes */
7619 		q = WR(q);
7620 	} else {
7621 		/*
7622 		 * Since ip_wput() isn't close to finished, we fill
7623 		 * in enough of the header for credible error reporting.
7624 		 */
7625 		if (ip_hdr_complete(ipha, zoneid)) {
7626 			/* Failed */
7627 			MULTIRT_DEBUG_UNTAG(first_mp);
7628 			freemsg(first_mp);
7629 			if (ire != NULL)
7630 				ire_refrele(ire);
7631 			return;
7632 		}
7633 	}
7634 	BUMP_MIB(&ip_mib, ipOutNoRoutes);
7635 
7636 	/*
7637 	 * At this point we will have ire only if RTF_BLACKHOLE
7638 	 * or RTF_REJECT flags are set on the IRE. It will not
7639 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
7640 	 */
7641 	if (ire != NULL) {
7642 		if (ire->ire_flags & RTF_BLACKHOLE) {
7643 			ire_refrele(ire);
7644 			MULTIRT_DEBUG_UNTAG(first_mp);
7645 			freemsg(first_mp);
7646 			return;
7647 		}
7648 		ire_refrele(ire);
7649 	}
7650 	if (ip_source_routed(ipha)) {
7651 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED);
7652 		return;
7653 	}
7654 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE);
7655 }
7656 
7657 /*
7658  * IPv4 -
7659  * ip_newroute_ipif is called by ip_wput_multicast and
7660  * ip_rput_forward_multicast whenever we need to send
7661  * out a packet to a destination address for which we do not have specific
7662  * routing information. It is used when the packet will be sent out
7663  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
7664  * socket option is set or icmp error message wants to go out on a particular
7665  * interface for a unicast packet.
7666  *
7667  * In most cases, the destination address is resolved thanks to the ipif
7668  * intrinsic resolver. However, there are some cases where the call to
7669  * ip_newroute_ipif must take into account the potential presence of
7670  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
7671  * that uses the interface. This is specified through flags,
7672  * which can be a combination of:
7673  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
7674  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
7675  *   and flags. Additionally, the packet source address has to be set to
7676  *   the specified address. The caller is thus expected to set this flag
7677  *   if the packet has no specific source address yet.
7678  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
7679  *   flag, the resulting ire will inherit the flag. All unresolved routes
7680  *   to the destination must be explored in the same call to
7681  *   ip_newroute_ipif().
7682  */
7683 static void
7684 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
7685     conn_t *connp, uint32_t flags)
7686 {
7687 	areq_t	*areq;
7688 	ire_t	*ire = NULL;
7689 	mblk_t	*res_mp;
7690 	ipaddr_t *addrp;
7691 	mblk_t *first_mp;
7692 	ire_t	*save_ire = NULL;
7693 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
7694 	ipif_t	*src_ipif = NULL;
7695 	ushort_t ire_marks = 0;
7696 	ill_t	*dst_ill = NULL;
7697 	boolean_t mctl_present;
7698 	ipsec_out_t *io;
7699 	ipha_t *ipha;
7700 	int	ihandle = 0;
7701 	mblk_t	*saved_mp;
7702 	ire_t   *fire = NULL;
7703 	mblk_t  *copy_mp = NULL;
7704 	boolean_t multirt_resolve_next;
7705 	ipaddr_t ipha_dst;
7706 	zoneid_t zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
7707 
7708 	/*
7709 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
7710 	 * here for uniformity
7711 	 */
7712 	ipif_refhold(ipif);
7713 
7714 	/*
7715 	 * This loop is run only once in most cases.
7716 	 * We loop to resolve further routes only when the destination
7717 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7718 	 */
7719 	do {
7720 		if (dst_ill != NULL) {
7721 			ill_refrele(dst_ill);
7722 			dst_ill = NULL;
7723 		}
7724 		if (src_ipif != NULL) {
7725 			ipif_refrele(src_ipif);
7726 			src_ipif = NULL;
7727 		}
7728 		multirt_resolve_next = B_FALSE;
7729 
7730 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
7731 		    ipif->ipif_ill->ill_name));
7732 
7733 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7734 		if (mctl_present)
7735 			io = (ipsec_out_t *)first_mp->b_rptr;
7736 
7737 		ipha = (ipha_t *)mp->b_rptr;
7738 
7739 		/*
7740 		 * Save the packet destination address, we may need it after
7741 		 * the packet has been consumed.
7742 		 */
7743 		ipha_dst = ipha->ipha_dst;
7744 
7745 		/*
7746 		 * If the interface is a pt-pt interface we look for an
7747 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
7748 		 * local_address and the pt-pt destination address. Otherwise
7749 		 * we just match the local address.
7750 		 * NOTE: dst could be different than ipha->ipha_dst in case
7751 		 * of sending igmp multicast packets over a point-to-point
7752 		 * connection.
7753 		 * Thus we must be careful enough to check ipha_dst to be a
7754 		 * multicast address, otherwise it will take xmit_if path for
7755 		 * multicast packets resulting into kernel stack overflow by
7756 		 * repeated calls to ip_newroute_ipif from ire_send().
7757 		 */
7758 		if (CLASSD(ipha_dst) &&
7759 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
7760 			goto err_ret;
7761 		}
7762 
7763 		/*
7764 		 * We check if an IRE_OFFSUBNET for the addr that goes through
7765 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
7766 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
7767 		 * propagate its flags to the new ire.
7768 		 */
7769 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
7770 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
7771 			ip2dbg(("ip_newroute_ipif: "
7772 			    "ipif_lookup_multi_ire("
7773 			    "ipif %p, dst %08x) = fire %p\n",
7774 			    (void *)ipif, ntohl(dst), (void *)fire));
7775 		}
7776 
7777 		if (mctl_present && io->ipsec_out_attach_if) {
7778 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
7779 			    io->ipsec_out_ill_index, B_FALSE);
7780 
7781 			/* Failure case frees things for us. */
7782 			if (attach_ill == NULL) {
7783 				ipif_refrele(ipif);
7784 				if (fire != NULL)
7785 					ire_refrele(fire);
7786 				return;
7787 			}
7788 
7789 			/*
7790 			 * Check if we need an ire that will not be
7791 			 * looked up by anybody else i.e. HIDDEN.
7792 			 */
7793 			if (ill_is_probeonly(attach_ill)) {
7794 				ire_marks = IRE_MARK_HIDDEN;
7795 			}
7796 			/*
7797 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
7798 			 * case.
7799 			 */
7800 			dst_ill = ipif->ipif_ill;
7801 			/* attach_ill has been refheld by ip_grab_attach_ill */
7802 			ASSERT(dst_ill == attach_ill);
7803 		} else {
7804 			/*
7805 			 * If this is set by IP_XMIT_IF, then make sure that
7806 			 * ipif is pointing to the same ill as the IP_XMIT_IF
7807 			 * specified ill.
7808 			 */
7809 			ASSERT((connp == NULL) ||
7810 			    (connp->conn_xmit_if_ill == NULL) ||
7811 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
7812 			/*
7813 			 * If the interface belongs to an interface group,
7814 			 * make sure the next possible interface in the group
7815 			 * is used.  This encourages load spreading among
7816 			 * peers in an interface group.
7817 			 * Note: load spreading is disabled for RTF_MULTIRT
7818 			 * routes.
7819 			 */
7820 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
7821 			    (fire->ire_flags & RTF_MULTIRT)) {
7822 				/*
7823 				 * Don't perform outbound load spreading
7824 				 * in the case of an RTF_MULTIRT issued route,
7825 				 * we actually typically want to replicate
7826 				 * outgoing packets through particular
7827 				 * interfaces.
7828 				 */
7829 				dst_ill = ipif->ipif_ill;
7830 				ill_refhold(dst_ill);
7831 			} else {
7832 				dst_ill = ip_newroute_get_dst_ill(
7833 				    ipif->ipif_ill);
7834 			}
7835 			if (dst_ill == NULL) {
7836 				if (ip_debug > 2) {
7837 					pr_addr_dbg("ip_newroute_ipif: "
7838 					    "no dst ill for dst %s\n",
7839 					    AF_INET, &dst);
7840 				}
7841 				goto err_ret;
7842 			}
7843 		}
7844 
7845 		/*
7846 		 * Pick a source address preferring non-deprecated ones.
7847 		 * Unlike ip_newroute, we don't do any source address
7848 		 * selection here since for multicast it really does not help
7849 		 * in inbound load spreading as in the unicast case.
7850 		 */
7851 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
7852 		    (fire->ire_flags & RTF_SETSRC)) {
7853 			/*
7854 			 * As requested by flags, an IRE_OFFSUBNET was looked up
7855 			 * on that interface. This ire has RTF_SETSRC flag, so
7856 			 * the source address of the packet must be changed.
7857 			 * Check that the ipif matching the requested source
7858 			 * address still exists.
7859 			 */
7860 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
7861 			    zoneid, NULL, NULL, NULL, NULL);
7862 		}
7863 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
7864 		    (connp != NULL && ipif->ipif_zoneid != zoneid)) &&
7865 		    (src_ipif == NULL)) {
7866 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
7867 			if (src_ipif == NULL) {
7868 				if (ip_debug > 2) {
7869 					/* ip1dbg */
7870 					pr_addr_dbg("ip_newroute_ipif: "
7871 					    "no src for dst %s",
7872 					    AF_INET, &dst);
7873 				}
7874 				ip1dbg((" through interface %s\n",
7875 				    dst_ill->ill_name));
7876 				goto err_ret;
7877 			}
7878 			ipif_refrele(ipif);
7879 			ipif = src_ipif;
7880 			ipif_refhold(ipif);
7881 		}
7882 		if (src_ipif == NULL) {
7883 			src_ipif = ipif;
7884 			ipif_refhold(src_ipif);
7885 		}
7886 
7887 		/*
7888 		 * Assign a source address while we have the conn.
7889 		 * We can't have ip_wput_ire pick a source address when the
7890 		 * packet returns from arp since conn_unspec_src might be set
7891 		 * and we loose the conn when going through arp.
7892 		 */
7893 		if (ipha->ipha_src == INADDR_ANY &&
7894 		    (connp == NULL || !connp->conn_unspec_src)) {
7895 			ipha->ipha_src = src_ipif->ipif_src_addr;
7896 		}
7897 
7898 		/*
7899 		 * In case of IP_XMIT_IF, it is possible that the outgoing
7900 		 * interface does not have an interface ire.
7901 		 * Example: Thousands of mobileip PPP interfaces to mobile
7902 		 * nodes. We don't want to create interface ires because
7903 		 * packets from other mobile nodes must not take the route
7904 		 * via interface ires to the visiting mobile node without
7905 		 * going through the home agent, in absence of mobileip
7906 		 * route optimization.
7907 		 */
7908 		if (CLASSD(ipha_dst) && (connp == NULL ||
7909 		    connp->conn_xmit_if_ill == NULL)) {
7910 			/* ipif_to_ire returns an held ire */
7911 			ire = ipif_to_ire(ipif);
7912 			if (ire == NULL)
7913 				goto err_ret;
7914 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
7915 				goto err_ret;
7916 			/*
7917 			 * ihandle is needed when the ire is added to
7918 			 * cache table.
7919 			 */
7920 			save_ire = ire;
7921 			ihandle = save_ire->ire_ihandle;
7922 
7923 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
7924 			    "flags %04x\n",
7925 			    (void *)ire, (void *)ipif, flags));
7926 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
7927 			    (fire->ire_flags & RTF_MULTIRT)) {
7928 				/*
7929 				 * As requested by flags, an IRE_OFFSUBNET was
7930 				 * looked up on that interface. This ire has
7931 				 * RTF_MULTIRT flag, so the resolution loop will
7932 				 * be re-entered to resolve additional routes on
7933 				 * other interfaces. For that purpose, a copy of
7934 				 * the packet is performed at this point.
7935 				 */
7936 				fire->ire_last_used_time = lbolt;
7937 				copy_mp = copymsg(first_mp);
7938 				if (copy_mp) {
7939 					MULTIRT_DEBUG_TAG(copy_mp);
7940 				}
7941 			}
7942 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
7943 			    (fire->ire_flags & RTF_SETSRC)) {
7944 				/*
7945 				 * As requested by flags, an IRE_OFFSUBET was
7946 				 * looked up on that interface. This ire has
7947 				 * RTF_SETSRC flag, so the source address of the
7948 				 * packet must be changed.
7949 				 */
7950 				ipha->ipha_src = fire->ire_src_addr;
7951 			}
7952 		} else {
7953 			ASSERT((connp == NULL) ||
7954 			    (connp->conn_xmit_if_ill != NULL) ||
7955 			    (connp->conn_dontroute));
7956 			/*
7957 			 * The only ways we can come here are:
7958 			 * 1) IP_XMIT_IF socket option is set
7959 			 * 2) ICMP error message generated from
7960 			 *    ip_mrtun_forward() routine and it needs
7961 			 *    to go through the specified ill.
7962 			 * 3) SO_DONTROUTE socket option is set
7963 			 * In all cases, the new ire will not be added
7964 			 * into cache table.
7965 			 */
7966 			ire_marks |= IRE_MARK_NOADD;
7967 		}
7968 
7969 		switch (ipif->ipif_net_type) {
7970 		case IRE_IF_NORESOLVER: {
7971 			/* We have what we need to build an IRE_CACHE. */
7972 			mblk_t	*dlureq_mp;
7973 
7974 			/*
7975 			 * Create a new dlureq_mp with the
7976 			 * IP gateway address as destination address in the
7977 			 * DLPI hdr if the physical length is exactly 4 bytes.
7978 			 */
7979 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
7980 				dlureq_mp = ill_dlur_gen((uchar_t *)&dst,
7981 				    dst_ill->ill_phys_addr_length,
7982 				    dst_ill->ill_sap,
7983 				    dst_ill->ill_sap_length);
7984 			} else {
7985 				/* use the value set in ip_ll_subnet_defaults */
7986 				dlureq_mp = ill_dlur_gen(NULL,
7987 				    dst_ill->ill_phys_addr_length,
7988 				    dst_ill->ill_sap,
7989 				    dst_ill->ill_sap_length);
7990 			}
7991 
7992 			if (dlureq_mp == NULL)
7993 				break;
7994 			/*
7995 			 * The new ire inherits the IRE_OFFSUBNET flags
7996 			 * and source address, if this was requested.
7997 			 */
7998 			ire = ire_create(
7999 			    (uchar_t *)&dst,		/* dest address */
8000 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8001 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8002 			    NULL,			/* gateway address */
8003 			    NULL,
8004 			    &ipif->ipif_mtu,
8005 			    NULL,			/* Fast Path header */
8006 			    dst_ill->ill_rq,		/* recv-from queue */
8007 			    dst_ill->ill_wq,		/* send-to queue */
8008 			    IRE_CACHE,
8009 			    dlureq_mp,
8010 			    src_ipif,
8011 			    NULL,
8012 			    (save_ire != NULL ? save_ire->ire_mask : 0),
8013 			    (fire != NULL) ?		/* Parent handle */
8014 				fire->ire_phandle : 0,
8015 			    ihandle,			/* Interface handle */
8016 			    (fire != NULL) ?
8017 				(fire->ire_flags &
8018 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
8019 			    (save_ire == NULL ? &ire_uinfo_null :
8020 				&save_ire->ire_uinfo));
8021 
8022 			freeb(dlureq_mp);
8023 
8024 			if (ire == NULL) {
8025 				if (save_ire != NULL)
8026 					ire_refrele(save_ire);
8027 				break;
8028 			}
8029 
8030 			ire->ire_marks |= ire_marks;
8031 
8032 			/* Prevent save_ire from getting deleted */
8033 			if (save_ire != NULL) {
8034 				IRB_REFHOLD(save_ire->ire_bucket);
8035 				/* Has it been removed already ? */
8036 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8037 					IRB_REFRELE(save_ire->ire_bucket);
8038 					ire_refrele(save_ire);
8039 					break;
8040 				}
8041 			}
8042 
8043 			ire_add_then_send(q, ire, first_mp);
8044 
8045 			/* Assert that save_ire is not deleted yet. */
8046 			if (save_ire != NULL) {
8047 				ASSERT(save_ire->ire_ptpn != NULL);
8048 				IRB_REFRELE(save_ire->ire_bucket);
8049 				ire_refrele(save_ire);
8050 				save_ire = NULL;
8051 			}
8052 			if (fire != NULL) {
8053 				ire_refrele(fire);
8054 				fire = NULL;
8055 			}
8056 
8057 			/*
8058 			 * the resolution loop is re-entered if this
8059 			 * was requested through flags and if we
8060 			 * actually are in a multirouting case.
8061 			 */
8062 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
8063 				boolean_t need_resolve =
8064 				    ire_multirt_need_resolve(ipha_dst);
8065 				if (!need_resolve) {
8066 					MULTIRT_DEBUG_UNTAG(copy_mp);
8067 					freemsg(copy_mp);
8068 					copy_mp = NULL;
8069 				} else {
8070 					/*
8071 					 * ipif_lookup_group() calls
8072 					 * ire_lookup_multi() that uses
8073 					 * ire_ftable_lookup() to find
8074 					 * an IRE_INTERFACE for the group.
8075 					 * In the multirt case,
8076 					 * ire_lookup_multi() then invokes
8077 					 * ire_multirt_lookup() to find
8078 					 * the next resolvable ire.
8079 					 * As a result, we obtain an new
8080 					 * interface, derived from the
8081 					 * next ire.
8082 					 */
8083 					ipif_refrele(ipif);
8084 					ipif = ipif_lookup_group(ipha_dst,
8085 					    zoneid);
8086 					ip2dbg(("ip_newroute_ipif: "
8087 					    "multirt dst %08x, ipif %p\n",
8088 					    htonl(dst), (void *)ipif));
8089 					if (ipif != NULL) {
8090 						mp = copy_mp;
8091 						copy_mp = NULL;
8092 						multirt_resolve_next = B_TRUE;
8093 						continue;
8094 					} else {
8095 						freemsg(copy_mp);
8096 					}
8097 				}
8098 			}
8099 			if (ipif != NULL)
8100 				ipif_refrele(ipif);
8101 			ill_refrele(dst_ill);
8102 			ipif_refrele(src_ipif);
8103 			return;
8104 		}
8105 		case IRE_IF_RESOLVER:
8106 			/*
8107 			 * We can't build an IRE_CACHE yet, but at least
8108 			 * we found a resolver that can help.
8109 			 */
8110 			res_mp = dst_ill->ill_resolver_mp;
8111 			if (!OK_RESOLVER_MP(res_mp))
8112 				break;
8113 
8114 			/*
8115 			 * We obtain a partial IRE_CACHE which we will pass
8116 			 * along with the resolver query.  When the response
8117 			 * comes back it will be there ready for us to add.
8118 			 * The new ire inherits the IRE_OFFSUBNET flags
8119 			 * and source address, if this was requested.
8120 			 * The ire_max_frag is atomically set under the
8121 			 * irebucket lock in ire_add_v[46]. Only in the
8122 			 * case of IRE_MARK_NOADD, we set it here itself.
8123 			 */
8124 			ire = ire_create_mp(
8125 			    (uchar_t *)&dst,		/* dest address */
8126 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8127 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8128 			    NULL,			/* gateway address */
8129 			    NULL,			/* no in_src_addr */
8130 			    (ire_marks & IRE_MARK_NOADD) ?
8131 				ipif->ipif_mtu : 0,	/* max_frag */
8132 			    NULL,			/* Fast path header */
8133 			    dst_ill->ill_rq,		/* recv-from queue */
8134 			    dst_ill->ill_wq,		/* send-to queue */
8135 			    IRE_CACHE,
8136 			    res_mp,
8137 			    src_ipif,
8138 			    NULL,
8139 			    (save_ire != NULL ? save_ire->ire_mask : 0),
8140 			    (fire != NULL) ?		/* Parent handle */
8141 				fire->ire_phandle : 0,
8142 			    ihandle,			/* Interface handle */
8143 			    (fire != NULL) ?		/* flags if any */
8144 				(fire->ire_flags &
8145 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
8146 			    (save_ire == NULL ? &ire_uinfo_null :
8147 				&save_ire->ire_uinfo));
8148 
8149 			if (save_ire != NULL) {
8150 				ire_refrele(save_ire);
8151 				save_ire = NULL;
8152 			}
8153 			if (ire == NULL)
8154 				break;
8155 
8156 			ire->ire_marks |= ire_marks;
8157 			/*
8158 			 * Construct message chain for the resolver of the
8159 			 * form:
8160 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8161 			 *
8162 			 * NOTE : ire will be added later when the response
8163 			 * comes back from ARP. If the response does not
8164 			 * come back, ARP frees the packet. For this reason,
8165 			 * we can't REFHOLD the bucket of save_ire to prevent
8166 			 * deletions. We may not be able to REFRELE the
8167 			 * bucket if the response never comes back.
8168 			 * Thus, before adding the ire, ire_add_v4 will make
8169 			 * sure that the interface route does not get deleted.
8170 			 * This is the only case unlike ip_newroute_v6,
8171 			 * ip_newroute_ipif_v6 where we can always prevent
8172 			 * deletions because ire_add_then_send is called after
8173 			 * creating the IRE.
8174 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
8175 			 * does not add this IRE into the IRE CACHE.
8176 			 */
8177 			ASSERT(ire->ire_mp != NULL);
8178 			ire->ire_mp->b_cont = first_mp;
8179 			/* Have saved_mp handy, for cleanup if canput fails */
8180 			saved_mp = mp;
8181 			mp = ire->ire_dlureq_mp;
8182 			ASSERT(mp != NULL);
8183 			ire->ire_dlureq_mp = NULL;
8184 			linkb(mp, ire->ire_mp);
8185 
8186 			/*
8187 			 * Fill in the source and dest addrs for the resolver.
8188 			 * NOTE: this depends on memory layouts imposed by
8189 			 * ill_init().
8190 			 */
8191 			areq = (areq_t *)mp->b_rptr;
8192 			addrp = (ipaddr_t *)((char *)areq +
8193 			    areq->areq_sender_addr_offset);
8194 			*addrp = ire->ire_src_addr;
8195 			addrp = (ipaddr_t *)((char *)areq +
8196 			    areq->areq_target_addr_offset);
8197 			*addrp = dst;
8198 			/* Up to the resolver. */
8199 			if (canputnext(dst_ill->ill_rq)) {
8200 				putnext(dst_ill->ill_rq, mp);
8201 				/*
8202 				 * The response will come back in ip_wput
8203 				 * with db_type IRE_DB_TYPE.
8204 				 */
8205 			} else {
8206 				ire->ire_dlureq_mp = mp;
8207 				mp->b_cont = NULL;
8208 				ire_delete(ire);
8209 				saved_mp->b_next = NULL;
8210 				saved_mp->b_prev = NULL;
8211 				freemsg(first_mp);
8212 				ip2dbg(("ip_newroute_ipif: dropped\n"));
8213 			}
8214 
8215 			if (fire != NULL) {
8216 				ire_refrele(fire);
8217 				fire = NULL;
8218 			}
8219 
8220 
8221 			/*
8222 			 * The resolution loop is re-entered if this was
8223 			 * requested through flags and we actually are
8224 			 * in a multirouting case.
8225 			 */
8226 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
8227 				boolean_t need_resolve =
8228 				    ire_multirt_need_resolve(ipha_dst);
8229 				if (!need_resolve) {
8230 					MULTIRT_DEBUG_UNTAG(copy_mp);
8231 					freemsg(copy_mp);
8232 					copy_mp = NULL;
8233 				} else {
8234 					/*
8235 					 * ipif_lookup_group() calls
8236 					 * ire_lookup_multi() that uses
8237 					 * ire_ftable_lookup() to find
8238 					 * an IRE_INTERFACE for the group.
8239 					 * In the multirt case,
8240 					 * ire_lookup_multi() then invokes
8241 					 * ire_multirt_lookup() to find
8242 					 * the next resolvable ire.
8243 					 * As a result, we obtain an new
8244 					 * interface, derived from the
8245 					 * next ire.
8246 					 */
8247 					ipif_refrele(ipif);
8248 					ipif = ipif_lookup_group(ipha_dst,
8249 					    zoneid);
8250 					if (ipif != NULL) {
8251 						mp = copy_mp;
8252 						copy_mp = NULL;
8253 						multirt_resolve_next = B_TRUE;
8254 						continue;
8255 					} else {
8256 						freemsg(copy_mp);
8257 					}
8258 				}
8259 			}
8260 			if (ipif != NULL)
8261 				ipif_refrele(ipif);
8262 			ill_refrele(dst_ill);
8263 			ipif_refrele(src_ipif);
8264 			return;
8265 		default:
8266 			break;
8267 		}
8268 	} while (multirt_resolve_next);
8269 
8270 err_ret:
8271 	ip2dbg(("ip_newroute_ipif: dropped\n"));
8272 	if (fire != NULL)
8273 		ire_refrele(fire);
8274 	ipif_refrele(ipif);
8275 	/* Did this packet originate externally? */
8276 	if (dst_ill != NULL)
8277 		ill_refrele(dst_ill);
8278 	if (src_ipif != NULL)
8279 		ipif_refrele(src_ipif);
8280 	if (mp->b_prev || mp->b_next) {
8281 		mp->b_next = NULL;
8282 		mp->b_prev = NULL;
8283 	} else {
8284 		/*
8285 		 * Since ip_wput() isn't close to finished, we fill
8286 		 * in enough of the header for credible error reporting.
8287 		 */
8288 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
8289 			/* Failed */
8290 			freemsg(first_mp);
8291 			if (ire != NULL)
8292 				ire_refrele(ire);
8293 			return;
8294 		}
8295 	}
8296 	/*
8297 	 * At this point we will have ire only if RTF_BLACKHOLE
8298 	 * or RTF_REJECT flags are set on the IRE. It will not
8299 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8300 	 */
8301 	if (ire != NULL) {
8302 		if (ire->ire_flags & RTF_BLACKHOLE) {
8303 			ire_refrele(ire);
8304 			freemsg(first_mp);
8305 			return;
8306 		}
8307 		ire_refrele(ire);
8308 	}
8309 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE);
8310 }
8311 
8312 /* Name/Value Table Lookup Routine */
8313 char *
8314 ip_nv_lookup(nv_t *nv, int value)
8315 {
8316 	if (!nv)
8317 		return (NULL);
8318 	for (; nv->nv_name; nv++) {
8319 		if (nv->nv_value == value)
8320 			return (nv->nv_name);
8321 	}
8322 	return ("unknown");
8323 }
8324 
8325 /*
8326  * one day it can be patched to 1 from /etc/system for machines that have few
8327  * fast network interfaces feeding multiple cpus.
8328  */
8329 int ill_stream_putlocks = 0;
8330 
8331 /*
8332  * This is a module open, i.e. this is a control stream for access
8333  * to a DLPI device.  We allocate an ill_t as the instance data in
8334  * this case.
8335  */
8336 int
8337 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
8338 {
8339 	uint32_t mem_cnt;
8340 	uint32_t cpu_cnt;
8341 	uint32_t min_cnt;
8342 	pgcnt_t mem_avail;
8343 	extern uint32_t ip_cache_table_size, ip6_cache_table_size;
8344 	ill_t	*ill;
8345 	int	err;
8346 
8347 	/*
8348 	 * Prevent unprivileged processes from pushing IP so that
8349 	 * they can't send raw IP.
8350 	 */
8351 	if (secpolicy_net_rawaccess(credp) != 0)
8352 		return (EPERM);
8353 
8354 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
8355 	q->q_ptr = WR(q)->q_ptr = ill;
8356 
8357 	/*
8358 	 * ill_init initializes the ill fields and then sends down
8359 	 * down a DL_INFO_REQ after calling qprocson.
8360 	 */
8361 	err = ill_init(q, ill);
8362 	if (err != 0) {
8363 		mi_free(ill);
8364 		q->q_ptr = NULL;
8365 		WR(q)->q_ptr = NULL;
8366 		return (err);
8367 	}
8368 
8369 	/* ill_init initializes the ipsq marking this thread as writer */
8370 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
8371 	/* Wait for the DL_INFO_ACK */
8372 	mutex_enter(&ill->ill_lock);
8373 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
8374 		/*
8375 		 * Return value of 0 indicates a pending signal.
8376 		 */
8377 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
8378 		if (err == 0) {
8379 			mutex_exit(&ill->ill_lock);
8380 			(void) ip_close(q, 0);
8381 			return (EINTR);
8382 		}
8383 	}
8384 	mutex_exit(&ill->ill_lock);
8385 
8386 	/*
8387 	 * ip_rput_other could have set an error  in ill_error on
8388 	 * receipt of M_ERROR.
8389 	 */
8390 
8391 	err = ill->ill_error;
8392 	if (err != 0) {
8393 		(void) ip_close(q, 0);
8394 		return (err);
8395 	}
8396 
8397 	/*
8398 	 * ip_ire_max_bucket_cnt is sized below based on the memory
8399 	 * size and the cpu speed of the machine. This is upper
8400 	 * bounded by the compile time value of ip_ire_max_bucket_cnt
8401 	 * and is lower bounded by the compile time value of
8402 	 * ip_ire_min_bucket_cnt.  Similar logic applies to
8403 	 * ip6_ire_max_bucket_cnt.
8404 	 */
8405 	mem_avail = kmem_avail();
8406 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
8407 	    ip_cache_table_size / sizeof (ire_t);
8408 	cpu_cnt = CPU->cpu_type_info.pi_clock >> ip_ire_cpu_ratio;
8409 
8410 	min_cnt = MIN(cpu_cnt, mem_cnt);
8411 	if (min_cnt < ip_ire_min_bucket_cnt)
8412 		min_cnt = ip_ire_min_bucket_cnt;
8413 	if (ip_ire_max_bucket_cnt > min_cnt) {
8414 		ip_ire_max_bucket_cnt = min_cnt;
8415 	}
8416 
8417 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
8418 	    ip6_cache_table_size / sizeof (ire_t);
8419 	min_cnt = MIN(cpu_cnt, mem_cnt);
8420 	if (min_cnt < ip6_ire_min_bucket_cnt)
8421 		min_cnt = ip6_ire_min_bucket_cnt;
8422 	if (ip6_ire_max_bucket_cnt > min_cnt) {
8423 		ip6_ire_max_bucket_cnt = min_cnt;
8424 	}
8425 
8426 	ill->ill_credp = credp;
8427 	crhold(credp);
8428 
8429 	mutex_enter(&ip_mi_lock);
8430 	err = mi_open_link(&ip_g_head, (IDP)ill, devp, flag, sflag, credp);
8431 	mutex_exit(&ip_mi_lock);
8432 	if (err) {
8433 		(void) ip_close(q, 0);
8434 		return (err);
8435 	}
8436 	return (0);
8437 }
8438 
8439 /* IP open routine. */
8440 int
8441 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
8442 {
8443 	conn_t 		*connp;
8444 	major_t		maj;
8445 
8446 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
8447 
8448 	/* Allow reopen. */
8449 	if (q->q_ptr != NULL)
8450 		return (0);
8451 
8452 	if (sflag & MODOPEN) {
8453 		/* This is a module open */
8454 		return (ip_modopen(q, devp, flag, sflag, credp));
8455 	}
8456 
8457 
8458 	/*
8459 	 * We are opening as a device. This is an IP client stream, and we
8460 	 * allocate an conn_t as the instance data.
8461 	 */
8462 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP);
8463 	connp->conn_upq = q;
8464 	q->q_ptr = WR(q)->q_ptr = connp;
8465 
8466 	/* Minor tells us which /dev entry was opened */
8467 	if (geteminor(*devp) == IPV6_MINOR) {
8468 		connp->conn_flags |= IPCL_ISV6;
8469 		connp->conn_af_isv6 = B_TRUE;
8470 		ip_setqinfo(q, geteminor(*devp), B_FALSE);
8471 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
8472 	} else {
8473 		connp->conn_af_isv6 = B_FALSE;
8474 		connp->conn_pkt_isv6 = B_FALSE;
8475 	}
8476 
8477 
8478 	if ((connp->conn_dev =
8479 	    inet_minor_alloc(ip_minor_arena)) == 0) {
8480 		q->q_ptr = WR(q)->q_ptr = NULL;
8481 		CONN_DEC_REF(connp);
8482 		return (EBUSY);
8483 	}
8484 
8485 	maj = getemajor(*devp);
8486 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
8487 
8488 	/*
8489 	 * connp->conn_cred is crfree()ed in ip_close().
8490 	 */
8491 	connp->conn_cred = credp;
8492 	crhold(connp->conn_cred);
8493 
8494 	connp->conn_zoneid = getzoneid();
8495 
8496 	/*
8497 	 * This should only happen for ndd, netstat, raw socket or other SCTP
8498 	 * administrative ops.  In these cases, we just need a normal conn_t
8499 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
8500 	 * an error will be returned.
8501 	 */
8502 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
8503 		connp->conn_rq = q;
8504 		connp->conn_wq = WR(q);
8505 	} else {
8506 		connp->conn_ulp = IPPROTO_SCTP;
8507 		connp->conn_rq = connp->conn_wq = NULL;
8508 	}
8509 	/* Non-zero default values */
8510 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
8511 
8512 	/*
8513 	 * Make the conn globally visible to walkers
8514 	 */
8515 	mutex_enter(&connp->conn_lock);
8516 	connp->conn_state_flags &= ~CONN_INCIPIENT;
8517 	mutex_exit(&connp->conn_lock);
8518 	ASSERT(connp->conn_ref == 1);
8519 
8520 	qprocson(q);
8521 
8522 	return (0);
8523 }
8524 
8525 /*
8526  * Change q_qinfo based on the value of isv6.
8527  * This can not called on an ill queue.
8528  * Note that there is no race since either q_qinfo works for conn queues - it
8529  * is just an optimization to enter the best wput routine directly.
8530  */
8531 void
8532 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib)
8533 {
8534 	ASSERT(q->q_flag & QREADR);
8535 	ASSERT(WR(q)->q_next == NULL);
8536 	ASSERT(q->q_ptr != NULL);
8537 
8538 	if (minor == IPV6_MINOR)  {
8539 		if (bump_mib)
8540 			BUMP_MIB(&ip6_mib, ipv6OutSwitchIPv4);
8541 		q->q_qinfo = &rinit_ipv6;
8542 		WR(q)->q_qinfo = &winit_ipv6;
8543 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
8544 	} else {
8545 		if (bump_mib)
8546 			BUMP_MIB(&ip_mib, ipOutSwitchIPv6);
8547 		q->q_qinfo = &rinit;
8548 		WR(q)->q_qinfo = &winit;
8549 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
8550 	}
8551 
8552 }
8553 
8554 /*
8555  * See if IPsec needs loading because of the options in mp.
8556  */
8557 static boolean_t
8558 ipsec_opt_present(mblk_t *mp)
8559 {
8560 	uint8_t *optcp, *next_optcp, *opt_endcp;
8561 	struct opthdr *opt;
8562 	struct T_opthdr *topt;
8563 	int opthdr_len;
8564 	t_uscalar_t optname, optlevel;
8565 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
8566 	ipsec_req_t *ipsr;
8567 
8568 	/*
8569 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
8570 	 * return TRUE.
8571 	 */
8572 
8573 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
8574 	opt_endcp = optcp + tor->OPT_length;
8575 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
8576 		opthdr_len = sizeof (struct T_opthdr);
8577 	} else {		/* O_OPTMGMT_REQ */
8578 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
8579 		opthdr_len = sizeof (struct opthdr);
8580 	}
8581 	for (; optcp < opt_endcp; optcp = next_optcp) {
8582 		if (optcp + opthdr_len > opt_endcp)
8583 			return (B_FALSE);	/* Not enough option header. */
8584 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
8585 			topt = (struct T_opthdr *)optcp;
8586 			optlevel = topt->level;
8587 			optname = topt->name;
8588 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
8589 		} else {
8590 			opt = (struct opthdr *)optcp;
8591 			optlevel = opt->level;
8592 			optname = opt->name;
8593 			next_optcp = optcp + opthdr_len +
8594 			    _TPI_ALIGN_OPT(opt->len);
8595 		}
8596 		if ((next_optcp < optcp) || /* wraparound pointer space */
8597 		    ((next_optcp >= opt_endcp) && /* last option bad len */
8598 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
8599 			return (B_FALSE); /* bad option buffer */
8600 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
8601 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
8602 			/*
8603 			 * Check to see if it's an all-bypass or all-zeroes
8604 			 * IPsec request.  Don't bother loading IPsec if
8605 			 * the socket doesn't want to use it.  (A good example
8606 			 * is a bypass request.)
8607 			 *
8608 			 * Basically, if any of the non-NEVER bits are set,
8609 			 * load IPsec.
8610 			 */
8611 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
8612 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
8613 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
8614 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
8615 			    != 0)
8616 				return (B_TRUE);
8617 		}
8618 	}
8619 	return (B_FALSE);
8620 }
8621 
8622 /*
8623  * If conn is is waiting for ipsec to finish loading, kick it.
8624  */
8625 /* ARGSUSED */
8626 static void
8627 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
8628 {
8629 	t_scalar_t	optreq_prim;
8630 	mblk_t		*mp;
8631 	cred_t		*cr;
8632 	int		err = 0;
8633 
8634 	/*
8635 	 * This function is called, after ipsec loading is complete.
8636 	 * Since IP checks exclusively and atomically (i.e it prevents
8637 	 * ipsec load from completing until ip_optcom_req completes)
8638 	 * whether ipsec load is complete, there cannot be a race with IP
8639 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
8640 	 */
8641 	mutex_enter(&connp->conn_lock);
8642 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
8643 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
8644 		mp = connp->conn_ipsec_opt_mp;
8645 		connp->conn_ipsec_opt_mp = NULL;
8646 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
8647 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
8648 		mutex_exit(&connp->conn_lock);
8649 
8650 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
8651 
8652 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
8653 		if (optreq_prim == T_OPTMGMT_REQ) {
8654 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
8655 			    &ip_opt_obj);
8656 		} else {
8657 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
8658 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
8659 			    &ip_opt_obj);
8660 		}
8661 		if (err != EINPROGRESS)
8662 			CONN_OPER_PENDING_DONE(connp);
8663 		return;
8664 	}
8665 	mutex_exit(&connp->conn_lock);
8666 }
8667 
8668 /*
8669  * Called from the ipsec_loader thread, outside any perimeter, to tell
8670  * ip qenable any of the queues waiting for the ipsec loader to
8671  * complete.
8672  *
8673  * Use ip_mi_lock to be safe here: all modifications of the mi lists
8674  * are done with this lock held, so it's guaranteed that none of the
8675  * links will change along the way.
8676  */
8677 void
8678 ip_ipsec_load_complete()
8679 {
8680 	ipcl_walk(conn_restart_ipsec_waiter, NULL);
8681 }
8682 
8683 /*
8684  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
8685  * determines the grp on which it has to become exclusive, queues the mp
8686  * and sq draining restarts the optmgmt
8687  */
8688 static boolean_t
8689 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
8690 {
8691 	conn_t *connp;
8692 
8693 	/*
8694 	 * Take IPsec requests and treat them special.
8695 	 */
8696 	if (ipsec_opt_present(mp)) {
8697 		/* First check if IPsec is loaded. */
8698 		mutex_enter(&ipsec_loader_lock);
8699 		if (ipsec_loader_state != IPSEC_LOADER_WAIT) {
8700 			mutex_exit(&ipsec_loader_lock);
8701 			return (B_FALSE);
8702 		}
8703 		connp = Q_TO_CONN(q);
8704 		mutex_enter(&connp->conn_lock);
8705 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
8706 
8707 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
8708 		connp->conn_ipsec_opt_mp = mp;
8709 		mutex_exit(&connp->conn_lock);
8710 		mutex_exit(&ipsec_loader_lock);
8711 
8712 		ipsec_loader_loadnow();
8713 		return (B_TRUE);
8714 	}
8715 	return (B_FALSE);
8716 }
8717 
8718 /*
8719  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
8720  * all of them are copied to the conn_t. If the req is "zero", the policy is
8721  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
8722  * fields.
8723  * We keep only the latest setting of the policy and thus policy setting
8724  * is not incremental/cumulative.
8725  *
8726  * Requests to set policies with multiple alternative actions will
8727  * go through a different API.
8728  */
8729 int
8730 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
8731 {
8732 	uint_t ah_req = 0;
8733 	uint_t esp_req = 0;
8734 	uint_t se_req = 0;
8735 	ipsec_selkey_t sel;
8736 	ipsec_act_t *actp = NULL;
8737 	uint_t nact;
8738 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
8739 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
8740 	ipsec_policy_root_t *pr;
8741 	ipsec_policy_head_t *ph;
8742 	int fam;
8743 	boolean_t is_pol_reset;
8744 	int error = 0;
8745 
8746 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
8747 
8748 	/*
8749 	 * The IP_SEC_OPT option does not allow variable length parameters,
8750 	 * hence a request cannot be NULL.
8751 	 */
8752 	if (req == NULL)
8753 		return (EINVAL);
8754 
8755 	ah_req = req->ipsr_ah_req;
8756 	esp_req = req->ipsr_esp_req;
8757 	se_req = req->ipsr_self_encap_req;
8758 
8759 	/*
8760 	 * Are we dealing with a request to reset the policy (i.e.
8761 	 * zero requests).
8762 	 */
8763 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
8764 	    (esp_req & REQ_MASK) == 0 &&
8765 	    (se_req & REQ_MASK) == 0);
8766 
8767 	if (!is_pol_reset) {
8768 		/*
8769 		 * If we couldn't load IPsec, fail with "protocol
8770 		 * not supported".
8771 		 * IPsec may not have been loaded for a request with zero
8772 		 * policies, so we don't fail in this case.
8773 		 */
8774 		mutex_enter(&ipsec_loader_lock);
8775 		if (ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
8776 			mutex_exit(&ipsec_loader_lock);
8777 			return (EPROTONOSUPPORT);
8778 		}
8779 		mutex_exit(&ipsec_loader_lock);
8780 
8781 		/*
8782 		 * Test for valid requests. Invalid algorithms
8783 		 * need to be tested by IPSEC code because new
8784 		 * algorithms can be added dynamically.
8785 		 */
8786 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
8787 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
8788 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
8789 			return (EINVAL);
8790 		}
8791 
8792 		/*
8793 		 * Only privileged users can issue these
8794 		 * requests.
8795 		 */
8796 		if (((ah_req & IPSEC_PREF_NEVER) ||
8797 		    (esp_req & IPSEC_PREF_NEVER) ||
8798 		    (se_req & IPSEC_PREF_NEVER)) &&
8799 		    secpolicy_net_config(cr, B_FALSE) != 0) {
8800 			return (EPERM);
8801 		}
8802 
8803 		/*
8804 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
8805 		 * are mutually exclusive.
8806 		 */
8807 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
8808 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
8809 		    ((se_req & REQ_MASK) == REQ_MASK)) {
8810 			/* Both of them are set */
8811 			return (EINVAL);
8812 		}
8813 	}
8814 
8815 	mutex_enter(&connp->conn_lock);
8816 
8817 	/*
8818 	 * If we have already cached policies in ip_bind_connected*(), don't
8819 	 * let them change now. We cache policies for connections
8820 	 * whose src,dst [addr, port] is known.  The exception to this is
8821 	 * tunnels.  Tunnels are allowed to change policies after having
8822 	 * become fully bound.
8823 	 */
8824 	if (connp->conn_policy_cached && !IPCL_IS_IPTUN(connp)) {
8825 		mutex_exit(&connp->conn_lock);
8826 		return (EINVAL);
8827 	}
8828 
8829 	/*
8830 	 * We have a zero policies, reset the connection policy if already
8831 	 * set. This will cause the connection to inherit the
8832 	 * global policy, if any.
8833 	 */
8834 	if (is_pol_reset) {
8835 		if (connp->conn_policy != NULL) {
8836 			IPPH_REFRELE(connp->conn_policy);
8837 			connp->conn_policy = NULL;
8838 		}
8839 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
8840 		connp->conn_in_enforce_policy = B_FALSE;
8841 		connp->conn_out_enforce_policy = B_FALSE;
8842 		mutex_exit(&connp->conn_lock);
8843 		return (0);
8844 	}
8845 
8846 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy);
8847 	if (ph == NULL)
8848 		goto enomem;
8849 
8850 	ipsec_actvec_from_req(req, &actp, &nact);
8851 	if (actp == NULL)
8852 		goto enomem;
8853 
8854 	/*
8855 	 * Always allocate IPv4 policy entries, since they can also
8856 	 * apply to ipv6 sockets being used in ipv4-compat mode.
8857 	 */
8858 	bzero(&sel, sizeof (sel));
8859 	sel.ipsl_valid = IPSL_IPV4;
8860 
8861 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
8862 	if (pin4 == NULL)
8863 		goto enomem;
8864 
8865 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
8866 	if (pout4 == NULL)
8867 		goto enomem;
8868 
8869 	if (connp->conn_pkt_isv6) {
8870 		/*
8871 		 * We're looking at a v6 socket, also allocate the
8872 		 * v6-specific entries...
8873 		 */
8874 		sel.ipsl_valid = IPSL_IPV6;
8875 		pin6 = ipsec_policy_create(&sel, actp, nact,
8876 		    IPSEC_PRIO_SOCKET);
8877 		if (pin6 == NULL)
8878 			goto enomem;
8879 
8880 		pout6 = ipsec_policy_create(&sel, actp, nact,
8881 		    IPSEC_PRIO_SOCKET);
8882 		if (pout6 == NULL)
8883 			goto enomem;
8884 
8885 		/*
8886 		 * .. and file them away in the right place.
8887 		 */
8888 		fam = IPSEC_AF_V6;
8889 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
8890 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
8891 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
8892 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
8893 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
8894 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
8895 	}
8896 
8897 	ipsec_actvec_free(actp, nact);
8898 
8899 	/*
8900 	 * File the v4 policies.
8901 	 */
8902 	fam = IPSEC_AF_V4;
8903 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
8904 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
8905 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
8906 
8907 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
8908 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
8909 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
8910 
8911 	/*
8912 	 * If the requests need security, set enforce_policy.
8913 	 * If the requests are IPSEC_PREF_NEVER, one should
8914 	 * still set conn_out_enforce_policy so that an ipsec_out
8915 	 * gets attached in ip_wput. This is needed so that
8916 	 * for connections that we don't cache policy in ip_bind,
8917 	 * if global policy matches in ip_wput_attach_policy, we
8918 	 * don't wrongly inherit global policy. Similarly, we need
8919 	 * to set conn_in_enforce_policy also so that we don't verify
8920 	 * policy wrongly.
8921 	 */
8922 	if ((ah_req & REQ_MASK) != 0 ||
8923 	    (esp_req & REQ_MASK) != 0 ||
8924 	    (se_req & REQ_MASK) != 0) {
8925 		connp->conn_in_enforce_policy = B_TRUE;
8926 		connp->conn_out_enforce_policy = B_TRUE;
8927 		connp->conn_flags |= IPCL_CHECK_POLICY;
8928 	}
8929 
8930 	/*
8931 	 * Tunnels are allowed to set policy after having been fully bound.
8932 	 * If that's the case, cache policy here.
8933 	 */
8934 	if (IPCL_IS_IPTUN(connp) && connp->conn_fully_bound)
8935 		error = ipsec_conn_cache_policy(connp, !connp->conn_af_isv6);
8936 
8937 	mutex_exit(&connp->conn_lock);
8938 	return (error);
8939 #undef REQ_MASK
8940 
8941 	/*
8942 	 * Common memory-allocation-failure exit path.
8943 	 */
8944 enomem:
8945 	mutex_exit(&connp->conn_lock);
8946 	if (actp != NULL)
8947 		ipsec_actvec_free(actp, nact);
8948 	if (pin4 != NULL)
8949 		IPPOL_REFRELE(pin4);
8950 	if (pout4 != NULL)
8951 		IPPOL_REFRELE(pout4);
8952 	if (pin6 != NULL)
8953 		IPPOL_REFRELE(pin6);
8954 	if (pout6 != NULL)
8955 		IPPOL_REFRELE(pout6);
8956 	return (ENOMEM);
8957 }
8958 
8959 /*
8960  * Only for options that pass in an IP addr. Currently only V4 options
8961  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
8962  * So this function assumes level is IPPROTO_IP
8963  */
8964 int
8965 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
8966     mblk_t *first_mp)
8967 {
8968 	ipif_t *ipif = NULL;
8969 	int error;
8970 	ill_t *ill;
8971 
8972 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
8973 
8974 	if (addr != INADDR_ANY || checkonly) {
8975 		ASSERT(connp != NULL);
8976 		ipif = ipif_lookup_addr(addr, NULL, connp->conn_zoneid,
8977 		    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt, &error);
8978 		if (ipif == NULL) {
8979 			if (error == EINPROGRESS)
8980 				return (error);
8981 			else if (option == IP_MULTICAST_IF)
8982 				return (EHOSTUNREACH);
8983 			else
8984 				return (EINVAL);
8985 		} else if (checkonly) {
8986 			if (option == IP_MULTICAST_IF) {
8987 				ill = ipif->ipif_ill;
8988 				/* not supported by the virtual network iface */
8989 				if (IS_VNI(ill)) {
8990 					ipif_refrele(ipif);
8991 					return (EINVAL);
8992 				}
8993 			}
8994 			ipif_refrele(ipif);
8995 			return (0);
8996 		}
8997 		ill = ipif->ipif_ill;
8998 		mutex_enter(&connp->conn_lock);
8999 		mutex_enter(&ill->ill_lock);
9000 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
9001 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
9002 			mutex_exit(&ill->ill_lock);
9003 			mutex_exit(&connp->conn_lock);
9004 			ipif_refrele(ipif);
9005 			return (option == IP_MULTICAST_IF ?
9006 			    EHOSTUNREACH : EINVAL);
9007 		}
9008 	} else {
9009 		mutex_enter(&connp->conn_lock);
9010 	}
9011 
9012 	/* None of the options below are supported on the VNI */
9013 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
9014 		mutex_exit(&ill->ill_lock);
9015 		mutex_exit(&connp->conn_lock);
9016 		ipif_refrele(ipif);
9017 		return (EINVAL);
9018 	}
9019 
9020 	switch (option) {
9021 	case IP_DONTFAILOVER_IF:
9022 		/*
9023 		 * This option is used by in.mpathd to ensure
9024 		 * that IPMP probe packets only go out on the
9025 		 * test interfaces. in.mpathd sets this option
9026 		 * on the non-failover interfaces.
9027 		 * For backward compatibility, this option
9028 		 * implicitly sets IP_MULTICAST_IF, as used
9029 		 * be done in bind(), so that ip_wput gets
9030 		 * this ipif to send mcast packets.
9031 		 */
9032 		if (ipif != NULL) {
9033 			ASSERT(addr != INADDR_ANY);
9034 			connp->conn_nofailover_ill = ipif->ipif_ill;
9035 			connp->conn_multicast_ipif = ipif;
9036 		} else {
9037 			ASSERT(addr == INADDR_ANY);
9038 			connp->conn_nofailover_ill = NULL;
9039 			connp->conn_multicast_ipif = NULL;
9040 		}
9041 		break;
9042 
9043 	case IP_MULTICAST_IF:
9044 		connp->conn_multicast_ipif = ipif;
9045 		break;
9046 	}
9047 
9048 	if (ipif != NULL) {
9049 		mutex_exit(&ill->ill_lock);
9050 		mutex_exit(&connp->conn_lock);
9051 		ipif_refrele(ipif);
9052 		return (0);
9053 	}
9054 	mutex_exit(&connp->conn_lock);
9055 	/* We succeded in cleared the option */
9056 	return (0);
9057 }
9058 
9059 /*
9060  * For options that pass in an ifindex specifying the ill. V6 options always
9061  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
9062  */
9063 int
9064 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
9065     int level, int option, mblk_t *first_mp)
9066 {
9067 	ill_t *ill = NULL;
9068 	int error = 0;
9069 
9070 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
9071 	if (ifindex != 0) {
9072 		ASSERT(connp != NULL);
9073 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
9074 		    first_mp, ip_restart_optmgmt, &error);
9075 		if (ill != NULL) {
9076 			if (checkonly) {
9077 				/* not supported by the virtual network iface */
9078 				if (IS_VNI(ill)) {
9079 					ill_refrele(ill);
9080 					return (EINVAL);
9081 				}
9082 				ill_refrele(ill);
9083 				return (0);
9084 			}
9085 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
9086 			    0, NULL)) {
9087 				ill_refrele(ill);
9088 				ill = NULL;
9089 				mutex_enter(&connp->conn_lock);
9090 				goto setit;
9091 			}
9092 			mutex_enter(&connp->conn_lock);
9093 			mutex_enter(&ill->ill_lock);
9094 			if (ill->ill_state_flags & ILL_CONDEMNED) {
9095 				mutex_exit(&ill->ill_lock);
9096 				mutex_exit(&connp->conn_lock);
9097 				ill_refrele(ill);
9098 				ill = NULL;
9099 				mutex_enter(&connp->conn_lock);
9100 			}
9101 			goto setit;
9102 		} else if (error == EINPROGRESS) {
9103 			return (error);
9104 		} else {
9105 			error = 0;
9106 		}
9107 	}
9108 	mutex_enter(&connp->conn_lock);
9109 setit:
9110 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
9111 
9112 	/*
9113 	 * The options below assume that the ILL (if any) transmits and/or
9114 	 * receives traffic. Neither of which is true for the virtual network
9115 	 * interface, so fail setting these on a VNI.
9116 	 */
9117 	if (IS_VNI(ill)) {
9118 		ASSERT(ill != NULL);
9119 		mutex_exit(&ill->ill_lock);
9120 		mutex_exit(&connp->conn_lock);
9121 		ill_refrele(ill);
9122 		return (EINVAL);
9123 	}
9124 
9125 	if (level == IPPROTO_IP) {
9126 		switch (option) {
9127 		case IP_BOUND_IF:
9128 			connp->conn_incoming_ill = ill;
9129 			connp->conn_outgoing_ill = ill;
9130 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
9131 			    0 : ifindex;
9132 			break;
9133 
9134 		case IP_XMIT_IF:
9135 			/*
9136 			 * Similar to IP_BOUND_IF, but this only
9137 			 * determines the outgoing interface for
9138 			 * unicast packets. Also no IRE_CACHE entry
9139 			 * is added for the destination of the
9140 			 * outgoing packets. This feature is needed
9141 			 * for mobile IP.
9142 			 */
9143 			connp->conn_xmit_if_ill = ill;
9144 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
9145 			    0 : ifindex;
9146 			break;
9147 
9148 		case IP_MULTICAST_IF:
9149 			/*
9150 			 * This option is an internal special. The socket
9151 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
9152 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
9153 			 * specifies an ifindex and we try first on V6 ill's.
9154 			 * If we don't find one, we they try using on v4 ill's
9155 			 * intenally and we come here.
9156 			 */
9157 			if (!checkonly && ill != NULL) {
9158 				ipif_t	*ipif;
9159 				ipif = ill->ill_ipif;
9160 
9161 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
9162 					mutex_exit(&ill->ill_lock);
9163 					mutex_exit(&connp->conn_lock);
9164 					ill_refrele(ill);
9165 					ill = NULL;
9166 					mutex_enter(&connp->conn_lock);
9167 				} else {
9168 					connp->conn_multicast_ipif = ipif;
9169 				}
9170 			}
9171 			break;
9172 		}
9173 	} else {
9174 		switch (option) {
9175 		case IPV6_BOUND_IF:
9176 			connp->conn_incoming_ill = ill;
9177 			connp->conn_outgoing_ill = ill;
9178 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
9179 			    0 : ifindex;
9180 			break;
9181 
9182 		case IPV6_BOUND_PIF:
9183 			/*
9184 			 * Limit all transmit to this ill.
9185 			 * Unlike IPV6_BOUND_IF, using this option
9186 			 * prevents load spreading and failover from
9187 			 * happening when the interface is part of the
9188 			 * group. That's why we don't need to remember
9189 			 * the ifindex in orig_bound_ifindex as in
9190 			 * IPV6_BOUND_IF.
9191 			 */
9192 			connp->conn_outgoing_pill = ill;
9193 			break;
9194 
9195 		case IPV6_DONTFAILOVER_IF:
9196 			/*
9197 			 * This option is used by in.mpathd to ensure
9198 			 * that IPMP probe packets only go out on the
9199 			 * test interfaces. in.mpathd sets this option
9200 			 * on the non-failover interfaces.
9201 			 */
9202 			connp->conn_nofailover_ill = ill;
9203 			/*
9204 			 * For backward compatibility, this option
9205 			 * implicitly sets ip_multicast_ill as used in
9206 			 * IP_MULTICAST_IF so that ip_wput gets
9207 			 * this ipif to send mcast packets.
9208 			 */
9209 			connp->conn_multicast_ill = ill;
9210 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
9211 			    0 : ifindex;
9212 			break;
9213 
9214 		case IPV6_MULTICAST_IF:
9215 			/*
9216 			 * Set conn_multicast_ill to be the IPv6 ill.
9217 			 * Set conn_multicast_ipif to be an IPv4 ipif
9218 			 * for ifindex to make IPv4 mapped addresses
9219 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
9220 			 * Even if no IPv6 ill exists for the ifindex
9221 			 * we need to check for an IPv4 ifindex in order
9222 			 * for this to work with mapped addresses. In that
9223 			 * case only set conn_multicast_ipif.
9224 			 */
9225 			if (!checkonly) {
9226 				if (ifindex == 0) {
9227 					connp->conn_multicast_ill = NULL;
9228 					connp->conn_orig_multicast_ifindex = 0;
9229 					connp->conn_multicast_ipif = NULL;
9230 				} else if (ill != NULL) {
9231 					connp->conn_multicast_ill = ill;
9232 					connp->conn_orig_multicast_ifindex =
9233 					    ifindex;
9234 				}
9235 			}
9236 			break;
9237 		}
9238 	}
9239 
9240 	if (ill != NULL) {
9241 		mutex_exit(&ill->ill_lock);
9242 		mutex_exit(&connp->conn_lock);
9243 		ill_refrele(ill);
9244 		return (0);
9245 	}
9246 	mutex_exit(&connp->conn_lock);
9247 	/*
9248 	 * We succeeded in clearing the option (ifindex == 0) or failed to
9249 	 * locate the ill and could not set the option (ifindex != 0)
9250 	 */
9251 	return (ifindex == 0 ? 0 : EINVAL);
9252 }
9253 
9254 /* This routine sets socket options. */
9255 /* ARGSUSED */
9256 int
9257 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
9258     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9259     void *dummy, cred_t *cr, mblk_t *first_mp)
9260 {
9261 	int		*i1 = (int *)invalp;
9262 	conn_t		*connp = Q_TO_CONN(q);
9263 	int		error = 0;
9264 	boolean_t	checkonly;
9265 	ire_t		*ire;
9266 	boolean_t	found;
9267 
9268 	switch (optset_context) {
9269 
9270 	case SETFN_OPTCOM_CHECKONLY:
9271 		checkonly = B_TRUE;
9272 		/*
9273 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9274 		 * inlen != 0 implies value supplied and
9275 		 * 	we have to "pretend" to set it.
9276 		 * inlen == 0 implies that there is no
9277 		 * 	value part in T_CHECK request and just validation
9278 		 * done elsewhere should be enough, we just return here.
9279 		 */
9280 		if (inlen == 0) {
9281 			*outlenp = 0;
9282 			return (0);
9283 		}
9284 		break;
9285 	case SETFN_OPTCOM_NEGOTIATE:
9286 	case SETFN_UD_NEGOTIATE:
9287 	case SETFN_CONN_NEGOTIATE:
9288 		checkonly = B_FALSE;
9289 		break;
9290 	default:
9291 		/*
9292 		 * We should never get here
9293 		 */
9294 		*outlenp = 0;
9295 		return (EINVAL);
9296 	}
9297 
9298 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
9299 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
9300 
9301 	/*
9302 	 * For fixed length options, no sanity check
9303 	 * of passed in length is done. It is assumed *_optcom_req()
9304 	 * routines do the right thing.
9305 	 */
9306 
9307 	switch (level) {
9308 	case SOL_SOCKET:
9309 		/*
9310 		 * conn_lock protects the bitfields, and is used to
9311 		 * set the fields atomically.
9312 		 */
9313 		switch (name) {
9314 		case SO_BROADCAST:
9315 			if (!checkonly) {
9316 				/* TODO: use value someplace? */
9317 				mutex_enter(&connp->conn_lock);
9318 				connp->conn_broadcast = *i1 ? 1 : 0;
9319 				mutex_exit(&connp->conn_lock);
9320 			}
9321 			break;	/* goto sizeof (int) option return */
9322 		case SO_USELOOPBACK:
9323 			if (!checkonly) {
9324 				/* TODO: use value someplace? */
9325 				mutex_enter(&connp->conn_lock);
9326 				connp->conn_loopback = *i1 ? 1 : 0;
9327 				mutex_exit(&connp->conn_lock);
9328 			}
9329 			break;	/* goto sizeof (int) option return */
9330 		case SO_DONTROUTE:
9331 			if (!checkonly) {
9332 				mutex_enter(&connp->conn_lock);
9333 				connp->conn_dontroute = *i1 ? 1 : 0;
9334 				mutex_exit(&connp->conn_lock);
9335 			}
9336 			break;	/* goto sizeof (int) option return */
9337 		case SO_REUSEADDR:
9338 			if (!checkonly) {
9339 				mutex_enter(&connp->conn_lock);
9340 				connp->conn_reuseaddr = *i1 ? 1 : 0;
9341 				mutex_exit(&connp->conn_lock);
9342 			}
9343 			break;	/* goto sizeof (int) option return */
9344 		case SO_PROTOTYPE:
9345 			if (!checkonly) {
9346 				mutex_enter(&connp->conn_lock);
9347 				connp->conn_proto = *i1;
9348 				mutex_exit(&connp->conn_lock);
9349 			}
9350 			break;	/* goto sizeof (int) option return */
9351 		default:
9352 			/*
9353 			 * "soft" error (negative)
9354 			 * option not handled at this level
9355 			 * Note: Do not modify *outlenp
9356 			 */
9357 			return (-EINVAL);
9358 		}
9359 		break;
9360 	case IPPROTO_IP:
9361 		switch (name) {
9362 		case IP_MULTICAST_IF:
9363 		case IP_DONTFAILOVER_IF: {
9364 			ipaddr_t addr = *i1;
9365 
9366 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
9367 			    first_mp);
9368 			if (error != 0)
9369 				return (error);
9370 			break;	/* goto sizeof (int) option return */
9371 		}
9372 
9373 		case IP_MULTICAST_TTL:
9374 			/* Recorded in transport above IP */
9375 			*outvalp = *invalp;
9376 			*outlenp = sizeof (uchar_t);
9377 			return (0);
9378 		case IP_MULTICAST_LOOP:
9379 			if (!checkonly) {
9380 				mutex_enter(&connp->conn_lock);
9381 				connp->conn_multicast_loop = *invalp ? 1 : 0;
9382 				mutex_exit(&connp->conn_lock);
9383 			}
9384 			*outvalp = *invalp;
9385 			*outlenp = sizeof (uchar_t);
9386 			return (0);
9387 		case IP_ADD_MEMBERSHIP:
9388 		case MCAST_JOIN_GROUP:
9389 		case IP_DROP_MEMBERSHIP:
9390 		case MCAST_LEAVE_GROUP: {
9391 			struct ip_mreq *mreqp;
9392 			struct group_req *greqp;
9393 			ire_t *ire;
9394 			boolean_t done = B_FALSE;
9395 			ipaddr_t group, ifaddr;
9396 			struct sockaddr_in *sin;
9397 			uint32_t *ifindexp;
9398 			boolean_t mcast_opt = B_TRUE;
9399 			mcast_record_t fmode;
9400 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
9401 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
9402 
9403 			switch (name) {
9404 			case IP_ADD_MEMBERSHIP:
9405 				mcast_opt = B_FALSE;
9406 				/* FALLTHRU */
9407 			case MCAST_JOIN_GROUP:
9408 				fmode = MODE_IS_EXCLUDE;
9409 				optfn = ip_opt_add_group;
9410 				break;
9411 
9412 			case IP_DROP_MEMBERSHIP:
9413 				mcast_opt = B_FALSE;
9414 				/* FALLTHRU */
9415 			case MCAST_LEAVE_GROUP:
9416 				fmode = MODE_IS_INCLUDE;
9417 				optfn = ip_opt_delete_group;
9418 				break;
9419 			}
9420 
9421 			if (mcast_opt) {
9422 				greqp = (struct group_req *)i1;
9423 				sin = (struct sockaddr_in *)&greqp->gr_group;
9424 				if (sin->sin_family != AF_INET) {
9425 					*outlenp = 0;
9426 					return (ENOPROTOOPT);
9427 				}
9428 				group = (ipaddr_t)sin->sin_addr.s_addr;
9429 				ifaddr = INADDR_ANY;
9430 				ifindexp = &greqp->gr_interface;
9431 			} else {
9432 				mreqp = (struct ip_mreq *)i1;
9433 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
9434 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
9435 				ifindexp = NULL;
9436 			}
9437 
9438 			/*
9439 			 * In the multirouting case, we need to replicate
9440 			 * the request on all interfaces that will take part
9441 			 * in replication.  We do so because multirouting is
9442 			 * reflective, thus we will probably receive multi-
9443 			 * casts on those interfaces.
9444 			 * The ip_multirt_apply_membership() succeeds if the
9445 			 * operation succeeds on at least one interface.
9446 			 */
9447 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
9448 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
9449 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
9450 			if (ire != NULL) {
9451 				if (ire->ire_flags & RTF_MULTIRT) {
9452 					error = ip_multirt_apply_membership(
9453 					    optfn, ire, connp, checkonly, group,
9454 					    fmode, INADDR_ANY, first_mp);
9455 					done = B_TRUE;
9456 				}
9457 				ire_refrele(ire);
9458 			}
9459 			if (!done) {
9460 				error = optfn(connp, checkonly, group, ifaddr,
9461 				    ifindexp, fmode, INADDR_ANY, first_mp);
9462 			}
9463 			if (error) {
9464 				/*
9465 				 * EINPROGRESS is a soft error, needs retry
9466 				 * so don't make *outlenp zero.
9467 				 */
9468 				if (error != EINPROGRESS)
9469 					*outlenp = 0;
9470 				return (error);
9471 			}
9472 			/* OK return - copy input buffer into output buffer */
9473 			if (invalp != outvalp) {
9474 				/* don't trust bcopy for identical src/dst */
9475 				bcopy(invalp, outvalp, inlen);
9476 			}
9477 			*outlenp = inlen;
9478 			return (0);
9479 		}
9480 		case IP_BLOCK_SOURCE:
9481 		case IP_UNBLOCK_SOURCE:
9482 		case IP_ADD_SOURCE_MEMBERSHIP:
9483 		case IP_DROP_SOURCE_MEMBERSHIP:
9484 		case MCAST_BLOCK_SOURCE:
9485 		case MCAST_UNBLOCK_SOURCE:
9486 		case MCAST_JOIN_SOURCE_GROUP:
9487 		case MCAST_LEAVE_SOURCE_GROUP: {
9488 			struct ip_mreq_source *imreqp;
9489 			struct group_source_req *gsreqp;
9490 			in_addr_t grp, src, ifaddr = INADDR_ANY;
9491 			uint32_t ifindex = 0;
9492 			mcast_record_t fmode;
9493 			struct sockaddr_in *sin;
9494 			ire_t *ire;
9495 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
9496 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
9497 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
9498 
9499 			switch (name) {
9500 			case IP_BLOCK_SOURCE:
9501 				mcast_opt = B_FALSE;
9502 				/* FALLTHRU */
9503 			case MCAST_BLOCK_SOURCE:
9504 				fmode = MODE_IS_EXCLUDE;
9505 				optfn = ip_opt_add_group;
9506 				break;
9507 
9508 			case IP_UNBLOCK_SOURCE:
9509 				mcast_opt = B_FALSE;
9510 				/* FALLTHRU */
9511 			case MCAST_UNBLOCK_SOURCE:
9512 				fmode = MODE_IS_EXCLUDE;
9513 				optfn = ip_opt_delete_group;
9514 				break;
9515 
9516 			case IP_ADD_SOURCE_MEMBERSHIP:
9517 				mcast_opt = B_FALSE;
9518 				/* FALLTHRU */
9519 			case MCAST_JOIN_SOURCE_GROUP:
9520 				fmode = MODE_IS_INCLUDE;
9521 				optfn = ip_opt_add_group;
9522 				break;
9523 
9524 			case IP_DROP_SOURCE_MEMBERSHIP:
9525 				mcast_opt = B_FALSE;
9526 				/* FALLTHRU */
9527 			case MCAST_LEAVE_SOURCE_GROUP:
9528 				fmode = MODE_IS_INCLUDE;
9529 				optfn = ip_opt_delete_group;
9530 				break;
9531 			}
9532 
9533 			if (mcast_opt) {
9534 				gsreqp = (struct group_source_req *)i1;
9535 				if (gsreqp->gsr_group.ss_family != AF_INET) {
9536 					*outlenp = 0;
9537 					return (ENOPROTOOPT);
9538 				}
9539 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
9540 				grp = (ipaddr_t)sin->sin_addr.s_addr;
9541 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
9542 				src = (ipaddr_t)sin->sin_addr.s_addr;
9543 				ifindex = gsreqp->gsr_interface;
9544 			} else {
9545 				imreqp = (struct ip_mreq_source *)i1;
9546 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
9547 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
9548 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
9549 			}
9550 
9551 			/*
9552 			 * In the multirouting case, we need to replicate
9553 			 * the request as noted in the mcast cases above.
9554 			 */
9555 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
9556 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
9557 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
9558 			if (ire != NULL) {
9559 				if (ire->ire_flags & RTF_MULTIRT) {
9560 					error = ip_multirt_apply_membership(
9561 					    optfn, ire, connp, checkonly, grp,
9562 					    fmode, src, first_mp);
9563 					done = B_TRUE;
9564 				}
9565 				ire_refrele(ire);
9566 			}
9567 			if (!done) {
9568 				error = optfn(connp, checkonly, grp, ifaddr,
9569 				    &ifindex, fmode, src, first_mp);
9570 			}
9571 			if (error != 0) {
9572 				/*
9573 				 * EINPROGRESS is a soft error, needs retry
9574 				 * so don't make *outlenp zero.
9575 				 */
9576 				if (error != EINPROGRESS)
9577 					*outlenp = 0;
9578 				return (error);
9579 			}
9580 			/* OK return - copy input buffer into output buffer */
9581 			if (invalp != outvalp) {
9582 				bcopy(invalp, outvalp, inlen);
9583 			}
9584 			*outlenp = inlen;
9585 			return (0);
9586 		}
9587 		case IP_SEC_OPT:
9588 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
9589 			if (error != 0) {
9590 				*outlenp = 0;
9591 				return (error);
9592 			}
9593 			break;
9594 		case IP_HDRINCL:
9595 		case IP_OPTIONS:
9596 		case T_IP_OPTIONS:
9597 		case IP_TOS:
9598 		case T_IP_TOS:
9599 		case IP_TTL:
9600 		case IP_RECVDSTADDR:
9601 		case IP_RECVOPTS:
9602 			/* OK return - copy input buffer into output buffer */
9603 			if (invalp != outvalp) {
9604 				/* don't trust bcopy for identical src/dst */
9605 				bcopy(invalp, outvalp, inlen);
9606 			}
9607 			*outlenp = inlen;
9608 			return (0);
9609 		case IP_RECVIF:
9610 			/* Retrieve the inbound interface index */
9611 			if (!checkonly) {
9612 				mutex_enter(&connp->conn_lock);
9613 				connp->conn_recvif = *i1 ? 1 : 0;
9614 				mutex_exit(&connp->conn_lock);
9615 			}
9616 			break;	/* goto sizeof (int) option return */
9617 		case IP_RECVSLLA:
9618 			/* Retrieve the source link layer address */
9619 			if (!checkonly) {
9620 				mutex_enter(&connp->conn_lock);
9621 				connp->conn_recvslla = *i1 ? 1 : 0;
9622 				mutex_exit(&connp->conn_lock);
9623 			}
9624 			break;	/* goto sizeof (int) option return */
9625 		case MRT_INIT:
9626 		case MRT_DONE:
9627 		case MRT_ADD_VIF:
9628 		case MRT_DEL_VIF:
9629 		case MRT_ADD_MFC:
9630 		case MRT_DEL_MFC:
9631 		case MRT_ASSERT:
9632 			if ((error = secpolicy_net_config(cr, B_FALSE)) != 0) {
9633 				*outlenp = 0;
9634 				return (error);
9635 			}
9636 			error = ip_mrouter_set((int)name, q, checkonly,
9637 			    (uchar_t *)invalp, inlen, first_mp);
9638 			if (error) {
9639 				*outlenp = 0;
9640 				return (error);
9641 			}
9642 			/* OK return - copy input buffer into output buffer */
9643 			if (invalp != outvalp) {
9644 				/* don't trust bcopy for identical src/dst */
9645 				bcopy(invalp, outvalp, inlen);
9646 			}
9647 			*outlenp = inlen;
9648 			return (0);
9649 		case IP_BOUND_IF:
9650 		case IP_XMIT_IF:
9651 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
9652 			    level, name, first_mp);
9653 			if (error != 0)
9654 				return (error);
9655 			break; 		/* goto sizeof (int) option return */
9656 
9657 		case IP_UNSPEC_SRC:
9658 			/* Allow sending with a zero source address */
9659 			if (!checkonly) {
9660 				mutex_enter(&connp->conn_lock);
9661 				connp->conn_unspec_src = *i1 ? 1 : 0;
9662 				mutex_exit(&connp->conn_lock);
9663 			}
9664 			break;	/* goto sizeof (int) option return */
9665 		default:
9666 			/*
9667 			 * "soft" error (negative)
9668 			 * option not handled at this level
9669 			 * Note: Do not modify *outlenp
9670 			 */
9671 			return (-EINVAL);
9672 		}
9673 		break;
9674 	case IPPROTO_IPV6:
9675 		switch (name) {
9676 		case IPV6_BOUND_IF:
9677 		case IPV6_BOUND_PIF:
9678 		case IPV6_DONTFAILOVER_IF:
9679 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
9680 			    level, name, first_mp);
9681 			if (error != 0)
9682 				return (error);
9683 			break; 		/* goto sizeof (int) option return */
9684 
9685 		case IPV6_MULTICAST_IF:
9686 			/*
9687 			 * The only possible errors are EINPROGRESS and
9688 			 * EINVAL. EINPROGRESS will be restarted and is not
9689 			 * a hard error. We call this option on both V4 and V6
9690 			 * If both return EINVAL, then this call returns
9691 			 * EINVAL. If at least one of them succeeds we
9692 			 * return success.
9693 			 */
9694 			found = B_FALSE;
9695 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
9696 			    level, name, first_mp);
9697 			if (error == EINPROGRESS)
9698 				return (error);
9699 			if (error == 0)
9700 				found = B_TRUE;
9701 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
9702 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
9703 			if (error == 0)
9704 				found = B_TRUE;
9705 			if (!found)
9706 				return (error);
9707 			break; 		/* goto sizeof (int) option return */
9708 
9709 		case IPV6_MULTICAST_HOPS:
9710 			/* Recorded in transport above IP */
9711 			break;	/* goto sizeof (int) option return */
9712 		case IPV6_MULTICAST_LOOP:
9713 			if (!checkonly) {
9714 				mutex_enter(&connp->conn_lock);
9715 				connp->conn_multicast_loop = *i1;
9716 				mutex_exit(&connp->conn_lock);
9717 			}
9718 			break;	/* goto sizeof (int) option return */
9719 		case IPV6_JOIN_GROUP:
9720 		case MCAST_JOIN_GROUP:
9721 		case IPV6_LEAVE_GROUP:
9722 		case MCAST_LEAVE_GROUP: {
9723 			struct ipv6_mreq *ip_mreqp;
9724 			struct group_req *greqp;
9725 			ire_t *ire;
9726 			boolean_t done = B_FALSE;
9727 			in6_addr_t groupv6;
9728 			uint32_t ifindex;
9729 			boolean_t mcast_opt = B_TRUE;
9730 			mcast_record_t fmode;
9731 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
9732 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
9733 
9734 			switch (name) {
9735 			case IPV6_JOIN_GROUP:
9736 				mcast_opt = B_FALSE;
9737 				/* FALLTHRU */
9738 			case MCAST_JOIN_GROUP:
9739 				fmode = MODE_IS_EXCLUDE;
9740 				optfn = ip_opt_add_group_v6;
9741 				break;
9742 
9743 			case IPV6_LEAVE_GROUP:
9744 				mcast_opt = B_FALSE;
9745 				/* FALLTHRU */
9746 			case MCAST_LEAVE_GROUP:
9747 				fmode = MODE_IS_INCLUDE;
9748 				optfn = ip_opt_delete_group_v6;
9749 				break;
9750 			}
9751 
9752 			if (mcast_opt) {
9753 				struct sockaddr_in *sin;
9754 				struct sockaddr_in6 *sin6;
9755 				greqp = (struct group_req *)i1;
9756 				if (greqp->gr_group.ss_family == AF_INET) {
9757 					sin = (struct sockaddr_in *)
9758 					    &(greqp->gr_group);
9759 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
9760 					    &groupv6);
9761 				} else {
9762 					sin6 = (struct sockaddr_in6 *)
9763 					    &(greqp->gr_group);
9764 					groupv6 = sin6->sin6_addr;
9765 				}
9766 				ifindex = greqp->gr_interface;
9767 			} else {
9768 				ip_mreqp = (struct ipv6_mreq *)i1;
9769 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
9770 				ifindex = ip_mreqp->ipv6mr_interface;
9771 			}
9772 			/*
9773 			 * In the multirouting case, we need to replicate
9774 			 * the request on all interfaces that will take part
9775 			 * in replication.  We do so because multirouting is
9776 			 * reflective, thus we will probably receive multi-
9777 			 * casts on those interfaces.
9778 			 * The ip_multirt_apply_membership_v6() succeeds if
9779 			 * the operation succeeds on at least one interface.
9780 			 */
9781 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
9782 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
9783 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
9784 			if (ire != NULL) {
9785 				if (ire->ire_flags & RTF_MULTIRT) {
9786 					error = ip_multirt_apply_membership_v6(
9787 					    optfn, ire, connp, checkonly,
9788 					    &groupv6, fmode, &ipv6_all_zeros,
9789 					    first_mp);
9790 					done = B_TRUE;
9791 				}
9792 				ire_refrele(ire);
9793 			}
9794 			if (!done) {
9795 				error = optfn(connp, checkonly, &groupv6,
9796 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
9797 			}
9798 			if (error) {
9799 				/*
9800 				 * EINPROGRESS is a soft error, needs retry
9801 				 * so don't make *outlenp zero.
9802 				 */
9803 				if (error != EINPROGRESS)
9804 					*outlenp = 0;
9805 				return (error);
9806 			}
9807 			/* OK return - copy input buffer into output buffer */
9808 			if (invalp != outvalp) {
9809 				/* don't trust bcopy for identical src/dst */
9810 				bcopy(invalp, outvalp, inlen);
9811 			}
9812 			*outlenp = inlen;
9813 			return (0);
9814 		}
9815 		case MCAST_BLOCK_SOURCE:
9816 		case MCAST_UNBLOCK_SOURCE:
9817 		case MCAST_JOIN_SOURCE_GROUP:
9818 		case MCAST_LEAVE_SOURCE_GROUP: {
9819 			struct group_source_req *gsreqp;
9820 			in6_addr_t v6grp, v6src;
9821 			uint32_t ifindex;
9822 			mcast_record_t fmode;
9823 			ire_t *ire;
9824 			boolean_t done = B_FALSE;
9825 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
9826 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
9827 
9828 			switch (name) {
9829 			case MCAST_BLOCK_SOURCE:
9830 				fmode = MODE_IS_EXCLUDE;
9831 				optfn = ip_opt_add_group_v6;
9832 				break;
9833 			case MCAST_UNBLOCK_SOURCE:
9834 				fmode = MODE_IS_EXCLUDE;
9835 				optfn = ip_opt_delete_group_v6;
9836 				break;
9837 			case MCAST_JOIN_SOURCE_GROUP:
9838 				fmode = MODE_IS_INCLUDE;
9839 				optfn = ip_opt_add_group_v6;
9840 				break;
9841 			case MCAST_LEAVE_SOURCE_GROUP:
9842 				fmode = MODE_IS_INCLUDE;
9843 				optfn = ip_opt_delete_group_v6;
9844 				break;
9845 			}
9846 
9847 			gsreqp = (struct group_source_req *)i1;
9848 			ifindex = gsreqp->gsr_interface;
9849 			if (gsreqp->gsr_group.ss_family == AF_INET) {
9850 				struct sockaddr_in *s;
9851 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
9852 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
9853 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
9854 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
9855 			} else {
9856 				struct sockaddr_in6 *s6;
9857 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
9858 				v6grp = s6->sin6_addr;
9859 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
9860 				v6src = s6->sin6_addr;
9861 			}
9862 
9863 			/*
9864 			 * In the multirouting case, we need to replicate
9865 			 * the request as noted in the mcast cases above.
9866 			 */
9867 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
9868 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0,
9869 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
9870 			if (ire != NULL) {
9871 				if (ire->ire_flags & RTF_MULTIRT) {
9872 					error = ip_multirt_apply_membership_v6(
9873 					    optfn, ire, connp, checkonly,
9874 					    &v6grp, fmode, &v6src, first_mp);
9875 					done = B_TRUE;
9876 				}
9877 				ire_refrele(ire);
9878 			}
9879 			if (!done) {
9880 				error = optfn(connp, checkonly, &v6grp,
9881 				    ifindex, fmode, &v6src, first_mp);
9882 			}
9883 			if (error != 0) {
9884 				/*
9885 				 * EINPROGRESS is a soft error, needs retry
9886 				 * so don't make *outlenp zero.
9887 				 */
9888 				if (error != EINPROGRESS)
9889 					*outlenp = 0;
9890 				return (error);
9891 			}
9892 			/* OK return - copy input buffer into output buffer */
9893 			if (invalp != outvalp) {
9894 				bcopy(invalp, outvalp, inlen);
9895 			}
9896 			*outlenp = inlen;
9897 			return (0);
9898 		}
9899 		case IPV6_UNICAST_HOPS:
9900 			/* Recorded in transport above IP */
9901 			break;	/* goto sizeof (int) option return */
9902 		case IPV6_UNSPEC_SRC:
9903 			/* Allow sending with a zero source address */
9904 			if (!checkonly) {
9905 				mutex_enter(&connp->conn_lock);
9906 				connp->conn_unspec_src = *i1 ? 1 : 0;
9907 				mutex_exit(&connp->conn_lock);
9908 			}
9909 			break;	/* goto sizeof (int) option return */
9910 		case IPV6_RECVPKTINFO:
9911 			if (!checkonly) {
9912 				mutex_enter(&connp->conn_lock);
9913 				connp->conn_ipv6_recvpktinfo = *i1 ? 1 : 0;
9914 				mutex_exit(&connp->conn_lock);
9915 			}
9916 			break;	/* goto sizeof (int) option return */
9917 		case IPV6_RECVTCLASS:
9918 			if (!checkonly) {
9919 				if (*i1 < 0 || *i1 > 1) {
9920 					return (EINVAL);
9921 				}
9922 				mutex_enter(&connp->conn_lock);
9923 				connp->conn_ipv6_recvtclass = *i1;
9924 				mutex_exit(&connp->conn_lock);
9925 			}
9926 			break;
9927 		case IPV6_RECVPATHMTU:
9928 			if (!checkonly) {
9929 				if (*i1 < 0 || *i1 > 1) {
9930 					return (EINVAL);
9931 				}
9932 				mutex_enter(&connp->conn_lock);
9933 				connp->conn_ipv6_recvpathmtu = *i1;
9934 				mutex_exit(&connp->conn_lock);
9935 			}
9936 			break;
9937 		case IPV6_RECVHOPLIMIT:
9938 			if (!checkonly) {
9939 				mutex_enter(&connp->conn_lock);
9940 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
9941 				mutex_exit(&connp->conn_lock);
9942 			}
9943 			break;	/* goto sizeof (int) option return */
9944 		case IPV6_RECVHOPOPTS:
9945 			if (!checkonly) {
9946 				mutex_enter(&connp->conn_lock);
9947 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
9948 				mutex_exit(&connp->conn_lock);
9949 			}
9950 			break;	/* goto sizeof (int) option return */
9951 		case IPV6_RECVDSTOPTS:
9952 			if (!checkonly) {
9953 				mutex_enter(&connp->conn_lock);
9954 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
9955 				mutex_exit(&connp->conn_lock);
9956 			}
9957 			break;	/* goto sizeof (int) option return */
9958 		case IPV6_RECVRTHDR:
9959 			if (!checkonly) {
9960 				mutex_enter(&connp->conn_lock);
9961 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
9962 				mutex_exit(&connp->conn_lock);
9963 			}
9964 			break;	/* goto sizeof (int) option return */
9965 		case IPV6_RECVRTHDRDSTOPTS:
9966 			if (!checkonly) {
9967 				mutex_enter(&connp->conn_lock);
9968 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
9969 				mutex_exit(&connp->conn_lock);
9970 			}
9971 			break;	/* goto sizeof (int) option return */
9972 		case IPV6_PKTINFO:
9973 			if (inlen == 0)
9974 				return (-EINVAL);	/* clearing option */
9975 			error = ip6_set_pktinfo(cr, connp,
9976 			    (struct in6_pktinfo *)invalp, first_mp);
9977 			if (error != 0)
9978 				*outlenp = 0;
9979 			else
9980 				*outlenp = inlen;
9981 			return (error);
9982 		case IPV6_NEXTHOP: {
9983 			struct sockaddr_in6 *sin6;
9984 
9985 			/* Verify that the nexthop is reachable */
9986 			if (inlen == 0)
9987 				return (-EINVAL);	/* clearing option */
9988 
9989 			sin6 = (struct sockaddr_in6 *)invalp;
9990 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
9991 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
9992 			    MATCH_IRE_DEFAULT);
9993 
9994 			if (ire == NULL) {
9995 				*outlenp = 0;
9996 				return (EHOSTUNREACH);
9997 			}
9998 			ire_refrele(ire);
9999 			return (-EINVAL);
10000 		}
10001 		case IPV6_SEC_OPT:
10002 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10003 			if (error != 0) {
10004 				*outlenp = 0;
10005 				return (error);
10006 			}
10007 			break;
10008 		case IPV6_SRC_PREFERENCES: {
10009 			/*
10010 			 * This is implemented strictly in the ip module
10011 			 * (here and in tcp_opt_*() to accomodate tcp
10012 			 * sockets).  Modules above ip pass this option
10013 			 * down here since ip is the only one that needs to
10014 			 * be aware of source address preferences.
10015 			 *
10016 			 * This socket option only affects connected
10017 			 * sockets that haven't already bound to a specific
10018 			 * IPv6 address.  In other words, sockets that
10019 			 * don't call bind() with an address other than the
10020 			 * unspecified address and that call connect().
10021 			 * ip_bind_connected_v6() passes these preferences
10022 			 * to the ipif_select_source_v6() function.
10023 			 */
10024 			if (inlen != sizeof (uint32_t))
10025 				return (EINVAL);
10026 			error = ip6_set_src_preferences(connp,
10027 			    *(uint32_t *)invalp);
10028 			if (error != 0) {
10029 				*outlenp = 0;
10030 				return (error);
10031 			} else {
10032 				*outlenp = sizeof (uint32_t);
10033 			}
10034 			break;
10035 		}
10036 		case IPV6_V6ONLY:
10037 			if (*i1 < 0 || *i1 > 1) {
10038 				return (EINVAL);
10039 			}
10040 			mutex_enter(&connp->conn_lock);
10041 			connp->conn_ipv6_v6only = *i1;
10042 			mutex_exit(&connp->conn_lock);
10043 			break;
10044 		default:
10045 			return (-EINVAL);
10046 		}
10047 		break;
10048 	default:
10049 		/*
10050 		 * "soft" error (negative)
10051 		 * option not handled at this level
10052 		 * Note: Do not modify *outlenp
10053 		 */
10054 		return (-EINVAL);
10055 	}
10056 	/*
10057 	 * Common case of return from an option that is sizeof (int)
10058 	 */
10059 	*(int *)outvalp = *i1;
10060 	*outlenp = sizeof (int);
10061 	return (0);
10062 }
10063 
10064 /*
10065  * This routine gets default values of certain options whose default
10066  * values are maintained by protocol specific code
10067  */
10068 /* ARGSUSED */
10069 int
10070 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
10071 {
10072 	int *i1 = (int *)ptr;
10073 
10074 	switch (level) {
10075 	case IPPROTO_IP:
10076 		switch (name) {
10077 		case IP_MULTICAST_TTL:
10078 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
10079 			return (sizeof (uchar_t));
10080 		case IP_MULTICAST_LOOP:
10081 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
10082 			return (sizeof (uchar_t));
10083 		default:
10084 			return (-1);
10085 		}
10086 	case IPPROTO_IPV6:
10087 		switch (name) {
10088 		case IPV6_UNICAST_HOPS:
10089 			*i1 = ipv6_def_hops;
10090 			return (sizeof (int));
10091 		case IPV6_MULTICAST_HOPS:
10092 			*i1 = IP_DEFAULT_MULTICAST_TTL;
10093 			return (sizeof (int));
10094 		case IPV6_MULTICAST_LOOP:
10095 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
10096 			return (sizeof (int));
10097 		case IPV6_V6ONLY:
10098 			*i1 = 1;
10099 			return (sizeof (int));
10100 		default:
10101 			return (-1);
10102 		}
10103 	default:
10104 		return (-1);
10105 	}
10106 	/* NOTREACHED */
10107 }
10108 
10109 /*
10110  * Given a destination address and a pointer to where to put the information
10111  * this routine fills in the mtuinfo.
10112  */
10113 int
10114 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
10115     struct ip6_mtuinfo *mtuinfo)
10116 {
10117 	ire_t *ire;
10118 
10119 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
10120 		return (-1);
10121 
10122 	bzero(mtuinfo, sizeof (*mtuinfo));
10123 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
10124 	mtuinfo->ip6m_addr.sin6_port = port;
10125 	mtuinfo->ip6m_addr.sin6_addr = *in6;
10126 
10127 	ire = ire_cache_lookup_v6(in6, ALL_ZONES);
10128 	if (ire != NULL) {
10129 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
10130 		ire_refrele(ire);
10131 	} else {
10132 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
10133 	}
10134 	return (sizeof (struct ip6_mtuinfo));
10135 }
10136 
10137 /*
10138  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
10139  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
10140  * isn't.  This doesn't matter as the error checking is done properly for the
10141  * other MRT options coming in through ip_opt_set.
10142  */
10143 int
10144 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
10145 {
10146 	conn_t		*connp = Q_TO_CONN(q);
10147 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
10148 
10149 	switch (level) {
10150 	case IPPROTO_IP:
10151 		switch (name) {
10152 		case MRT_VERSION:
10153 		case MRT_ASSERT:
10154 			(void) ip_mrouter_get(name, q, ptr);
10155 			return (sizeof (int));
10156 		case IP_SEC_OPT:
10157 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
10158 		default:
10159 			break;
10160 		}
10161 		break;
10162 	case IPPROTO_IPV6:
10163 		switch (name) {
10164 		case IPV6_SEC_OPT:
10165 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
10166 		case IPV6_SRC_PREFERENCES: {
10167 			return (ip6_get_src_preferences(connp,
10168 			    (uint32_t *)ptr));
10169 		}
10170 		case IPV6_V6ONLY:
10171 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
10172 			return (sizeof (int));
10173 		case IPV6_PATHMTU:
10174 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
10175 				(struct ip6_mtuinfo *)ptr));
10176 		default:
10177 			break;
10178 		}
10179 		break;
10180 	default:
10181 		break;
10182 	}
10183 	return (-1);
10184 }
10185 
10186 /* Named Dispatch routine to get a current value out of our parameter table. */
10187 /* ARGSUSED */
10188 static int
10189 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
10190 {
10191 	ipparam_t *ippa = (ipparam_t *)cp;
10192 
10193 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
10194 	return (0);
10195 }
10196 
10197 /* ARGSUSED */
10198 static int
10199 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
10200 {
10201 
10202 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
10203 	return (0);
10204 }
10205 
10206 /*
10207  * Set ip{,6}_forwarding values.  This means walking through all of the
10208  * ill's and toggling their forwarding values.
10209  */
10210 /* ARGSUSED */
10211 static int
10212 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
10213 {
10214 	long new_value;
10215 	int *forwarding_value = (int *)cp;
10216 	ill_t *walker;
10217 	boolean_t isv6 = (forwarding_value == &ipv6_forward);
10218 	ill_walk_context_t ctx;
10219 
10220 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10221 	    new_value < 0 || new_value > 1) {
10222 		return (EINVAL);
10223 	}
10224 
10225 	*forwarding_value = new_value;
10226 
10227 	/*
10228 	 * Regardless of the current value of ip_forwarding, set all per-ill
10229 	 * values of ip_forwarding to the value being set.
10230 	 *
10231 	 * Bring all the ill's up to date with the new global value.
10232 	 */
10233 	rw_enter(&ill_g_lock, RW_READER);
10234 
10235 	if (isv6)
10236 		walker = ILL_START_WALK_V6(&ctx);
10237 	else
10238 		walker = ILL_START_WALK_V4(&ctx);
10239 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
10240 		(void) ill_forward_set(q, mp, (new_value != 0),
10241 		    (caddr_t)walker);
10242 	}
10243 	rw_exit(&ill_g_lock);
10244 
10245 	return (0);
10246 }
10247 
10248 /*
10249  * Walk through the param array specified registering each element with the
10250  * Named Dispatch handler. This is called only during init. So it is ok
10251  * not to acquire any locks
10252  */
10253 static boolean_t
10254 ip_param_register(ipparam_t *ippa, size_t ippa_cnt,
10255     ipndp_t *ipnd, size_t ipnd_cnt)
10256 {
10257 	for (; ippa_cnt-- > 0; ippa++) {
10258 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
10259 			if (!nd_load(&ip_g_nd, ippa->ip_param_name,
10260 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
10261 				nd_free(&ip_g_nd);
10262 				return (B_FALSE);
10263 			}
10264 		}
10265 	}
10266 
10267 	for (; ipnd_cnt-- > 0; ipnd++) {
10268 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
10269 			if (!nd_load(&ip_g_nd, ipnd->ip_ndp_name,
10270 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
10271 			    ipnd->ip_ndp_data)) {
10272 				nd_free(&ip_g_nd);
10273 				return (B_FALSE);
10274 			}
10275 		}
10276 	}
10277 
10278 	return (B_TRUE);
10279 }
10280 
10281 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
10282 /* ARGSUSED */
10283 static int
10284 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
10285 {
10286 	long		new_value;
10287 	ipparam_t	*ippa = (ipparam_t *)cp;
10288 
10289 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10290 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
10291 		return (EINVAL);
10292 	}
10293 	ippa->ip_param_value = new_value;
10294 	return (0);
10295 }
10296 
10297 /*
10298  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
10299  * When an ipf is passed here for the first time, if
10300  * we already have in-order fragments on the queue, we convert from the fast-
10301  * path reassembly scheme to the hard-case scheme.  From then on, additional
10302  * fragments are reassembled here.  We keep track of the start and end offsets
10303  * of each piece, and the number of holes in the chain.  When the hole count
10304  * goes to zero, we are done!
10305  *
10306  * The ipf_count will be updated to account for any mblk(s) added (pointed to
10307  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
10308  * ipfb_count and ill_frag_count by the difference of ipf_count before and
10309  * after the call to ip_reassemble().
10310  */
10311 int
10312 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
10313     size_t msg_len)
10314 {
10315 	uint_t	end;
10316 	mblk_t	*next_mp;
10317 	mblk_t	*mp1;
10318 	uint_t	offset;
10319 	boolean_t incr_dups = B_TRUE;
10320 	boolean_t offset_zero_seen = B_FALSE;
10321 	boolean_t pkt_boundary_checked = B_FALSE;
10322 
10323 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
10324 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
10325 
10326 	/* Add in byte count */
10327 	ipf->ipf_count += msg_len;
10328 	if (ipf->ipf_end) {
10329 		/*
10330 		 * We were part way through in-order reassembly, but now there
10331 		 * is a hole.  We walk through messages already queued, and
10332 		 * mark them for hard case reassembly.  We know that up till
10333 		 * now they were in order starting from offset zero.
10334 		 */
10335 		offset = 0;
10336 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
10337 			IP_REASS_SET_START(mp1, offset);
10338 			if (offset == 0) {
10339 				ASSERT(ipf->ipf_nf_hdr_len != 0);
10340 				offset = -ipf->ipf_nf_hdr_len;
10341 			}
10342 			offset += mp1->b_wptr - mp1->b_rptr;
10343 			IP_REASS_SET_END(mp1, offset);
10344 		}
10345 		/* One hole at the end. */
10346 		ipf->ipf_hole_cnt = 1;
10347 		/* Brand it as a hard case, forever. */
10348 		ipf->ipf_end = 0;
10349 	}
10350 	/* Walk through all the new pieces. */
10351 	do {
10352 		end = start + (mp->b_wptr - mp->b_rptr);
10353 		/*
10354 		 * If start is 0, decrease 'end' only for the first mblk of
10355 		 * the fragment. Otherwise 'end' can get wrong value in the
10356 		 * second pass of the loop if first mblk is exactly the
10357 		 * size of ipf_nf_hdr_len.
10358 		 */
10359 		if (start == 0 && !offset_zero_seen) {
10360 			/* First segment */
10361 			ASSERT(ipf->ipf_nf_hdr_len != 0);
10362 			end -= ipf->ipf_nf_hdr_len;
10363 			offset_zero_seen = B_TRUE;
10364 		}
10365 		next_mp = mp->b_cont;
10366 		/*
10367 		 * We are checking to see if there is any interesing data
10368 		 * to process.  If there isn't and the mblk isn't the
10369 		 * one which carries the unfragmentable header then we
10370 		 * drop it.  It's possible to have just the unfragmentable
10371 		 * header come through without any data.  That needs to be
10372 		 * saved.
10373 		 *
10374 		 * If the assert at the top of this function holds then the
10375 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
10376 		 * is infrequently traveled enough that the test is left in
10377 		 * to protect against future code changes which break that
10378 		 * invariant.
10379 		 */
10380 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
10381 			/* Empty.  Blast it. */
10382 			IP_REASS_SET_START(mp, 0);
10383 			IP_REASS_SET_END(mp, 0);
10384 			/*
10385 			 * If the ipf points to the mblk we are about to free,
10386 			 * update ipf to point to the next mblk (or NULL
10387 			 * if none).
10388 			 */
10389 			if (ipf->ipf_mp->b_cont == mp)
10390 				ipf->ipf_mp->b_cont = next_mp;
10391 			freeb(mp);
10392 			continue;
10393 		}
10394 		mp->b_cont = NULL;
10395 		IP_REASS_SET_START(mp, start);
10396 		IP_REASS_SET_END(mp, end);
10397 		if (!ipf->ipf_tail_mp) {
10398 			ipf->ipf_tail_mp = mp;
10399 			ipf->ipf_mp->b_cont = mp;
10400 			if (start == 0 || !more) {
10401 				ipf->ipf_hole_cnt = 1;
10402 				/*
10403 				 * if the first fragment comes in more than one
10404 				 * mblk, this loop will be executed for each
10405 				 * mblk. Need to adjust hole count so exiting
10406 				 * this routine will leave hole count at 1.
10407 				 */
10408 				if (next_mp)
10409 					ipf->ipf_hole_cnt++;
10410 			} else
10411 				ipf->ipf_hole_cnt = 2;
10412 			continue;
10413 		} else if (ipf->ipf_last_frag_seen && !more &&
10414 			    !pkt_boundary_checked) {
10415 			/*
10416 			 * We check datagram boundary only if this fragment
10417 			 * claims to be the last fragment and we have seen a
10418 			 * last fragment in the past too. We do this only
10419 			 * once for a given fragment.
10420 			 *
10421 			 * start cannot be 0 here as fragments with start=0
10422 			 * and MF=0 gets handled as a complete packet. These
10423 			 * fragments should not reach here.
10424 			 */
10425 
10426 			if (start + msgdsize(mp) !=
10427 			    IP_REASS_END(ipf->ipf_tail_mp)) {
10428 				/*
10429 				 * We have two fragments both of which claim
10430 				 * to be the last fragment but gives conflicting
10431 				 * information about the whole datagram size.
10432 				 * Something fishy is going on. Drop the
10433 				 * fragment and free up the reassembly list.
10434 				 */
10435 				return (IP_REASS_FAILED);
10436 			}
10437 
10438 			/*
10439 			 * We shouldn't come to this code block again for this
10440 			 * particular fragment.
10441 			 */
10442 			pkt_boundary_checked = B_TRUE;
10443 		}
10444 
10445 		/* New stuff at or beyond tail? */
10446 		offset = IP_REASS_END(ipf->ipf_tail_mp);
10447 		if (start >= offset) {
10448 			if (ipf->ipf_last_frag_seen) {
10449 				/* current fragment is beyond last fragment */
10450 				return (IP_REASS_FAILED);
10451 			}
10452 			/* Link it on end. */
10453 			ipf->ipf_tail_mp->b_cont = mp;
10454 			ipf->ipf_tail_mp = mp;
10455 			if (more) {
10456 				if (start != offset)
10457 					ipf->ipf_hole_cnt++;
10458 			} else if (start == offset && next_mp == NULL)
10459 					ipf->ipf_hole_cnt--;
10460 			continue;
10461 		}
10462 		mp1 = ipf->ipf_mp->b_cont;
10463 		offset = IP_REASS_START(mp1);
10464 		/* New stuff at the front? */
10465 		if (start < offset) {
10466 			if (start == 0) {
10467 				if (end >= offset) {
10468 					/* Nailed the hole at the begining. */
10469 					ipf->ipf_hole_cnt--;
10470 				}
10471 			} else if (end < offset) {
10472 				/*
10473 				 * A hole, stuff, and a hole where there used
10474 				 * to be just a hole.
10475 				 */
10476 				ipf->ipf_hole_cnt++;
10477 			}
10478 			mp->b_cont = mp1;
10479 			/* Check for overlap. */
10480 			while (end > offset) {
10481 				if (end < IP_REASS_END(mp1)) {
10482 					mp->b_wptr -= end - offset;
10483 					IP_REASS_SET_END(mp, offset);
10484 					if (ill->ill_isv6) {
10485 						BUMP_MIB(ill->ill_ip6_mib,
10486 						    ipv6ReasmPartDups);
10487 					} else {
10488 						BUMP_MIB(&ip_mib,
10489 						    ipReasmPartDups);
10490 					}
10491 					break;
10492 				}
10493 				/* Did we cover another hole? */
10494 				if ((mp1->b_cont &&
10495 				    IP_REASS_END(mp1) !=
10496 				    IP_REASS_START(mp1->b_cont) &&
10497 				    end >= IP_REASS_START(mp1->b_cont)) ||
10498 				    (!ipf->ipf_last_frag_seen && !more)) {
10499 					ipf->ipf_hole_cnt--;
10500 				}
10501 				/* Clip out mp1. */
10502 				if ((mp->b_cont = mp1->b_cont) == NULL) {
10503 					/*
10504 					 * After clipping out mp1, this guy
10505 					 * is now hanging off the end.
10506 					 */
10507 					ipf->ipf_tail_mp = mp;
10508 				}
10509 				IP_REASS_SET_START(mp1, 0);
10510 				IP_REASS_SET_END(mp1, 0);
10511 				/* Subtract byte count */
10512 				ipf->ipf_count -= mp1->b_datap->db_lim -
10513 				    mp1->b_datap->db_base;
10514 				freeb(mp1);
10515 				if (ill->ill_isv6) {
10516 					BUMP_MIB(ill->ill_ip6_mib,
10517 					    ipv6ReasmPartDups);
10518 				} else {
10519 					BUMP_MIB(&ip_mib, ipReasmPartDups);
10520 				}
10521 				mp1 = mp->b_cont;
10522 				if (!mp1)
10523 					break;
10524 				offset = IP_REASS_START(mp1);
10525 			}
10526 			ipf->ipf_mp->b_cont = mp;
10527 			continue;
10528 		}
10529 		/*
10530 		 * The new piece starts somewhere between the start of the head
10531 		 * and before the end of the tail.
10532 		 */
10533 		for (; mp1; mp1 = mp1->b_cont) {
10534 			offset = IP_REASS_END(mp1);
10535 			if (start < offset) {
10536 				if (end <= offset) {
10537 					/* Nothing new. */
10538 					IP_REASS_SET_START(mp, 0);
10539 					IP_REASS_SET_END(mp, 0);
10540 					/* Subtract byte count */
10541 					ipf->ipf_count -= mp->b_datap->db_lim -
10542 					    mp->b_datap->db_base;
10543 					if (incr_dups) {
10544 						ipf->ipf_num_dups++;
10545 						incr_dups = B_FALSE;
10546 					}
10547 					freeb(mp);
10548 					if (ill->ill_isv6) {
10549 						BUMP_MIB(ill->ill_ip6_mib,
10550 						    ipv6ReasmDuplicates);
10551 					} else {
10552 						BUMP_MIB(&ip_mib,
10553 						    ipReasmDuplicates);
10554 					}
10555 					break;
10556 				}
10557 				/*
10558 				 * Trim redundant stuff off beginning of new
10559 				 * piece.
10560 				 */
10561 				IP_REASS_SET_START(mp, offset);
10562 				mp->b_rptr += offset - start;
10563 				if (ill->ill_isv6) {
10564 					BUMP_MIB(ill->ill_ip6_mib,
10565 					    ipv6ReasmPartDups);
10566 				} else {
10567 					BUMP_MIB(&ip_mib, ipReasmPartDups);
10568 				}
10569 				start = offset;
10570 				if (!mp1->b_cont) {
10571 					/*
10572 					 * After trimming, this guy is now
10573 					 * hanging off the end.
10574 					 */
10575 					mp1->b_cont = mp;
10576 					ipf->ipf_tail_mp = mp;
10577 					if (!more) {
10578 						ipf->ipf_hole_cnt--;
10579 					}
10580 					break;
10581 				}
10582 			}
10583 			if (start >= IP_REASS_START(mp1->b_cont))
10584 				continue;
10585 			/* Fill a hole */
10586 			if (start > offset)
10587 				ipf->ipf_hole_cnt++;
10588 			mp->b_cont = mp1->b_cont;
10589 			mp1->b_cont = mp;
10590 			mp1 = mp->b_cont;
10591 			offset = IP_REASS_START(mp1);
10592 			if (end >= offset) {
10593 				ipf->ipf_hole_cnt--;
10594 				/* Check for overlap. */
10595 				while (end > offset) {
10596 					if (end < IP_REASS_END(mp1)) {
10597 						mp->b_wptr -= end - offset;
10598 						IP_REASS_SET_END(mp, offset);
10599 						/*
10600 						 * TODO we might bump
10601 						 * this up twice if there is
10602 						 * overlap at both ends.
10603 						 */
10604 						if (ill->ill_isv6) {
10605 							BUMP_MIB(
10606 							    ill->ill_ip6_mib,
10607 							    ipv6ReasmPartDups);
10608 						} else {
10609 							BUMP_MIB(&ip_mib,
10610 							    ipReasmPartDups);
10611 						}
10612 						break;
10613 					}
10614 					/* Did we cover another hole? */
10615 					if ((mp1->b_cont &&
10616 					    IP_REASS_END(mp1)
10617 					    != IP_REASS_START(mp1->b_cont) &&
10618 					    end >=
10619 					    IP_REASS_START(mp1->b_cont)) ||
10620 					    (!ipf->ipf_last_frag_seen &&
10621 					    !more)) {
10622 						ipf->ipf_hole_cnt--;
10623 					}
10624 					/* Clip out mp1. */
10625 					if ((mp->b_cont = mp1->b_cont) ==
10626 					    NULL) {
10627 						/*
10628 						 * After clipping out mp1,
10629 						 * this guy is now hanging
10630 						 * off the end.
10631 						 */
10632 						ipf->ipf_tail_mp = mp;
10633 					}
10634 					IP_REASS_SET_START(mp1, 0);
10635 					IP_REASS_SET_END(mp1, 0);
10636 					/* Subtract byte count */
10637 					ipf->ipf_count -=
10638 					    mp1->b_datap->db_lim -
10639 					    mp1->b_datap->db_base;
10640 					freeb(mp1);
10641 					if (ill->ill_isv6) {
10642 						BUMP_MIB(ill->ill_ip6_mib,
10643 						    ipv6ReasmPartDups);
10644 					} else {
10645 						BUMP_MIB(&ip_mib,
10646 						    ipReasmPartDups);
10647 					}
10648 					mp1 = mp->b_cont;
10649 					if (!mp1)
10650 						break;
10651 					offset = IP_REASS_START(mp1);
10652 				}
10653 			}
10654 			break;
10655 		}
10656 	} while (start = end, mp = next_mp);
10657 
10658 	/* Fragment just processed could be the last one. Remember this fact */
10659 	if (!more)
10660 		ipf->ipf_last_frag_seen = B_TRUE;
10661 
10662 	/* Still got holes? */
10663 	if (ipf->ipf_hole_cnt)
10664 		return (IP_REASS_PARTIAL);
10665 	/* Clean up overloaded fields to avoid upstream disasters. */
10666 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
10667 		IP_REASS_SET_START(mp1, 0);
10668 		IP_REASS_SET_END(mp1, 0);
10669 	}
10670 	return (IP_REASS_COMPLETE);
10671 }
10672 
10673 /*
10674  * ipsec processing for the fast path, used for input UDP Packets
10675  */
10676 static boolean_t
10677 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
10678     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
10679 {
10680 	uint32_t	ill_index;
10681 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
10682 
10683 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
10684 	/* The ill_index of the incoming ILL */
10685 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
10686 
10687 	/* pass packet up to the transport */
10688 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
10689 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
10690 		    NULL, mctl_present);
10691 		if (*first_mpp == NULL) {
10692 			return (B_FALSE);
10693 		}
10694 	}
10695 
10696 	/* Initiate IPPF processing for fastpath UDP */
10697 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
10698 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
10699 		if (*mpp == NULL) {
10700 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
10701 			    "deferred/dropped during IPPF processing\n"));
10702 			return (B_FALSE);
10703 		}
10704 	}
10705 	/*
10706 	 * We make the checks as below since we are in the fast path
10707 	 * and want to minimize the number of checks if the IP_RECVIF and/or
10708 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
10709 	 */
10710 	if (connp->conn_recvif || connp->conn_recvslla ||
10711 	    connp->conn_ipv6_recvpktinfo) {
10712 		if (connp->conn_recvif ||
10713 		    connp->conn_ipv6_recvpktinfo) {
10714 			in_flags = IPF_RECVIF;
10715 		}
10716 		if (connp->conn_recvslla) {
10717 			in_flags |= IPF_RECVSLLA;
10718 		}
10719 		/*
10720 		 * since in_flags are being set ill will be
10721 		 * referenced in ip_add_info, so it better not
10722 		 * be NULL.
10723 		 */
10724 		/*
10725 		 * the actual data will be contained in b_cont
10726 		 * upon successful return of the following call.
10727 		 * If the call fails then the original mblk is
10728 		 * returned.
10729 		 */
10730 		*mpp = ip_add_info(*mpp, ill, in_flags);
10731 	}
10732 
10733 	return (B_TRUE);
10734 }
10735 
10736 /*
10737  * Do fragmentation reassembly.
10738  * returns B_TRUE if successful else B_FALSE.
10739  * frees mp on failure.
10740  */
10741 static boolean_t
10742 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha)
10743 {
10744 	uint32_t	frag_offset_flags;
10745 	ill_t   *ill = (ill_t *)q->q_ptr;
10746 	mblk_t *mp = *mpp;
10747 	mblk_t *t_mp;
10748 	ipaddr_t	dst;
10749 
10750 	/*
10751 	 * Drop the fragmented as early as possible, if
10752 	 * we don't have resource(s) to re-assemble.
10753 	 */
10754 
10755 	if (ip_reass_queue_bytes == 0) {
10756 		freemsg(mp);
10757 		return (B_FALSE);
10758 	}
10759 
10760 	dst = ipha->ipha_dst;
10761 
10762 	/* Clear hardware checksumming flag if set */
10763 	mp->b_datap->db_struioun.cksum.flags = 0;
10764 
10765 	/* Check for fragmentation offset. */
10766 	frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
10767 	    (IPH_MF | IPH_OFFSET);
10768 	if (frag_offset_flags) {
10769 		ipf_t		*ipf;
10770 		ipf_t		**ipfp;
10771 		ipfb_t		*ipfb;
10772 		uint16_t	ident;
10773 		uint32_t	offset;
10774 		ipaddr_t	src;
10775 		uint_t		hdr_length;
10776 		uint32_t	end;
10777 		uint8_t		proto;
10778 		mblk_t		*mp1;
10779 		mblk_t		*tail_mp;
10780 		size_t		count;
10781 		size_t		msg_len;
10782 		uint8_t		ecn_info = 0;
10783 		uint32_t	packet_size;
10784 		boolean_t 	pruned = B_FALSE;
10785 
10786 		ident = ipha->ipha_ident;
10787 		offset = (frag_offset_flags << 3) & 0xFFFF;
10788 		src = ipha->ipha_src;
10789 		hdr_length = IPH_HDR_LENGTH(ipha);
10790 		end = ntohs(ipha->ipha_length) - hdr_length;
10791 
10792 		/*
10793 		 * if end == 0 then we have a packet with no data, so just
10794 		 * free it.
10795 		 */
10796 		if (end == 0) {
10797 			freemsg(mp);
10798 			return (B_FALSE);
10799 		}
10800 		proto = ipha->ipha_protocol;
10801 
10802 		/*
10803 		 * Fragmentation reassembly.  Each ILL has a hash table for
10804 		 * queuing packets undergoing reassembly for all IPIFs
10805 		 * associated with the ILL.  The hash is based on the packet
10806 		 * IP ident field.  The ILL frag hash table was allocated
10807 		 * as a timer block at the time the ILL was created.  Whenever
10808 		 * there is anything on the reassembly queue, the timer will
10809 		 * be running.
10810 		 */
10811 		ASSERT(ill != NULL);
10812 
10813 		/* Record the ECN field info. */
10814 		ecn_info = (ipha->ipha_type_of_service & 0x3);
10815 		if (offset != 0) {
10816 			/*
10817 			 * If this isn't the first piece, strip the header, and
10818 			 * add the offset to the end value.
10819 			 */
10820 			mp->b_rptr += hdr_length;
10821 			end += offset;
10822 		}
10823 
10824 		msg_len = mp->b_datap->db_lim - mp->b_datap->db_base;
10825 		tail_mp = mp;
10826 		while (tail_mp->b_cont != NULL) {
10827 			tail_mp = tail_mp->b_cont;
10828 			msg_len += tail_mp->b_datap->db_lim -
10829 			    tail_mp->b_datap->db_base;
10830 		}
10831 
10832 		/*
10833 		 * If the reassembly list for this ILL will get too big
10834 		 * prune it.
10835 		 */
10836 		if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
10837 		    ip_reass_queue_bytes) {
10838 			ill_frag_prune(ill,
10839 			    (ip_reass_queue_bytes < msg_len) ? 0 :
10840 			    (ip_reass_queue_bytes - msg_len));
10841 			pruned = B_TRUE;
10842 		}
10843 
10844 		ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
10845 		mutex_enter(&ipfb->ipfb_lock);
10846 
10847 		ipfp = &ipfb->ipfb_ipf;
10848 		/* Try to find an existing fragment queue for this packet. */
10849 		for (;;) {
10850 			ipf = ipfp[0];
10851 			if (ipf != NULL) {
10852 				/*
10853 				 * It has to match on ident and src/dst address.
10854 				 */
10855 				if (ipf->ipf_ident == ident &&
10856 				    ipf->ipf_src == src &&
10857 				    ipf->ipf_dst == dst &&
10858 				    ipf->ipf_protocol == proto) {
10859 					/*
10860 					 * If we have received too many
10861 					 * duplicate fragments for this packet
10862 					 * free it.
10863 					 */
10864 					if (ipf->ipf_num_dups >
10865 					    ip_max_frag_dups) {
10866 						ill_frag_free_pkts(ill, ipfb,
10867 						    ipf, 1);
10868 						freemsg(mp);
10869 						mutex_exit(&ipfb->ipfb_lock);
10870 						return (B_FALSE);
10871 					}
10872 					/* Found it. */
10873 					break;
10874 				}
10875 				ipfp = &ipf->ipf_hash_next;
10876 				continue;
10877 			}
10878 
10879 			/*
10880 			 * If we pruned the list, do we want to store this new
10881 			 * fragment?. We apply an optimization here based on the
10882 			 * fact that most fragments will be received in order.
10883 			 * So if the offset of this incoming fragment is zero,
10884 			 * it is the first fragment of a new packet. We will
10885 			 * keep it.  Otherwise drop the fragment, as we have
10886 			 * probably pruned the packet already (since the
10887 			 * packet cannot be found).
10888 			 */
10889 			if (pruned && offset != 0) {
10890 				mutex_exit(&ipfb->ipfb_lock);
10891 				freemsg(mp);
10892 				return (B_FALSE);
10893 			}
10894 
10895 			if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS)  {
10896 				/*
10897 				 * Too many fragmented packets in this hash
10898 				 * bucket. Free the oldest.
10899 				 */
10900 				ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf,
10901 				    1);
10902 			}
10903 
10904 			/* New guy.  Allocate a frag message. */
10905 			mp1 = allocb(sizeof (*ipf), BPRI_MED);
10906 			if (mp1 == NULL) {
10907 				BUMP_MIB(&ip_mib, ipInDiscards);
10908 				freemsg(mp);
10909 reass_done:
10910 				mutex_exit(&ipfb->ipfb_lock);
10911 				return (B_FALSE);
10912 			}
10913 
10914 
10915 			BUMP_MIB(&ip_mib, ipReasmReqds);
10916 			mp1->b_cont = mp;
10917 
10918 			/* Initialize the fragment header. */
10919 			ipf = (ipf_t *)mp1->b_rptr;
10920 			ipf->ipf_mp = mp1;
10921 			ipf->ipf_ptphn = ipfp;
10922 			ipfp[0] = ipf;
10923 			ipf->ipf_hash_next = NULL;
10924 			ipf->ipf_ident = ident;
10925 			ipf->ipf_protocol = proto;
10926 			ipf->ipf_src = src;
10927 			ipf->ipf_dst = dst;
10928 			ipf->ipf_nf_hdr_len = 0;
10929 			/* Record reassembly start time. */
10930 			ipf->ipf_timestamp = gethrestime_sec();
10931 			/* Record ipf generation and account for frag header */
10932 			ipf->ipf_gen = ill->ill_ipf_gen++;
10933 			ipf->ipf_count = mp1->b_datap->db_lim -
10934 			    mp1->b_datap->db_base;
10935 			ipf->ipf_last_frag_seen = B_FALSE;
10936 			ipf->ipf_ecn = ecn_info;
10937 			ipf->ipf_num_dups = 0;
10938 			ipfb->ipfb_frag_pkts++;
10939 
10940 			/*
10941 			 * We handle reassembly two ways.  In the easy case,
10942 			 * where all the fragments show up in order, we do
10943 			 * minimal bookkeeping, and just clip new pieces on
10944 			 * the end.  If we ever see a hole, then we go off
10945 			 * to ip_reassemble which has to mark the pieces and
10946 			 * keep track of the number of holes, etc.  Obviously,
10947 			 * the point of having both mechanisms is so we can
10948 			 * handle the easy case as efficiently as possible.
10949 			 */
10950 			if (offset == 0) {
10951 				/* Easy case, in-order reassembly so far. */
10952 				ipf->ipf_count += msg_len;
10953 				ipf->ipf_tail_mp = tail_mp;
10954 				/*
10955 				 * Keep track of next expected offset in
10956 				 * ipf_end.
10957 				 */
10958 				ipf->ipf_end = end;
10959 				ipf->ipf_nf_hdr_len = hdr_length;
10960 			} else {
10961 				/* Hard case, hole at the beginning. */
10962 				ipf->ipf_tail_mp = NULL;
10963 				/*
10964 				 * ipf_end == 0 means that we have given up
10965 				 * on easy reassembly.
10966 				 */
10967 				ipf->ipf_end = 0;
10968 				/*
10969 				 * ipf_hole_cnt is set by ip_reassemble.
10970 				 * ipf_count is updated by ip_reassemble.
10971 				 * No need to check for return value here
10972 				 * as we don't expect reassembly to complete
10973 				 * or fail for the first fragment itself.
10974 				 */
10975 				(void) ip_reassemble(mp, ipf,
10976 				    (frag_offset_flags & IPH_OFFSET) << 3,
10977 				    (frag_offset_flags & IPH_MF), ill, msg_len);
10978 			}
10979 			/* Update per ipfb and ill byte counts */
10980 			ipfb->ipfb_count += ipf->ipf_count;
10981 			ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
10982 			ill->ill_frag_count += ipf->ipf_count;
10983 			ASSERT(ill->ill_frag_count > 0); /* Wraparound */
10984 			/* If the frag timer wasn't already going, start it. */
10985 			mutex_enter(&ill->ill_lock);
10986 			ill_frag_timer_start(ill);
10987 			mutex_exit(&ill->ill_lock);
10988 			goto reass_done;
10989 		}
10990 
10991 		/*
10992 		 * We have a new piece of a datagram which is already being
10993 		 * reassembled.  Update the ECN info if all IP fragments
10994 		 * are ECN capable.  If there is one which is not, clear
10995 		 * all the info.  If there is at least one which has CE
10996 		 * code point, IP needs to report that up to transport.
10997 		 */
10998 		if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
10999 			if (ecn_info == IPH_ECN_CE)
11000 				ipf->ipf_ecn = IPH_ECN_CE;
11001 		} else {
11002 			ipf->ipf_ecn = IPH_ECN_NECT;
11003 		}
11004 		if (offset && ipf->ipf_end == offset) {
11005 			/* The new fragment fits at the end */
11006 			ipf->ipf_tail_mp->b_cont = mp;
11007 			/* Update the byte count */
11008 			ipf->ipf_count += msg_len;
11009 			/* Update per ipfb and ill byte counts */
11010 			ipfb->ipfb_count += msg_len;
11011 			ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
11012 			ill->ill_frag_count += msg_len;
11013 			ASSERT(ill->ill_frag_count > 0); /* Wraparound */
11014 			if (frag_offset_flags & IPH_MF) {
11015 				/* More to come. */
11016 				ipf->ipf_end = end;
11017 				ipf->ipf_tail_mp = tail_mp;
11018 				goto reass_done;
11019 			}
11020 		} else {
11021 			/* Go do the hard cases. */
11022 			int ret;
11023 
11024 			if (offset == 0)
11025 				ipf->ipf_nf_hdr_len = hdr_length;
11026 
11027 			/* Save current byte count */
11028 			count = ipf->ipf_count;
11029 			ret = ip_reassemble(mp, ipf,
11030 			    (frag_offset_flags & IPH_OFFSET) << 3,
11031 			    (frag_offset_flags & IPH_MF), ill, msg_len);
11032 			/* Count of bytes added and subtracted (freeb()ed) */
11033 			count = ipf->ipf_count - count;
11034 			if (count) {
11035 				/* Update per ipfb and ill byte counts */
11036 				ipfb->ipfb_count += count;
11037 				ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
11038 				ill->ill_frag_count += count;
11039 				ASSERT(ill->ill_frag_count > 0);
11040 			}
11041 			if (ret == IP_REASS_PARTIAL) {
11042 				goto reass_done;
11043 			} else if (ret == IP_REASS_FAILED) {
11044 				/* Reassembly failed. Free up all resources */
11045 				ill_frag_free_pkts(ill, ipfb, ipf, 1);
11046 				for (t_mp = mp; t_mp != NULL;
11047 				    t_mp = t_mp->b_cont) {
11048 					IP_REASS_SET_START(t_mp, 0);
11049 					IP_REASS_SET_END(t_mp, 0);
11050 				}
11051 				freemsg(mp);
11052 				goto reass_done;
11053 			}
11054 			/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
11055 		}
11056 		/*
11057 		 * We have completed reassembly.  Unhook the frag header from
11058 		 * the reassembly list.
11059 		 *
11060 		 * Before we free the frag header, record the ECN info
11061 		 * to report back to the transport.
11062 		 */
11063 		ecn_info = ipf->ipf_ecn;
11064 		BUMP_MIB(&ip_mib, ipReasmOKs);
11065 		ipfp = ipf->ipf_ptphn;
11066 		mp1 = ipf->ipf_mp;
11067 		count = ipf->ipf_count;
11068 		ipf = ipf->ipf_hash_next;
11069 		if (ipf)
11070 			ipf->ipf_ptphn = ipfp;
11071 		ipfp[0] = ipf;
11072 		ill->ill_frag_count -= count;
11073 		ASSERT(ipfb->ipfb_count >= count);
11074 		ipfb->ipfb_count -= count;
11075 		ipfb->ipfb_frag_pkts--;
11076 		mutex_exit(&ipfb->ipfb_lock);
11077 		/* Ditch the frag header. */
11078 		mp = mp1->b_cont;
11079 
11080 		freeb(mp1);
11081 
11082 		/* Restore original IP length in header. */
11083 		packet_size = (uint32_t)msgdsize(mp);
11084 		if (packet_size > IP_MAXPACKET) {
11085 			freemsg(mp);
11086 			BUMP_MIB(&ip_mib, ipInHdrErrors);
11087 			return (B_FALSE);
11088 		}
11089 
11090 		if (mp->b_datap->db_ref > 1) {
11091 			mblk_t *mp2;
11092 
11093 			mp2 = copymsg(mp);
11094 			freemsg(mp);
11095 			if (!mp2) {
11096 				BUMP_MIB(&ip_mib, ipInDiscards);
11097 				return (B_FALSE);
11098 			}
11099 			mp = mp2;
11100 		}
11101 		ipha = (ipha_t *)mp->b_rptr;
11102 
11103 		ipha->ipha_length = htons((uint16_t)packet_size);
11104 		/* We're now complete, zip the frag state */
11105 		ipha->ipha_fragment_offset_and_flags = 0;
11106 		/* Record the ECN info. */
11107 		ipha->ipha_type_of_service &= 0xFC;
11108 		ipha->ipha_type_of_service |= ecn_info;
11109 		*mpp = mp;
11110 
11111 	}
11112 	return (B_TRUE);
11113 }
11114 
11115 /*
11116  * Perform ip header check sum update local options.
11117  * return B_TRUE if all is well, else return B_FALSE and release
11118  * the mp. caller is responsible for decrementing ire ref cnt.
11119  */
11120 static boolean_t
11121 ip_options_cksum(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
11122 {
11123 	mblk_t		*first_mp;
11124 	boolean_t	mctl_present;
11125 	uint16_t	sum;
11126 
11127 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
11128 	/*
11129 	 * Don't do the checksum if it has gone through AH/ESP
11130 	 * processing.
11131 	 */
11132 	if (!mctl_present) {
11133 		sum = ip_csum_hdr(ipha);
11134 		if (sum != 0) {
11135 			BUMP_MIB(&ip_mib, ipInCksumErrs);
11136 			freemsg(first_mp);
11137 			return (B_FALSE);
11138 		}
11139 	}
11140 
11141 	if (!ip_rput_local_options(q, mp, ipha, ire)) {
11142 		if (mctl_present)
11143 			freeb(first_mp);
11144 		return (B_FALSE);
11145 	}
11146 
11147 	return (B_TRUE);
11148 }
11149 
11150 /*
11151  * All udp packet are delivered to the local host via this routine.
11152  */
11153 void
11154 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
11155     ill_t *recv_ill)
11156 {
11157 	uint32_t	sum;
11158 	uint32_t	u1;
11159 	uint32_t	u2;
11160 	boolean_t	mctl_present;
11161 	conn_t		*connp;
11162 	mblk_t		*first_mp;
11163 	mblk_t		*mp1;
11164 	dblk_t		*dp;
11165 	uint16_t	*up;
11166 	ill_t		*ill = (ill_t *)q->q_ptr;
11167 	uint32_t	ports;
11168 	boolean_t	cksum_computed = B_FALSE;
11169 
11170 #define	rptr    ((uchar_t *)ipha)
11171 
11172 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
11173 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
11174 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11175 
11176 	/*
11177 	 * FAST PATH for udp packets
11178 	 */
11179 
11180 	/* u1 is # words of IP options */
11181 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
11182 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
11183 
11184 	/* IP options present */
11185 	if (u1)
11186 		goto ipoptions;
11187 
11188 #define	IS_IPHDR_HWCKSUM(mctl_present, mp, ill)				\
11189 	((!mctl_present) && (mp->b_datap->db_struioun.cksum.flags &	\
11190 	HCK_IPV4_HDRCKSUM) && (ill->ill_capabilities &			\
11191 	ILL_CAPAB_HCKSUM) && dohwcksum)
11192 
11193 	/* Check the IP header checksum.  */
11194 	if (IS_IPHDR_HWCKSUM(mctl_present, mp, ill)) {
11195 		/* Clear the IP header h/w cksum flag */
11196 		mp->b_datap->db_struioun.cksum.flags &=
11197 		    ~HCK_IPV4_HDRCKSUM;
11198 	} else {
11199 #define	uph	((uint16_t *)ipha)
11200 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
11201 		    uph[6] + uph[7] + uph[8] + uph[9];
11202 #undef	uph
11203 		/* finish doing IP checksum */
11204 		sum = (sum & 0xFFFF) + (sum >> 16);
11205 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
11206 		/*
11207 		 * Don't verify header checksum if this packet is coming
11208 		 * back from AH/ESP as we already did it.
11209 		 */
11210 		if (!mctl_present && (sum && sum != 0xFFFF)) {
11211 			BUMP_MIB(&ip_mib, ipInCksumErrs);
11212 			freemsg(first_mp);
11213 			return;
11214 		}
11215 	}
11216 
11217 	/*
11218 	 * Count for SNMP of inbound packets for ire.
11219 	 * if mctl is present this might be a secure packet and
11220 	 * has already been counted for in ip_proto_input().
11221 	 */
11222 	if (!mctl_present) {
11223 		UPDATE_IB_PKT_COUNT(ire);
11224 		ire->ire_last_used_time = lbolt;
11225 	}
11226 
11227 	/* packet part of fragmented IP packet? */
11228 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11229 	if (u1 & (IPH_MF | IPH_OFFSET)) {
11230 		goto fragmented;
11231 	}
11232 
11233 	/* u1 = IP header length (20 bytes) */
11234 	u1 = IP_SIMPLE_HDR_LENGTH;
11235 
11236 	/* packet does not contain complete IP & UDP headers */
11237 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
11238 		goto udppullup;
11239 	/* up points to UDP header */
11240 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
11241 #define	iphs    ((uint16_t *)ipha)
11242 
11243 #define	IP_CKSUM_RECV(len, u1, u2, mp, mp1, error, dp) {		\
11244 	boolean_t	doswcksum = B_TRUE;				\
11245 	uint_t		hcksumflags = 0;				\
11246 									\
11247 	hcksumflags = dp->db_struioun.cksum.flags;			\
11248 									\
11249 	/* Clear the hardware checksum flags; they have been consumed */\
11250 	dp->db_struioun.cksum.flags = 0;				\
11251 	if (hcksumflags && (ill->ill_capabilities & ILL_CAPAB_HCKSUM) &&\
11252 		dohwcksum) {						\
11253 		if (hcksumflags & HCK_FULLCKSUM) {			\
11254 			/* 						\
11255 			 * Full checksum has been computed by the	\
11256 			 * hardware and has been attached. 		\
11257 			 */						\
11258 			doswcksum = B_FALSE;				\
11259 			if (!(hcksumflags & HCK_FULLCKSUM_OK) &&	\
11260 			    (dp->db_cksum16 != 0xffff)) {		\
11261 				ipcsumdbg("full hwcksumerr\n", mp);	\
11262 				goto error;				\
11263 			}						\
11264 		} else if ((hcksumflags & HCK_PARTIALCKSUM) &&		\
11265 		    (((len = (IP_SIMPLE_HDR_LENGTH - dp->db_cksumstart))\
11266 		    & 1) == 0)) {					\
11267 			uint32_t	tot_len = 0;			\
11268 									\
11269 			doswcksum = B_FALSE;				\
11270 			/* Partial checksum computed */			\
11271 			u1 += dp->db_cksum16;				\
11272 			tot_len = mp->b_wptr - mp->b_rptr;		\
11273 			if (!mp1)					\
11274 				mp1 = mp;				\
11275 			else						\
11276 				tot_len += mp1->b_wptr - mp1->b_rptr;	\
11277 			if (len > 0) {					\
11278 				/* 					\
11279 				 * Prepended extraneous data. Adjust	\
11280 				 * checksum.				\
11281 				 */					\
11282 				u2 = IP_BCSUM_PARTIAL((uchar_t *)(rptr +\
11283 				    dp->db_cksumstart),	(int32_t)len, 	\
11284 				    0);					\
11285 			} else						\
11286 				u2 = 0;					\
11287 			if ((len = (dp->db_cksumend - tot_len)) > 0) {	\
11288 				/* 					\
11289 				 * Postpended extraneous data. Adjust	\
11290 				 * checksum.				\
11291 				 */					\
11292 				uint32_t	u3;			\
11293 									\
11294 				u3 = IP_BCSUM_PARTIAL(mp1->b_wptr, 	\
11295 				    (int32_t)len, 0);			\
11296 				if ((uintptr_t)mp1->b_wptr & 1)		\
11297 					/*				\
11298 					 * Postpended extraneous data	\
11299 					 * was odd byte aligned, so 	\
11300 					 * swap resulting checksum 	\
11301 					 * bytes.			\
11302 					 */				\
11303 					u2 += ((u3 << 8) & 0xffff) | 	\
11304 					    (u3 >> 8);			\
11305 				else					\
11306 					u2 += u3;			\
11307 				u2 = (u2 & 0xFFFF) + ((int)(u2) >> 16);	\
11308 			}						\
11309 			/*						\
11310 			 * One's complement subtract extraneous checksum\
11311 			 */						\
11312 			if (u2 >= u1)					\
11313 				u1 = ~(u2 - u1) & 0xFFFF;		\
11314 			else						\
11315 				u1 -= u2;				\
11316 			u1 = (u1 & 0xFFFF) + ((int)u1 >> 16);		\
11317 			if (~(u1) & 0xFFFF) {				\
11318 				ipcsumdbg("partial hwcksumerr\n", mp);	\
11319 				goto error;				\
11320 			}						\
11321 		} 							\
11322 	} 								\
11323 	if (doswcksum) {						\
11324 		IP_STAT(ip_in_sw_cksum);				\
11325 		if ((IP_CSUM(mp, (int32_t)((uchar_t *)up -		\
11326 		    (uchar_t *)ipha), u1)) != 0) {			\
11327 			ipcsumdbg("swcksumerr\n", mp);			\
11328 			goto error;					\
11329 		}							\
11330 	}								\
11331 }
11332 
11333 	dp = mp->b_datap;
11334 	/* if udp hdr cksum != 0, then need to checksum udp packet */
11335 	if (up[3]) {
11336 		cksum_computed = B_TRUE;
11337 		/* multiple mblks of udp data? */
11338 		if ((mp1 = mp->b_cont) != NULL) {
11339 			/* more than two? */
11340 			if (mp1->b_cont)
11341 				goto multipktudp;
11342 		}
11343 
11344 		/* Pseudo-header checksum */
11345 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
11346 		    iphs[9] + up[2];
11347 		if (!mctl_present) {
11348 			ssize_t len = 0;
11349 
11350 			IP_CKSUM_RECV(len, u1, u2, mp, mp1, udpcksumerr, dp);
11351 		} else {
11352 multipktudp:
11353 			IP_STAT(ip_in_sw_cksum);
11354 			if ((IP_CSUM(mp, (int32_t)((uchar_t *)up -
11355 			    (uchar_t *)ipha), u1)) != 0) {
11356 udpcksumerr:
11357 				ip1dbg(("ip_udp_input: bad udp checksum\n"));
11358 				BUMP_MIB(&ip_mib, udpInCksumErrs);
11359 				freemsg(first_mp);
11360 				return;
11361 			}
11362 		}
11363 	}
11364 
11365 	/* broadcast IP packet? */
11366 	if (ire->ire_type == IRE_BROADCAST)
11367 		goto udpslowpath;
11368 
11369 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
11370 	    ire->ire_zoneid)) != NULL) {
11371 		ASSERT(connp->conn_upq != NULL);
11372 		IP_STAT(ip_udp_fast_path);
11373 
11374 		if (!canputnext(connp->conn_upq)) {
11375 			freemsg(mp);
11376 			BUMP_MIB(&ip_mib, udpInOverflows);
11377 		} else {
11378 			if (!mctl_present) {
11379 				BUMP_MIB(&ip_mib, ipInDelivers);
11380 			}
11381 			/*
11382 			 * mp and first_mp can change.
11383 			 */
11384 			if (ip_udp_check(q, connp, recv_ill,
11385 			    ipha, &mp, &first_mp, mctl_present)) {
11386 				putnext(connp->conn_upq, mp);
11387 			}
11388 		}
11389 		/*
11390 		 * freeb() cannot deal with null mblk being passed
11391 		 * in and first_mp can be set to null in the call
11392 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
11393 		 */
11394 		if (mctl_present && first_mp != NULL) {
11395 			freeb(first_mp);
11396 		}
11397 		CONN_DEC_REF(connp);
11398 		return;
11399 	}
11400 
11401 	/*
11402 	 * if we got here we know the packet is not fragmented and
11403 	 * has no options. The classifier could not find a conn_t and
11404 	 * most likely its an icmp packet so send it through slow path.
11405 	 */
11406 
11407 	goto udpslowpath;
11408 
11409 ipoptions:
11410 	if (!ip_options_cksum(q, mp, ipha, ire)) {
11411 		goto slow_done;
11412 	}
11413 
11414 	UPDATE_IB_PKT_COUNT(ire);
11415 	ire->ire_last_used_time = lbolt;
11416 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11417 	if (u1 & (IPH_MF | IPH_OFFSET)) {
11418 fragmented:
11419 		if (!ip_rput_fragment(q, &mp, ipha)) {
11420 			goto slow_done;
11421 		}
11422 		/*
11423 		 * Make sure that first_mp points back to mp as
11424 		 * the mp we came in with could have changed in
11425 		 * ip_rput_fragment().
11426 		 */
11427 		ASSERT(!mctl_present);
11428 		ipha = (ipha_t *)mp->b_rptr;
11429 		first_mp = mp;
11430 	}
11431 
11432 	/* Now we have a complete datagram, destined for this machine. */
11433 	u1 = IPH_HDR_LENGTH(ipha);
11434 	/* Pull up the UDP header, if necessary. */
11435 	if ((mp->b_wptr - mp->b_rptr) < (u1 + UDPH_SIZE)) {
11436 udppullup:
11437 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
11438 			BUMP_MIB(&ip_mib, ipInDiscards);
11439 			freemsg(first_mp);
11440 			goto slow_done;
11441 		}
11442 		ipha = (ipha_t *)mp->b_rptr;
11443 	}
11444 	/*
11445 	 * Validate the checksum.  This code is a bit funny looking
11446 	 * but may help out the compiler in this crucial spot.
11447 	 */
11448 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
11449 	if (!cksum_computed && up[3]) {
11450 		IP_STAT(ip_in_sw_cksum);
11451 		sum = IP_CSUM(mp, (int32_t)((uchar_t *)up - (uchar_t *)ipha),
11452 		    IP_UDP_CSUM_COMP + iphs[6] +
11453 		    iphs[7] + iphs[8] +
11454 		    iphs[9] + up[2]);
11455 		if (sum != 0) {
11456 			ip1dbg(("ip_udp_input: bad udp checksum\n"));
11457 				BUMP_MIB(&ip_mib, udpInCksumErrs);
11458 				freemsg(first_mp);
11459 				goto slow_done;
11460 		}
11461 	}
11462 udpslowpath:
11463 
11464 	ports = *(uint32_t *)up;
11465 	/* Clear hardware checksum flag */
11466 	mp->b_datap->db_struioun.cksum.flags = 0;
11467 	ip_fanout_udp(q, first_mp, ill, ipha, ports,
11468 	    (ire->ire_type == IRE_BROADCAST),
11469 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IP6INFO,
11470 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
11471 
11472 slow_done:
11473 	IP_STAT(ip_udp_slow_path);
11474 	return;
11475 
11476 #undef  rptr
11477 }
11478 
11479 /* ARGSUSED */
11480 static mblk_t *
11481 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
11482     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
11483     ill_rx_ring_t *ill_ring)
11484 {
11485 	conn_t		*connp;
11486 	uint32_t	sum;
11487 	uint32_t	u1;
11488 	uint32_t	u2;
11489 	uint16_t	*up;
11490 	int		offset;
11491 	ssize_t		len;
11492 	mblk_t		*mp1;
11493 	dblk_t		*dp;
11494 	boolean_t	syn_present = B_FALSE;
11495 	tcph_t		*tcph;
11496 	uint_t		ip_hdr_len;
11497 	ill_t		*ill = (ill_t *)q->q_ptr;
11498 	zoneid_t	zoneid = ire->ire_zoneid;
11499 
11500 #define	rptr	((uchar_t *)ipha)
11501 
11502 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
11503 
11504 	/*
11505 	 * FAST PATH for tcp packets
11506 	 */
11507 
11508 	/* u1 is # words of IP options */
11509 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
11510 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
11511 
11512 	/* IP options present */
11513 	if (u1) {
11514 		goto ipoptions;
11515 	} else {
11516 		/* Check the IP header checksum.  */
11517 		if (IS_IPHDR_HWCKSUM(mctl_present, mp, ill)) {
11518 			/* Clear the IP header h/w cksum flag */
11519 			mp->b_datap->db_struioun.cksum.flags &=
11520 			    ~HCK_IPV4_HDRCKSUM;
11521 		} else {
11522 #define	uph	((uint16_t *)ipha)
11523 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
11524 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
11525 #undef	uph
11526 			/* finish doing IP checksum */
11527 			sum = (sum & 0xFFFF) + (sum >> 16);
11528 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
11529 			/*
11530 			 * Don't verify header checksum if this packet
11531 			 * is coming back from AH/ESP as we already did it.
11532 			 */
11533 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
11534 				BUMP_MIB(&ip_mib, ipInCksumErrs);
11535 				goto error;
11536 			}
11537 		}
11538 	}
11539 
11540 	if (!mctl_present) {
11541 		UPDATE_IB_PKT_COUNT(ire);
11542 		ire->ire_last_used_time = lbolt;
11543 	}
11544 
11545 	/* packet part of fragmented IP packet? */
11546 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11547 	if (u1 & (IPH_MF | IPH_OFFSET)) {
11548 		goto fragmented;
11549 	}
11550 
11551 	/* u1 = IP header length (20 bytes) */
11552 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
11553 
11554 	/* does packet contain IP+TCP headers? */
11555 	len = mp->b_wptr - rptr;
11556 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
11557 		IP_STAT(ip_tcppullup);
11558 		goto tcppullup;
11559 	}
11560 
11561 	/* TCP options present? */
11562 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
11563 
11564 	/*
11565 	 * If options need to be pulled up, then goto tcpoptions.
11566 	 * otherwise we are still in the fast path
11567 	 */
11568 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
11569 		IP_STAT(ip_tcpoptions);
11570 		goto tcpoptions;
11571 	}
11572 
11573 	/* multiple mblks of tcp data? */
11574 	if ((mp1 = mp->b_cont) != NULL) {
11575 		/* more then two? */
11576 		if (mp1->b_cont != NULL) {
11577 			IP_STAT(ip_multipkttcp);
11578 			goto multipkttcp;
11579 		}
11580 		len += mp1->b_wptr - mp1->b_rptr;
11581 	}
11582 
11583 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
11584 
11585 	/* part of pseudo checksum */
11586 
11587 	/* TCP datagram length */
11588 	u1 = len - IP_SIMPLE_HDR_LENGTH;
11589 
11590 #define	iphs    ((uint16_t *)ipha)
11591 
11592 #ifdef	_BIG_ENDIAN
11593 	u1 += IPPROTO_TCP;
11594 #else
11595 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
11596 #endif
11597 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
11598 
11599 
11600 	/*
11601 	 * If the packet has gone through AH/ESP, do the checksum here
11602 	 * itself.
11603 	 *
11604 	 * If it has not gone through IPSEC processing and not a duped
11605 	 * mblk, then look for driver checksummed mblk. We validate or
11606 	 * postpone the checksum to TCP for single copy checksum.
11607 	 *
11608 	 * Note that we only honor HW cksum in the fastpath.
11609 	 */
11610 	dp = mp->b_datap;
11611 	if (!mctl_present) {
11612 		IP_CKSUM_RECV(len, u1, u2, mp, mp1, tcpcksumerr, dp);
11613 	} else {
11614 		IP_STAT(ip_in_sw_cksum);
11615 		if ((IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr),
11616 		    u1)) != 0) {
11617 tcpcksumerr:
11618 			BUMP_MIB(&ip_mib, tcpInErrs);
11619 			ip1dbg(("ip_tcp_input: bad tcp checksum \n"));
11620 			freemsg(first_mp);
11621 			goto slow_done;
11622 		}
11623 	}
11624 
11625 try_again:
11626 
11627 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
11628 	    NULL) {
11629 		/* Send the TH_RST */
11630 		goto no_conn;
11631 	}
11632 
11633 	/*
11634 	 * TCP FAST PATH for AF_INET socket.
11635 	 *
11636 	 * TCP fast path to avoid extra work. An AF_INET socket type
11637 	 * does not have facility to receive extra information via
11638 	 * ip_process or ip_add_info. Also, when the connection was
11639 	 * established, we made a check if this connection is impacted
11640 	 * by any global IPSec policy or per connection policy (a
11641 	 * policy that comes in effect later will not apply to this
11642 	 * connection). Since all this can be determined at the
11643 	 * connection establishment time, a quick check of flags
11644 	 * can avoid extra work.
11645 	 */
11646 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
11647 	    !IPP_ENABLED(IPP_LOCAL_IN)) {
11648 		ASSERT(first_mp == mp);
11649 		SET_SQUEUE(mp, tcp_rput_data, connp);
11650 		return (mp);
11651 	}
11652 
11653 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
11654 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
11655 		if (IPCL_IS_TCP(connp)) {
11656 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
11657 			mp->b_datap->db_cksumstart =
11658 			    (intptr_t)ip_squeue_get(ill_ring);
11659 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
11660 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
11661 				SET_SQUEUE(mp, connp->conn_recv, connp);
11662 				return (mp);
11663 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
11664 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
11665 				ip_squeue_enter_unbound++;
11666 				SET_SQUEUE(mp, tcp_conn_request_unbound,
11667 				    connp);
11668 				return (mp);
11669 			}
11670 			syn_present = B_TRUE;
11671 		}
11672 
11673 	}
11674 
11675 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
11676 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
11677 
11678 		/* No need to send this packet to TCP */
11679 		if ((flags & TH_RST) || (flags & TH_URG)) {
11680 			CONN_DEC_REF(connp);
11681 			freemsg(first_mp);
11682 			return (NULL);
11683 		}
11684 		if (flags & TH_ACK) {
11685 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
11686 			CONN_DEC_REF(connp);
11687 			return (NULL);
11688 		}
11689 
11690 		CONN_DEC_REF(connp);
11691 		freemsg(first_mp);
11692 		return (NULL);
11693 	}
11694 
11695 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
11696 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
11697 		    ipha, NULL, mctl_present);
11698 		if (first_mp == NULL) {
11699 			CONN_DEC_REF(connp);
11700 			return (NULL);
11701 		}
11702 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
11703 			ASSERT(syn_present);
11704 			if (mctl_present) {
11705 				ASSERT(first_mp != mp);
11706 				first_mp->b_datap->db_struioflag |=
11707 				    STRUIO_POLICY;
11708 			} else {
11709 				ASSERT(first_mp == mp);
11710 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
11711 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
11712 			}
11713 		} else {
11714 			/*
11715 			 * Discard first_mp early since we're dealing with a
11716 			 * fully-connected conn_t and tcp doesn't do policy in
11717 			 * this case.
11718 			 */
11719 			if (mctl_present) {
11720 				freeb(first_mp);
11721 				mctl_present = B_FALSE;
11722 			}
11723 			first_mp = mp;
11724 		}
11725 	}
11726 
11727 	/* Initiate IPPF processing for fastpath */
11728 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
11729 		uint32_t	ill_index;
11730 
11731 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
11732 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
11733 		if (mp == NULL) {
11734 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
11735 			    "deferred/dropped during IPPF processing\n"));
11736 			CONN_DEC_REF(connp);
11737 			if (mctl_present)
11738 				freeb(first_mp);
11739 			return (NULL);
11740 		} else if (mctl_present) {
11741 			/*
11742 			 * ip_process might return a new mp.
11743 			 */
11744 			ASSERT(first_mp != mp);
11745 			first_mp->b_cont = mp;
11746 		} else {
11747 			first_mp = mp;
11748 		}
11749 
11750 	}
11751 
11752 	if (!syn_present && connp->conn_ipv6_recvpktinfo) {
11753 		mp = ip_add_info(mp, recv_ill, flags);
11754 		if (mp == NULL) {
11755 			CONN_DEC_REF(connp);
11756 			if (mctl_present)
11757 				freeb(first_mp);
11758 			return (NULL);
11759 		} else if (mctl_present) {
11760 			/*
11761 			 * ip_add_info might return a new mp.
11762 			 */
11763 			ASSERT(first_mp != mp);
11764 			first_mp->b_cont = mp;
11765 		} else {
11766 			first_mp = mp;
11767 		}
11768 	}
11769 
11770 	if (IPCL_IS_TCP(connp)) {
11771 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
11772 		return (first_mp);
11773 	} else {
11774 		putnext(connp->conn_rq, first_mp);
11775 		CONN_DEC_REF(connp);
11776 		return (NULL);
11777 	}
11778 
11779 no_conn:
11780 	/* Initiate IPPf processing, if needed. */
11781 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
11782 		uint32_t ill_index;
11783 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
11784 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
11785 		if (first_mp == NULL) {
11786 			return (NULL);
11787 		}
11788 	}
11789 	BUMP_MIB(&ip_mib, ipInDelivers);
11790 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr));
11791 	return (NULL);
11792 ipoptions:
11793 	if (!ip_options_cksum(q, first_mp, ipha, ire)) {
11794 		goto slow_done;
11795 	}
11796 
11797 	UPDATE_IB_PKT_COUNT(ire);
11798 	ire->ire_last_used_time = lbolt;
11799 
11800 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11801 	if (u1 & (IPH_MF | IPH_OFFSET)) {
11802 fragmented:
11803 		if (!ip_rput_fragment(q, &mp, ipha)) {
11804 			if (mctl_present)
11805 				freeb(first_mp);
11806 			goto slow_done;
11807 		}
11808 		/*
11809 		 * Make sure that first_mp points back to mp as
11810 		 * the mp we came in with could have changed in
11811 		 * ip_rput_fragment().
11812 		 */
11813 		ASSERT(!mctl_present);
11814 		ipha = (ipha_t *)mp->b_rptr;
11815 		first_mp = mp;
11816 	}
11817 
11818 tcp_slow:
11819 	/* Now we have a complete datagram, destined for this machine. */
11820 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
11821 
11822 	len = mp->b_wptr - mp->b_rptr;
11823 	/* Pull up a minimal TCP header, if necessary. */
11824 	if (len < (u1 + 20)) {
11825 tcppullup:
11826 		if (!pullupmsg(mp, u1 + 20)) {
11827 			BUMP_MIB(&ip_mib, ipInDiscards);
11828 			goto error;
11829 		}
11830 		ipha = (ipha_t *)mp->b_rptr;
11831 		len = mp->b_wptr - mp->b_rptr;
11832 	}
11833 
11834 	/*
11835 	 * Extract the offset field from the TCP header.  As usual, we
11836 	 * try to help the compiler more than the reader.
11837 	 */
11838 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
11839 	if (offset != 5) {
11840 tcpoptions:
11841 		if (offset < 5) {
11842 			BUMP_MIB(&ip_mib, ipInDiscards);
11843 			goto error;
11844 		}
11845 		/*
11846 		 * There must be TCP options.
11847 		 * Make sure we can grab them.
11848 		 */
11849 		offset <<= 2;
11850 		offset += u1;
11851 		if (len < offset) {
11852 			if (!pullupmsg(mp, offset)) {
11853 				BUMP_MIB(&ip_mib, ipInDiscards);
11854 				goto error;
11855 			}
11856 			ipha = (ipha_t *)mp->b_rptr;
11857 			len = mp->b_wptr - rptr;
11858 		}
11859 	}
11860 
11861 	/* Get the total packet length in len, including headers. */
11862 	if (mp->b_cont) {
11863 multipkttcp:
11864 		len = msgdsize(mp);
11865 	}
11866 
11867 	/*
11868 	 * Check the TCP checksum by pulling together the pseudo-
11869 	 * header checksum, and passing it to ip_csum to be added in
11870 	 * with the TCP datagram.
11871 	 *
11872 	 * Since we are not using the hwcksum if available we must
11873 	 * clear the flag. We may come here via tcppullup or tcpoptions.
11874 	 * If either of these fails along the way the mblk is freed.
11875 	 * If this logic ever changes and mblk is reused to say send
11876 	 * ICMP's back, then this flag may need to be cleared in
11877 	 * other places as well.
11878 	 */
11879 	mp->b_datap->db_struioun.cksum.flags = 0;
11880 
11881 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
11882 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
11883 #ifdef	_BIG_ENDIAN
11884 	u1 += IPPROTO_TCP;
11885 #else
11886 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
11887 #endif
11888 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
11889 	/*
11890 	 * Not M_DATA mblk or its a dup, so do the checksum now.
11891 	 */
11892 	IP_STAT(ip_in_sw_cksum);
11893 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1)) {
11894 		BUMP_MIB(&ip_mib, tcpInErrs);
11895 		goto error;
11896 	}
11897 
11898 	IP_STAT(ip_tcp_slow_path);
11899 	goto try_again;
11900 #undef  iphs
11901 #undef  rptr
11902 
11903 error:
11904 	freemsg(first_mp);
11905 slow_done:
11906 	return (NULL);
11907 }
11908 
11909 /* ARGSUSED */
11910 static void
11911 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
11912     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
11913 {
11914 	conn_t		*connp;
11915 	uint32_t	sum;
11916 	uint32_t	u1;
11917 	ssize_t		len;
11918 	sctp_hdr_t	*sctph;
11919 	zoneid_t	zoneid = ire->ire_zoneid;
11920 	uint32_t	pktsum;
11921 	uint32_t	calcsum;
11922 	uint32_t	ports;
11923 	uint_t		ipif_seqid;
11924 	in6_addr_t	map_src, map_dst;
11925 	ill_t		*ill = (ill_t *)q->q_ptr;
11926 
11927 #define	rptr	((uchar_t *)ipha)
11928 
11929 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
11930 
11931 	/* u1 is # words of IP options */
11932 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
11933 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
11934 
11935 	/* IP options present */
11936 	if (u1 > 0) {
11937 		goto ipoptions;
11938 	} else {
11939 		/* Check the IP header checksum.  */
11940 		if (IS_IPHDR_HWCKSUM(mctl_present, mp, ill)) {
11941 			/*
11942 			 * Since there is no SCTP h/w cksum support yet, just
11943 			 * clear the flag.
11944 			 */
11945 			mp->b_datap->db_struioun.cksum.flags = 0;
11946 		} else {
11947 #define	uph	((uint16_t *)ipha)
11948 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
11949 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
11950 #undef	uph
11951 			/* finish doing IP checksum */
11952 			sum = (sum & 0xFFFF) + (sum >> 16);
11953 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
11954 			/*
11955 			 * Don't verify header checksum if this packet
11956 			 * is coming back from AH/ESP as we already did it.
11957 			 */
11958 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
11959 				BUMP_MIB(&ip_mib, ipInCksumErrs);
11960 				goto error;
11961 			}
11962 		}
11963 	}
11964 
11965 	/*
11966 	 * Don't verify header checksum if this packet is coming
11967 	 * back from AH/ESP as we already did it.
11968 	 */
11969 	if (!mctl_present) {
11970 		UPDATE_IB_PKT_COUNT(ire);
11971 		ire->ire_last_used_time = lbolt;
11972 	}
11973 
11974 	/* packet part of fragmented IP packet? */
11975 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
11976 	if (u1 & (IPH_MF | IPH_OFFSET))
11977 		goto fragmented;
11978 
11979 	/* u1 = IP header length (20 bytes) */
11980 	u1 = IP_SIMPLE_HDR_LENGTH;
11981 
11982 find_sctp_client:
11983 	/* Pullup if we don't have the sctp common header. */
11984 	len = MBLKL(mp);
11985 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
11986 		if (mp->b_cont == NULL ||
11987 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
11988 			BUMP_MIB(&ip_mib, ipInDiscards);
11989 			goto error;
11990 		}
11991 		ipha = (ipha_t *)mp->b_rptr;
11992 		len = MBLKL(mp);
11993 	}
11994 
11995 	sctph = (sctp_hdr_t *)(rptr + u1);
11996 #ifdef	DEBUG
11997 	if (!skip_sctp_cksum) {
11998 #endif
11999 		pktsum = sctph->sh_chksum;
12000 		sctph->sh_chksum = 0;
12001 		calcsum = sctp_cksum(mp, u1);
12002 		if (calcsum != pktsum) {
12003 			BUMP_MIB(&sctp_mib, sctpChecksumError);
12004 			goto error;
12005 		}
12006 		sctph->sh_chksum = pktsum;
12007 #ifdef	DEBUG	/* skip_sctp_cksum */
12008 	}
12009 #endif
12010 	/* get the ports */
12011 	ports = *(uint32_t *)&sctph->sh_sport;
12012 
12013 	ipif_seqid = ire->ire_ipif->ipif_seqid;
12014 	IRE_REFRELE(ire);
12015 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
12016 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
12017 	if ((connp = sctp_find_conn(&map_src, &map_dst, ports, ipif_seqid,
12018 	    zoneid)) == NULL) {
12019 		/* Check for raw socket or OOTB handling */
12020 		goto no_conn;
12021 	}
12022 
12023 	/* Found a client; up it goes */
12024 	BUMP_MIB(&ip_mib, ipInDelivers);
12025 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
12026 	return;
12027 
12028 no_conn:
12029 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
12030 	    ports, mctl_present, flags, B_TRUE, ipif_seqid, zoneid);
12031 	return;
12032 
12033 ipoptions:
12034 	mp->b_datap->db_struioun.cksum.flags = 0;
12035 	if (!ip_options_cksum(q, first_mp, ipha, ire))
12036 		goto slow_done;
12037 
12038 	UPDATE_IB_PKT_COUNT(ire);
12039 	ire->ire_last_used_time = lbolt;
12040 
12041 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12042 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12043 fragmented:
12044 		if (!ip_rput_fragment(q, &mp, ipha))
12045 			goto slow_done;
12046 		/*
12047 		 * Make sure that first_mp points back to mp as
12048 		 * the mp we came in with could have changed in
12049 		 * ip_rput_fragment().
12050 		 */
12051 		ASSERT(!mctl_present);
12052 		ipha = (ipha_t *)mp->b_rptr;
12053 		first_mp = mp;
12054 	}
12055 
12056 	/* Now we have a complete datagram, destined for this machine. */
12057 	u1 = IPH_HDR_LENGTH(ipha);
12058 	goto find_sctp_client;
12059 #undef  iphs
12060 #undef  rptr
12061 
12062 error:
12063 	freemsg(first_mp);
12064 slow_done:
12065 	IRE_REFRELE(ire);
12066 }
12067 
12068 #define	VER_BITS	0xF0
12069 #define	VERSION_6	0x60
12070 
12071 static boolean_t
12072 ip_rput_multimblk_ipoptions(queue_t *q, mblk_t *mp, ipha_t **iphapp,
12073     ipaddr_t *dstp)
12074 {
12075 	uint_t	opt_len;
12076 	ipha_t *ipha;
12077 	ssize_t len;
12078 	uint_t	pkt_len;
12079 
12080 	IP_STAT(ip_ipoptions);
12081 	ipha = *iphapp;
12082 
12083 #define	rptr    ((uchar_t *)ipha)
12084 	/* Assume no IPv6 packets arrive over the IPv4 queue */
12085 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
12086 		BUMP_MIB(&ip_mib, ipInIPv6);
12087 		freemsg(mp);
12088 		return (B_FALSE);
12089 	}
12090 
12091 	/* multiple mblk or too short */
12092 	pkt_len = ntohs(ipha->ipha_length);
12093 
12094 	/* Get the number of words of IP options in the IP header. */
12095 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
12096 	if (opt_len) {
12097 		/* IP Options present!  Validate and process. */
12098 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
12099 			BUMP_MIB(&ip_mib, ipInHdrErrors);
12100 			goto done;
12101 		}
12102 		/*
12103 		 * Recompute complete header length and make sure we
12104 		 * have access to all of it.
12105 		 */
12106 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
12107 		if (len > (mp->b_wptr - rptr)) {
12108 			if (len > pkt_len) {
12109 				BUMP_MIB(&ip_mib, ipInHdrErrors);
12110 				goto done;
12111 			}
12112 			if (!pullupmsg(mp, len)) {
12113 				BUMP_MIB(&ip_mib, ipInDiscards);
12114 				goto done;
12115 			}
12116 			ipha = (ipha_t *)mp->b_rptr;
12117 		}
12118 		/*
12119 		 * Go off to ip_rput_options which returns the next hop
12120 		 * destination address, which may have been affected
12121 		 * by source routing.
12122 		 */
12123 		IP_STAT(ip_opt);
12124 		if (ip_rput_options(q, mp, ipha, dstp) == -1) {
12125 			return (B_FALSE);
12126 		}
12127 	}
12128 	*iphapp = ipha;
12129 	return (B_TRUE);
12130 done:
12131 	/* clear b_prev - used by ip_mroute_decap */
12132 	mp->b_prev = NULL;
12133 	freemsg(mp);
12134 	return (B_FALSE);
12135 #undef  rptr
12136 }
12137 
12138 /*
12139  * Deal with the fact that there is no ire for the destination.
12140  * The incoming ill (in_ill) is passed in to ip_newroute only
12141  * in the case of packets coming from mobile ip forward tunnel.
12142  * It must be null otherwise.
12143  */
12144 static void
12145 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
12146     ipaddr_t dst)
12147 {
12148 	ipha_t	*ipha;
12149 	ill_t	*ill;
12150 
12151 	ipha = (ipha_t *)mp->b_rptr;
12152 	ill = (ill_t *)q->q_ptr;
12153 
12154 	ASSERT(ill != NULL);
12155 	/*
12156 	 * No IRE for this destination, so it can't be for us.
12157 	 * Unless we are forwarding, drop the packet.
12158 	 * We have to let source routed packets through
12159 	 * since we don't yet know if they are 'ping -l'
12160 	 * packets i.e. if they will go out over the
12161 	 * same interface as they came in on.
12162 	 */
12163 	if (ll_multicast) {
12164 		freemsg(mp);
12165 		return;
12166 	}
12167 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha)) {
12168 		BUMP_MIB(&ip_mib, ipForwProhibits);
12169 		freemsg(mp);
12170 		return;
12171 	}
12172 
12173 	/* Check for Martian addresses */
12174 	if ((in_ill == NULL) && (ip_no_forward(ipha, ill))) {
12175 		freemsg(mp);
12176 		return;
12177 	}
12178 
12179 	/* Mark this packet as having originated externally */
12180 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
12181 
12182 	/*
12183 	 * Clear the indication that this may have a hardware checksum
12184 	 * as we are not using it
12185 	 */
12186 	mp->b_datap->db_struioun.cksum.flags = 0;
12187 
12188 	/*
12189 	 * Now hand the packet to ip_newroute.
12190 	 */
12191 	ip_newroute(q, mp, dst, in_ill, NULL);
12192 }
12193 
12194 /*
12195  * check ip header length and align it.
12196  */
12197 static boolean_t
12198 ip_check_and_align_header(queue_t *q, mblk_t *mp)
12199 {
12200 	ssize_t len;
12201 	ill_t *ill;
12202 	ipha_t	*ipha;
12203 
12204 	len = MBLKL(mp);
12205 
12206 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
12207 		if (!OK_32PTR(mp->b_rptr))
12208 			IP_STAT(ip_notaligned1);
12209 		else
12210 			IP_STAT(ip_notaligned2);
12211 		/* Guard against bogus device drivers */
12212 		if (len < 0) {
12213 			/* clear b_prev - used by ip_mroute_decap */
12214 			mp->b_prev = NULL;
12215 			BUMP_MIB(&ip_mib, ipInHdrErrors);
12216 			freemsg(mp);
12217 			return (B_FALSE);
12218 		}
12219 
12220 		if (ip_rput_pullups++ == 0) {
12221 			ill = (ill_t *)q->q_ptr;
12222 			ipha = (ipha_t *)mp->b_rptr;
12223 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
12224 			    "ip_check_and_align_header: %s forced us to "
12225 			    " pullup pkt, hdr len %ld, hdr addr %p",
12226 			    ill->ill_name, len, ipha);
12227 		}
12228 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
12229 			/* clear b_prev - used by ip_mroute_decap */
12230 			mp->b_prev = NULL;
12231 			BUMP_MIB(&ip_mib, ipInDiscards);
12232 			freemsg(mp);
12233 			return (B_FALSE);
12234 		}
12235 	}
12236 	return (B_TRUE);
12237 }
12238 
12239 static boolean_t
12240 ip_rput_notforus(queue_t **qp, mblk_t *mp, ire_t *ire, ill_t *ill)
12241 {
12242 	ill_group_t	*ill_group;
12243 	ill_group_t	*ire_group;
12244 	queue_t 	*q;
12245 	ill_t		*ire_ill;
12246 	uint_t		ill_ifindex;
12247 
12248 	q = *qp;
12249 	/*
12250 	 * We need to check to make sure the packet came in
12251 	 * on the queue associated with the destination IRE.
12252 	 * Note that for multicast packets and broadcast packets sent to
12253 	 * a broadcast address which is shared between multiple interfaces
12254 	 * we should not do this since we just got a random broadcast ire.
12255 	 */
12256 	if (ire->ire_rfq && ire->ire_type != IRE_BROADCAST) {
12257 		boolean_t check_multi = B_TRUE;
12258 
12259 		/*
12260 		 * This packet came in on an interface other than the
12261 		 * one associated with the destination address.
12262 		 * "Gateway" it to the appropriate interface here.
12263 		 * As long as the ills belong to the same group,
12264 		 * we don't consider them to arriving on the wrong
12265 		 * interface. Thus, when the switch is doing inbound
12266 		 * load spreading, we won't drop packets when we
12267 		 * are doing strict multihoming checks. Note, the
12268 		 * same holds true for 'usesrc groups' where the
12269 		 * destination address may belong to another interface
12270 		 * to allow multipathing to happen
12271 		 */
12272 		ill_group = ill->ill_group;
12273 		ire_ill = (ill_t *)(ire->ire_rfq)->q_ptr;
12274 		ill_ifindex = ill->ill_usesrc_ifindex;
12275 		ire_group = ire_ill->ill_group;
12276 
12277 		/*
12278 		 * If it's part of the same IPMP group, or if it's a legal
12279 		 * address on the 'usesrc' interface, then bypass strict
12280 		 * checks.
12281 		 */
12282 		if (ill_group != NULL && ill_group == ire_group) {
12283 			check_multi = B_FALSE;
12284 		} else if (ill_ifindex != 0 &&
12285 		    ill_ifindex == ire_ill->ill_phyint->phyint_ifindex) {
12286 			check_multi = B_FALSE;
12287 		}
12288 
12289 		if (check_multi &&
12290 		    ip_strict_dst_multihoming &&
12291 		    ((ill->ill_flags &
12292 		    ire->ire_ipif->ipif_ill->ill_flags &
12293 		    ILLF_ROUTER) == 0)) {
12294 			/* Drop packet */
12295 			BUMP_MIB(&ip_mib, ipForwProhibits);
12296 			freemsg(mp);
12297 			ire_refrele(ire);
12298 			return (B_TRUE);
12299 		}
12300 
12301 		/*
12302 		 * Change the queue (for non-virtual destination network
12303 		 * interfaces) and ip_rput_local will be called with the right
12304 		 * queue
12305 		 */
12306 		q = ire->ire_rfq;
12307 	}
12308 	/* Must be broadcast.  We'll take it. */
12309 	*qp = q;
12310 	return (B_FALSE);
12311 }
12312 
12313 static void
12314 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
12315     ill_t *ill, int ll_multicast)
12316 {
12317 	ill_group_t	*ill_group;
12318 	ill_group_t	*ire_group;
12319 	queue_t	*dev_q;
12320 
12321 	ASSERT(ire->ire_stq != NULL);
12322 	if (ll_multicast != 0)
12323 		goto drop_pkt;
12324 
12325 	if (ip_no_forward(ipha, ill))
12326 		goto drop_pkt;
12327 
12328 	ill_group = ill->ill_group;
12329 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
12330 	/*
12331 	 * Check if we want to forward this one at this time.
12332 	 * We allow source routed packets on a host provided that
12333 	 * they go out the same interface or same interface group
12334 	 * as they came in on.
12335 	 *
12336 	 * XXX To be quicker, we may wish to not chase pointers to
12337 	 * get the ILLF_ROUTER flag and instead store the
12338 	 * forwarding policy in the ire.  An unfortunate
12339 	 * side-effect of that would be requiring an ire flush
12340 	 * whenever the ILLF_ROUTER flag changes.
12341 	 */
12342 	if (((ill->ill_flags &
12343 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
12344 	    ILLF_ROUTER) == 0) &&
12345 	    !(ip_source_routed(ipha) && (ire->ire_rfq == q ||
12346 	    (ill_group != NULL && ill_group == ire_group)))) {
12347 		BUMP_MIB(&ip_mib, ipForwProhibits);
12348 		if (ip_source_routed(ipha)) {
12349 			q = WR(q);
12350 			/*
12351 			 * Clear the indication that this may have
12352 			 * hardware checksum as we are not using it.
12353 			 */
12354 			mp->b_datap->db_struioun.cksum.flags = 0;
12355 			icmp_unreachable(q, mp,
12356 			    ICMP_SOURCE_ROUTE_FAILED);
12357 			ire_refrele(ire);
12358 			return;
12359 		}
12360 		goto drop_pkt;
12361 	}
12362 
12363 	/* Packet is being forwarded. Turning off hwcksum flag. */
12364 	mp->b_datap->db_struioun.cksum.flags = 0;
12365 	if (ip_g_send_redirects) {
12366 		/*
12367 		 * Check whether the incoming interface and outgoing
12368 		 * interface is part of the same group. If so,
12369 		 * send redirects.
12370 		 *
12371 		 * Check the source address to see if it originated
12372 		 * on the same logical subnet it is going back out on.
12373 		 * If so, we should be able to send it a redirect.
12374 		 * Avoid sending a redirect if the destination
12375 		 * is directly connected (gw_addr == 0),
12376 		 * or if the packet was source routed out this
12377 		 * interface.
12378 		 */
12379 		ipaddr_t src;
12380 		mblk_t	*mp1;
12381 		ire_t	*src_ire = NULL;
12382 
12383 		/*
12384 		 * Check whether ire_rfq and q are from the same ill
12385 		 * or if they are not same, they at least belong
12386 		 * to the same group. If so, send redirects.
12387 		 */
12388 		if ((ire->ire_rfq == q ||
12389 		    (ill_group != NULL && ill_group == ire_group)) &&
12390 		    (ire->ire_gateway_addr != 0) &&
12391 		    !ip_source_routed(ipha)) {
12392 
12393 			src = ipha->ipha_src;
12394 			src_ire = ire_ftable_lookup(src, 0, 0,
12395 			    IRE_INTERFACE, ire->ire_ipif, NULL, ALL_ZONES,
12396 			    0, MATCH_IRE_IPIF | MATCH_IRE_TYPE);
12397 
12398 			if (src_ire != NULL) {
12399 				/*
12400 				 * The source is directly connected.
12401 				 * Just copy the ip header (which is
12402 				 * in the first mblk)
12403 				 */
12404 				mp1 = copyb(mp);
12405 				if (mp1 != NULL) {
12406 					icmp_send_redirect(WR(q), mp1,
12407 					    ire->ire_gateway_addr);
12408 				}
12409 				ire_refrele(src_ire);
12410 			}
12411 		}
12412 	}
12413 
12414 	dev_q = ire->ire_stq->q_next;
12415 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
12416 		BUMP_MIB(&ip_mib, ipInDiscards);
12417 		freemsg(mp);
12418 		ire_refrele(ire);
12419 		return;
12420 	}
12421 
12422 	ip_rput_forward(ire, ipha, mp, ill);
12423 	IRE_REFRELE(ire);
12424 	return;
12425 
12426 drop_pkt:
12427 	ire_refrele(ire);
12428 	ip2dbg(("ip_rput_forward: drop pkt\n"));
12429 	freemsg(mp);
12430 }
12431 
12432 static boolean_t
12433 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t **irep, ipha_t *ipha,
12434     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
12435 {
12436 	queue_t		*q;
12437 	ire_t		*ire;
12438 
12439 	q = *qp;
12440 	ire = *irep;
12441 
12442 	/*
12443 	 * Clear the indication that this may have hardware
12444 	 * checksum as we are not using it.
12445 	 */
12446 	mp->b_datap->db_struioun.cksum.flags = 0;
12447 
12448 	/*
12449 	 * Directed broadcast forwarding: if the packet came in over a
12450 	 * different interface then it is routed out over we can forward it.
12451 	 */
12452 	if (ipha->ipha_protocol == IPPROTO_TCP) {
12453 		ire_refrele(ire);
12454 		freemsg(mp);
12455 		BUMP_MIB(&ip_mib, ipInDiscards);
12456 		return (B_TRUE);
12457 	}
12458 	/*
12459 	 * For multicast we have set dst to be INADDR_BROADCAST
12460 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
12461 	 * only for broadcast packets.
12462 	 */
12463 	if (!CLASSD(ipha->ipha_dst)) {
12464 		ire_t *new_ire;
12465 		ipif_t *ipif;
12466 		/*
12467 		 * For ill groups, as the switch duplicates broadcasts
12468 		 * across all the ports, we need to filter out and
12469 		 * send up only one copy. There is one copy for every
12470 		 * broadcast address on each ill. Thus, we look for a
12471 		 * specific IRE on this ill and look at IRE_MARK_NORECV
12472 		 * later to see whether this ill is eligible to receive
12473 		 * them or not. ill_nominate_bcast_rcv() nominates only
12474 		 * one set of IREs for receiving.
12475 		 */
12476 
12477 		ipif = ipif_get_next_ipif(NULL, ill);
12478 		if (ipif == NULL) {
12479 			ire_refrele(ire);
12480 			freemsg(mp);
12481 			BUMP_MIB(&ip_mib, ipInDiscards);
12482 			return (B_TRUE);
12483 		}
12484 		new_ire = ire_ctable_lookup(dst, 0, 0,
12485 		    ipif, ALL_ZONES, MATCH_IRE_ILL);
12486 		ipif_refrele(ipif);
12487 
12488 		if (new_ire != NULL) {
12489 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
12490 				ire_refrele(ire);
12491 				ire_refrele(new_ire);
12492 				freemsg(mp);
12493 				BUMP_MIB(&ip_mib, ipInDiscards);
12494 				return (B_TRUE);
12495 			}
12496 			/*
12497 			 * In the special case of multirouted broadcast
12498 			 * packets, we unconditionally need to "gateway"
12499 			 * them to the appropriate interface here.
12500 			 * In the normal case, this cannot happen, because
12501 			 * there is no broadcast IRE tagged with the
12502 			 * RTF_MULTIRT flag.
12503 			 */
12504 			if (new_ire->ire_flags & RTF_MULTIRT) {
12505 				ire_refrele(new_ire);
12506 				if (ire->ire_rfq != NULL) {
12507 					q = ire->ire_rfq;
12508 					*qp = q;
12509 				}
12510 			} else {
12511 				ire_refrele(ire);
12512 				ire = new_ire;
12513 			}
12514 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
12515 			if (!ip_g_forward_directed_bcast) {
12516 				/*
12517 				 * Free the message if
12518 				 * ip_g_forward_directed_bcast is turned
12519 				 * off for non-local broadcast.
12520 				 */
12521 				ire_refrele(ire);
12522 				freemsg(mp);
12523 				BUMP_MIB(&ip_mib, ipInDiscards);
12524 				return (B_TRUE);
12525 			}
12526 		} else {
12527 			/*
12528 			 * This CGTP packet successfully passed the
12529 			 * CGTP filter, but the related CGTP
12530 			 * broadcast IRE has not been found,
12531 			 * meaning that the redundant ipif is
12532 			 * probably down. However, if we discarded
12533 			 * this packet, its duplicate would be
12534 			 * filtered out by the CGTP filter so none
12535 			 * of them would get through. So we keep
12536 			 * going with this one.
12537 			 */
12538 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
12539 			if (ire->ire_rfq != NULL) {
12540 				q = ire->ire_rfq;
12541 				*qp = q;
12542 			}
12543 		}
12544 	}
12545 	if (ip_g_forward_directed_bcast && ll_multicast == 0) {
12546 		/*
12547 		 * Verify that there are not more then one
12548 		 * IRE_BROADCAST with this broadcast address which
12549 		 * has ire_stq set.
12550 		 * TODO: simplify, loop over all IRE's
12551 		 */
12552 		ire_t	*ire1;
12553 		int	num_stq = 0;
12554 		mblk_t	*mp1;
12555 
12556 		/* Find the first one with ire_stq set */
12557 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
12558 		for (ire1 = ire; ire1 &&
12559 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
12560 		    ire1 = ire1->ire_next)
12561 			;
12562 		if (ire1) {
12563 			ire_refrele(ire);
12564 			ire = ire1;
12565 			IRE_REFHOLD(ire);
12566 		}
12567 
12568 		/* Check if there are additional ones with stq set */
12569 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
12570 			if (ire->ire_addr != ire1->ire_addr)
12571 				break;
12572 			if (ire1->ire_stq) {
12573 				num_stq++;
12574 				break;
12575 			}
12576 		}
12577 		rw_exit(&ire->ire_bucket->irb_lock);
12578 		if (num_stq == 1 && ire->ire_stq != NULL) {
12579 			ip1dbg(("ip_rput_process_broadcast: directed "
12580 			    "broadcast to 0x%x\n",
12581 			    ntohl(ire->ire_addr)));
12582 			mp1 = copymsg(mp);
12583 			if (mp1) {
12584 				switch (ipha->ipha_protocol) {
12585 				case IPPROTO_UDP:
12586 					ip_udp_input(q, mp1, ipha, ire, ill);
12587 					break;
12588 				default:
12589 					ip_proto_input(q, mp1, ipha, ire, ill);
12590 					break;
12591 				}
12592 			}
12593 			/*
12594 			 * Adjust ttl to 2 (1+1 - the forward engine
12595 			 * will decrement it by one.
12596 			 */
12597 			if (ip_csum_hdr(ipha)) {
12598 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12599 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
12600 				freemsg(mp);
12601 				ire_refrele(ire);
12602 				return (B_TRUE);
12603 			}
12604 			ipha->ipha_ttl = ip_broadcast_ttl + 1;
12605 			ipha->ipha_hdr_checksum = 0;
12606 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
12607 			ip_rput_process_forward(q, mp, ire, ipha,
12608 			    ill, ll_multicast);
12609 			return (B_TRUE);
12610 		}
12611 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
12612 		    ntohl(ire->ire_addr)));
12613 	}
12614 
12615 	*irep = ire;
12616 	return (B_FALSE);
12617 }
12618 
12619 /* ARGSUSED */
12620 static boolean_t
12621 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
12622     int *ll_multicast, ipaddr_t *dstp)
12623 {
12624 	/*
12625 	 * Forward packets only if we have joined the allmulti
12626 	 * group on this interface.
12627 	 */
12628 	if (ip_g_mrouter && ill->ill_join_allmulti) {
12629 		int retval;
12630 
12631 		/*
12632 		 * Clear the indication that this may have hardware
12633 		 * checksum as we are not using it.
12634 		 */
12635 		mp->b_datap->db_struioun.cksum.flags = 0;
12636 		retval = ip_mforward(ill, ipha, mp);
12637 		/* ip_mforward updates mib variables if needed */
12638 		/* clear b_prev - used by ip_mroute_decap */
12639 		mp->b_prev = NULL;
12640 
12641 		switch (retval) {
12642 		case 0:
12643 			/*
12644 			 * pkt is okay and arrived on phyint.
12645 			 *
12646 			 * If we are running as a multicast router
12647 			 * we need to see all IGMP and/or PIM packets.
12648 			 */
12649 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
12650 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
12651 				goto done;
12652 			}
12653 			break;
12654 		case -1:
12655 			/* pkt is mal-formed, toss it */
12656 			goto drop_pkt;
12657 		case 1:
12658 			/* pkt is okay and arrived on a tunnel */
12659 			/*
12660 			 * If we are running a multicast router
12661 			 *  we need to see all igmp packets.
12662 			 */
12663 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
12664 				*dstp = INADDR_BROADCAST;
12665 				*ll_multicast = 1;
12666 				return (B_FALSE);
12667 			}
12668 
12669 			goto drop_pkt;
12670 		}
12671 	}
12672 
12673 	ILM_WALKER_HOLD(ill);
12674 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
12675 		/*
12676 		 * This might just be caused by the fact that
12677 		 * multiple IP Multicast addresses map to the same
12678 		 * link layer multicast - no need to increment counter!
12679 		 */
12680 		ILM_WALKER_RELE(ill);
12681 		freemsg(mp);
12682 		return (B_TRUE);
12683 	}
12684 	ILM_WALKER_RELE(ill);
12685 done:
12686 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
12687 	/*
12688 	 * This assumes the we deliver to all streams for multicast
12689 	 * and broadcast packets.
12690 	 */
12691 	*dstp = INADDR_BROADCAST;
12692 	*ll_multicast = 1;
12693 	return (B_FALSE);
12694 drop_pkt:
12695 	ip2dbg(("ip_rput: drop pkt\n"));
12696 	freemsg(mp);
12697 	return (B_TRUE);
12698 }
12699 
12700 static boolean_t
12701 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
12702     int *ll_multicast, mblk_t **mpp)
12703 {
12704 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
12705 	boolean_t must_copy = B_FALSE;
12706 	struct iocblk   *iocp;
12707 	ipha_t		*ipha;
12708 
12709 #define	rptr    ((uchar_t *)ipha)
12710 
12711 	first_mp = *first_mpp;
12712 	mp = *mpp;
12713 
12714 	ASSERT(first_mp == mp);
12715 
12716 	/*
12717 	 * if db_ref > 1 then copymsg and free original. Packet may be
12718 	 * changed and do not want other entity who has a reference to this
12719 	 * message to trip over the changes. This is a blind change because
12720 	 * trying to catch all places that might change packet is too
12721 	 * difficult (since it may be a module above this one)
12722 	 *
12723 	 * This corresponds to the non-fast path case. We walk down the full
12724 	 * chain in this case, and check the db_ref count of all the dblks,
12725 	 * and do a copymsg if required. It is possible that the db_ref counts
12726 	 * of the data blocks in the mblk chain can be different.
12727 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
12728 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
12729 	 * 'snoop' is running.
12730 	 */
12731 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
12732 		if (mp1->b_datap->db_ref > 1) {
12733 			must_copy = B_TRUE;
12734 			break;
12735 		}
12736 	}
12737 
12738 	if (must_copy) {
12739 		mp1 = copymsg(mp);
12740 		if (mp1 == NULL) {
12741 			for (mp1 = mp; mp1 != NULL;
12742 			    mp1 = mp1->b_cont) {
12743 				mp1->b_next = NULL;
12744 				mp1->b_prev = NULL;
12745 			}
12746 			freemsg(mp);
12747 			BUMP_MIB(&ip_mib, ipInDiscards);
12748 			return (B_TRUE);
12749 		}
12750 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
12751 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
12752 			/* Copy b_next - used in M_BREAK messages */
12753 			to_mp->b_next = from_mp->b_next;
12754 			from_mp->b_next = NULL;
12755 			/* Copy b_prev - used by ip_mroute_decap */
12756 			to_mp->b_prev = from_mp->b_prev;
12757 			from_mp->b_prev = NULL;
12758 		}
12759 		*first_mpp = first_mp = mp1;
12760 		freemsg(mp);
12761 		mp = mp1;
12762 		*mpp = mp1;
12763 	}
12764 
12765 	ipha = (ipha_t *)mp->b_rptr;
12766 
12767 	/*
12768 	 * previous code has a case for M_DATA.
12769 	 * We want to check how that happens.
12770 	 */
12771 	ASSERT(first_mp->b_datap->db_type != M_DATA);
12772 	switch (first_mp->b_datap->db_type) {
12773 	case M_PROTO:
12774 	case M_PCPROTO:
12775 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
12776 		    DL_UNITDATA_IND) {
12777 			/* Go handle anything other than data elsewhere. */
12778 			ip_rput_dlpi(q, mp);
12779 			return (B_TRUE);
12780 		}
12781 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
12782 		/* Ditch the DLPI header. */
12783 		mp1 = mp->b_cont;
12784 		ASSERT(first_mp == mp);
12785 		*first_mpp = mp1;
12786 		freeb(mp);
12787 		*mpp = mp1;
12788 		return (B_FALSE);
12789 	case M_BREAK:
12790 		/*
12791 		 * A packet arrives as M_BREAK following a cycle through
12792 		 * ip_rput, ip_newroute, ... and finally ire_add_then_send.
12793 		 * This is an IP datagram sans lower level header.
12794 		 * M_BREAK are also used to pass back in multicast packets
12795 		 * that are encapsulated with a source route.
12796 		 */
12797 		/* Ditch the M_BREAK mblk */
12798 		mp1 = mp->b_cont;
12799 		ASSERT(first_mp == mp);
12800 		*first_mpp = mp1;
12801 		freeb(mp);
12802 		mp = mp1;
12803 		mp->b_next = NULL;
12804 		*mpp = mp;
12805 		*ll_multicast = 0;
12806 		return (B_FALSE);
12807 	case M_IOCACK:
12808 		ip1dbg(("got iocack "));
12809 		iocp = (struct iocblk *)mp->b_rptr;
12810 		switch (iocp->ioc_cmd) {
12811 		case DL_IOC_HDR_INFO:
12812 			ill = (ill_t *)q->q_ptr;
12813 			ill_fastpath_ack(ill, mp);
12814 			return (B_TRUE);
12815 		case SIOCSTUNPARAM:
12816 		case OSIOCSTUNPARAM:
12817 			/* Go through qwriter_ip */
12818 			break;
12819 		case SIOCGTUNPARAM:
12820 		case OSIOCGTUNPARAM:
12821 			ip_rput_other(NULL, q, mp, NULL);
12822 			return (B_TRUE);
12823 		default:
12824 			putnext(q, mp);
12825 			return (B_TRUE);
12826 		}
12827 		/* FALLTHRU */
12828 	case M_ERROR:
12829 	case M_HANGUP:
12830 		/*
12831 		 * Since this is on the ill stream we unconditionally
12832 		 * bump up the refcount
12833 		 */
12834 		ill_refhold(ill);
12835 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
12836 		    B_FALSE);
12837 		return (B_TRUE);
12838 	case M_CTL:
12839 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
12840 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
12841 			IPHADA_M_CTL)) {
12842 			/*
12843 			 * It's an IPsec accelerated packet.
12844 			 * Make sure that the ill from which we received the
12845 			 * packet has enabled IPsec hardware acceleration.
12846 			 */
12847 			if (!(ill->ill_capabilities &
12848 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
12849 				/* IPsec kstats: bean counter */
12850 				freemsg(mp);
12851 				return (B_TRUE);
12852 			}
12853 
12854 			/*
12855 			 * Make mp point to the mblk following the M_CTL,
12856 			 * then process according to type of mp.
12857 			 * After this processing, first_mp will point to
12858 			 * the data-attributes and mp to the pkt following
12859 			 * the M_CTL.
12860 			 */
12861 			mp = first_mp->b_cont;
12862 			if (mp == NULL) {
12863 				freemsg(first_mp);
12864 				return (B_TRUE);
12865 			}
12866 			/*
12867 			 * A Hardware Accelerated packet can only be M_DATA
12868 			 * ESP or AH packet.
12869 			 */
12870 			if (mp->b_datap->db_type != M_DATA) {
12871 				/* non-M_DATA IPsec accelerated packet */
12872 				IPSECHW_DEBUG(IPSECHW_PKT,
12873 				    ("non-M_DATA IPsec accelerated pkt\n"));
12874 				freemsg(first_mp);
12875 				return (B_TRUE);
12876 			}
12877 			ipha = (ipha_t *)mp->b_rptr;
12878 			if (ipha->ipha_protocol != IPPROTO_AH &&
12879 			    ipha->ipha_protocol != IPPROTO_ESP) {
12880 				IPSECHW_DEBUG(IPSECHW_PKT,
12881 				    ("non-M_DATA IPsec accelerated pkt\n"));
12882 				freemsg(first_mp);
12883 				return (B_TRUE);
12884 			}
12885 			*mpp = mp;
12886 			return (B_FALSE);
12887 		}
12888 		putnext(q, mp);
12889 		return (B_TRUE);
12890 	case M_FLUSH:
12891 		if (*mp->b_rptr & FLUSHW) {
12892 			*mp->b_rptr &= ~FLUSHR;
12893 			qreply(q, mp);
12894 			return (B_TRUE);
12895 		}
12896 		freemsg(mp);
12897 		return (B_TRUE);
12898 	case M_IOCNAK:
12899 		ip1dbg(("got iocnak "));
12900 		iocp = (struct iocblk *)mp->b_rptr;
12901 		switch (iocp->ioc_cmd) {
12902 		case DL_IOC_HDR_INFO:
12903 		case SIOCSTUNPARAM:
12904 		case OSIOCSTUNPARAM:
12905 			/*
12906 			 * Since this is on the ill stream we unconditionally
12907 			 * bump up the refcount
12908 			 */
12909 			ill_refhold(ill);
12910 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
12911 			    CUR_OP, B_FALSE);
12912 			return (B_TRUE);
12913 		case SIOCGTUNPARAM:
12914 		case OSIOCGTUNPARAM:
12915 			ip_rput_other(NULL, q, mp, NULL);
12916 			return (B_TRUE);
12917 		default:
12918 			break;
12919 		}
12920 		/* FALLTHRU */
12921 	default:
12922 		putnext(q, mp);
12923 		return (B_TRUE);
12924 	}
12925 }
12926 
12927 /* Read side put procedure.  Packets coming from the wire arrive here. */
12928 void
12929 ip_rput(queue_t *q, mblk_t *mp)
12930 {
12931 	ill_t		*ill;
12932 
12933 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
12934 
12935 	ill = (ill_t *)q->q_ptr;
12936 
12937 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
12938 		union DL_primitives *dl;
12939 
12940 		/*
12941 		 * Things are opening or closing. Only accept DLPI control
12942 		 * messages. In the open case, the ill->ill_ipif has not yet
12943 		 * been created. In the close case, things hanging off the
12944 		 * ill could have been freed already. In either case it
12945 		 * may not be safe to proceed further.
12946 		 */
12947 
12948 		dl = (union DL_primitives *)mp->b_rptr;
12949 		if ((mp->b_datap->db_type != M_PCPROTO) ||
12950 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
12951 			/*
12952 			 * Also SIOC[GS]TUN* ioctls can come here.
12953 			 */
12954 			ip_ioctl_freemsg(mp);
12955 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
12956 			    "ip_input_end: q %p (%S)", q, "uninit");
12957 			return;
12958 		}
12959 	}
12960 
12961 	/*
12962 	 * if db_ref > 1 then copymsg and free original. Packet may be
12963 	 * changed and we do not want the other entity who has a reference to
12964 	 * this message to trip over the changes. This is a blind change because
12965 	 * trying to catch all places that might change the packet is too
12966 	 * difficult.
12967 	 *
12968 	 * This corresponds to the fast path case, where we have a chain of
12969 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
12970 	 * in the mblk chain. There doesn't seem to be a reason why a device
12971 	 * driver would send up data with varying db_ref counts in the mblk
12972 	 * chain. In any case the Fast path is a private interface, and our
12973 	 * drivers don't do such a thing. Given the above assumption, there is
12974 	 * no need to walk down the entire mblk chain (which could have a
12975 	 * potential performance problem)
12976 	 */
12977 	if (mp->b_datap->db_ref > 1) {
12978 		mblk_t  *mp1;
12979 		boolean_t adjusted = B_FALSE;
12980 		IP_STAT(ip_db_ref);
12981 
12982 		/*
12983 		 * The IP_RECVSLLA option depends on having the link layer
12984 		 * header. First check that:
12985 		 * a> the underlying device is of type ether, since this
12986 		 * option is currently supported only over ethernet.
12987 		 * b> there is enough room to copy over the link layer header.
12988 		 *
12989 		 * Once the checks are done, adjust rptr so that the link layer
12990 		 * header will be copied via copymsg. Note that, IFT_ETHER may
12991 		 * be returned by some non-ethernet drivers but in this case the
12992 		 * second check will fail.
12993 		 */
12994 		if (ill->ill_type == IFT_ETHER &&
12995 		    (mp->b_rptr - mp->b_datap->db_base) >=
12996 		    sizeof (struct ether_header)) {
12997 			mp->b_rptr -= sizeof (struct ether_header);
12998 			adjusted = B_TRUE;
12999 		}
13000 		mp1 = copymsg(mp);
13001 		if (mp1 == NULL) {
13002 			/* Clear b_next - used in M_BREAK messages */
13003 			mp->b_next = NULL;
13004 			/* clear b_prev - used by ip_mroute_decap */
13005 			mp->b_prev = NULL;
13006 			freemsg(mp);
13007 			BUMP_MIB(&ip_mib, ipInDiscards);
13008 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13009 			    "ip_rput_end: q %p (%S)", q, "copymsg");
13010 			return;
13011 		}
13012 		if (adjusted) {
13013 			/*
13014 			 * Copy is done. Restore the pointer in the _new_ mblk
13015 			 */
13016 			mp1->b_rptr += sizeof (struct ether_header);
13017 		}
13018 		/* Copy b_next - used in M_BREAK messages */
13019 		mp1->b_next = mp->b_next;
13020 		mp->b_next = NULL;
13021 		/* Copy b_prev - used by ip_mroute_decap */
13022 		mp1->b_prev = mp->b_prev;
13023 		mp->b_prev = NULL;
13024 		freemsg(mp);
13025 		mp = mp1;
13026 	}
13027 
13028 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13029 	    "ip_rput_end: q %p (%S)", q, "end");
13030 
13031 	ip_input(ill, NULL, mp, 0);
13032 }
13033 
13034 /*
13035  * Direct read side procedure capable of dealing with chains. GLDv3 based
13036  * drivers call this function directly with mblk chains while STREAMS
13037  * read side procedure ip_rput() calls this for single packet with ip_ring
13038  * set to NULL to process one packet at a time.
13039  *
13040  * The ill will always be valid if this function is called directly from
13041  * the driver.
13042  */
13043 /*ARGSUSED*/
13044 void
13045 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain, size_t hdrlen)
13046 {
13047 	ipaddr_t		dst;
13048 	ire_t			*ire;
13049 	ipha_t			*ipha;
13050 	uint_t			pkt_len;
13051 	ssize_t			len;
13052 	uint_t			opt_len;
13053 	int			ll_multicast;
13054 	int			cgtp_flt_pkt;
13055 	queue_t			*q = ill->ill_rq;
13056 	squeue_t		*curr_sqp = NULL;
13057 	mblk_t 			*head = NULL;
13058 	mblk_t			*tail = NULL;
13059 	mblk_t			*first_mp;
13060 	mblk_t 			*mp;
13061 	int			cnt = 0;
13062 
13063 	ASSERT(mp_chain != NULL);
13064 	ASSERT(ill != NULL);
13065 
13066 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
13067 
13068 #define	rptr	((uchar_t *)ipha)
13069 
13070 	while (mp_chain != NULL) {
13071 		first_mp = mp = mp_chain;
13072 		mp_chain = mp_chain->b_next;
13073 		mp->b_next = NULL;
13074 		ll_multicast = 0;
13075 		ire = NULL;
13076 
13077 		/*
13078 		 * ip_input fast path
13079 		 */
13080 
13081 		/* mblk type is not M_DATA */
13082 		if (mp->b_datap->db_type != M_DATA) {
13083 			if (ip_rput_process_notdata(q, &first_mp, ill,
13084 			    &ll_multicast, &mp))
13085 				continue;
13086 		}
13087 
13088 		ASSERT(mp->b_datap->db_type == M_DATA);
13089 		ASSERT(mp->b_datap->db_ref == 1);
13090 
13091 		/*
13092 		 * Invoke the CGTP (multirouting) filtering module to process
13093 		 * the incoming packet. Packets identified as duplicates
13094 		 * must be discarded. Filtering is active only if the
13095 		 * the ip_cgtp_filter ndd variable is non-zero.
13096 		 */
13097 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
13098 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL)) {
13099 			cgtp_flt_pkt =
13100 			    ip_cgtp_filter_ops->cfo_filter_fp(q, mp);
13101 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
13102 				freemsg(first_mp);
13103 				continue;
13104 			}
13105 		}
13106 
13107 		ipha = (ipha_t *)mp->b_rptr;
13108 		len = mp->b_wptr - rptr;
13109 
13110 		BUMP_MIB(&ip_mib, ipInReceives);
13111 
13112 		/*
13113 		 * IP header ptr not aligned?
13114 		 * OR IP header not complete in first mblk
13115 		 */
13116 		if (!OK_32PTR(rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13117 			if (!ip_check_and_align_header(q, mp))
13118 				continue;
13119 			ipha = (ipha_t *)mp->b_rptr;
13120 			len = mp->b_wptr - rptr;
13121 		}
13122 
13123 		/* multiple mblk or too short */
13124 		pkt_len = ntohs(ipha->ipha_length);
13125 		len -= pkt_len;
13126 		if (len != 0) {
13127 			/*
13128 			 * Make sure we have data length consistent
13129 			 * with the IP header.
13130 			 */
13131 			if (mp->b_cont == NULL) {
13132 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
13133 					BUMP_MIB(&ip_mib, ipInHdrErrors);
13134 					ip2dbg(("ip_input: drop pkt\n"));
13135 					freemsg(mp);
13136 					continue;
13137 				}
13138 				mp->b_wptr = rptr + pkt_len;
13139 			} else if (len += msgdsize(mp->b_cont)) {
13140 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
13141 					BUMP_MIB(&ip_mib, ipInHdrErrors);
13142 					ip2dbg(("ip_input: drop pkt\n"));
13143 					freemsg(mp);
13144 					continue;
13145 				}
13146 				(void) adjmsg(mp, -len);
13147 				IP_STAT(ip_multimblk3);
13148 			}
13149 		}
13150 
13151 		if (ip_loopback_src_or_dst(ipha, ill)) {
13152 			ip2dbg(("ip_input: drop pkt\n"));
13153 			freemsg(mp);
13154 			continue;
13155 		}
13156 
13157 		opt_len = ipha->ipha_version_and_hdr_length -
13158 		    IP_SIMPLE_HDR_VERSION;
13159 		/* IP version bad or there are IP options */
13160 		if (opt_len) {
13161 			if (len != 0)
13162 				IP_STAT(ip_multimblk4);
13163 			else
13164 				IP_STAT(ip_ipoptions);
13165 			if (!ip_rput_multimblk_ipoptions(q, mp, &ipha, &dst))
13166 				continue;
13167 		} else {
13168 			dst = ipha->ipha_dst;
13169 		}
13170 
13171 		/*
13172 		 * If rsvpd is running, let RSVP daemon handle its processing
13173 		 * and forwarding of RSVP multicast/unicast packets.
13174 		 * If rsvpd is not running but mrouted is running, RSVP
13175 		 * multicast packets are forwarded as multicast traffic
13176 		 * and RSVP unicast packets are forwarded by unicast router.
13177 		 * If neither rsvpd nor mrouted is running, RSVP multicast
13178 		 * packets are not forwarded, but the unicast packets are
13179 		 * forwarded like unicast traffic.
13180 		 */
13181 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
13182 		    ipcl_proto_search(IPPROTO_RSVP) != NULL) {
13183 			/* RSVP packet and rsvpd running. Treat as ours */
13184 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
13185 			/*
13186 			 * This assumes that we deliver to all streams for
13187 			 * multicast and broadcast packets.
13188 			 * We have to force ll_multicast to 1 to handle the
13189 			 * M_DATA messages passed in from ip_mroute_decap.
13190 			 */
13191 			dst = INADDR_BROADCAST;
13192 			ll_multicast = 1;
13193 		} else if (CLASSD(dst)) {
13194 			/* packet is multicast */
13195 			mp->b_next = NULL;
13196 			if (ip_rput_process_multicast(q, mp, ill, ipha,
13197 			    &ll_multicast, &dst))
13198 				continue;
13199 		}
13200 
13201 
13202 		/*
13203 		 * Check if the packet is coming from the Mobile IP
13204 		 * forward tunnel interface
13205 		 */
13206 		if (ill->ill_srcif_refcnt > 0) {
13207 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
13208 			    NULL, ill, MATCH_IRE_TYPE);
13209 			if (ire != NULL && ire->ire_dlureq_mp == NULL &&
13210 			    ire->ire_ipif->ipif_net_type ==
13211 			    IRE_IF_RESOLVER) {
13212 				/* We need to resolve the link layer info */
13213 				ire_refrele(ire);
13214 				ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
13215 				    ll_multicast, dst);
13216 				continue;
13217 			}
13218 		}
13219 
13220 		if (ire == NULL)
13221 			ire = ire_cache_lookup(dst, ALL_ZONES);
13222 
13223 		/*
13224 		 * If mipagent is running and reverse tunnel is created as per
13225 		 * mobile node request, then any packet coming through the
13226 		 * incoming interface from the mobile-node, should be reverse
13227 		 * tunneled to it's home agent except those that are destined
13228 		 * to foreign agent only.
13229 		 * This needs source address based ire lookup. The routing
13230 		 * entries for source address based lookup are only created by
13231 		 * mipagent program only when a reverse tunnel is created.
13232 		 * Reference : RFC2002, RFC2344
13233 		 */
13234 		if (ill->ill_mrtun_refcnt > 0) {
13235 			ipaddr_t	srcaddr;
13236 			ire_t		*tmp_ire;
13237 
13238 			tmp_ire = ire;	/* Save, we might need it later */
13239 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
13240 			    ire->ire_type != IRE_BROADCAST)) {
13241 				srcaddr = ipha->ipha_src;
13242 				ire = ire_mrtun_lookup(srcaddr, ill);
13243 				if (ire != NULL) {
13244 					/*
13245 					 * Should not be getting iphada packet
13246 					 * here. we should only get those for
13247 					 * IRE_LOCAL traffic, excluded above.
13248 					 * Fail-safe (drop packet) in the event
13249 					 * hardware is misbehaving.
13250 					 */
13251 					if (first_mp != mp) {
13252 						/* IPsec KSTATS: beancount me */
13253 						freemsg(first_mp);
13254 					} else {
13255 						/*
13256 						 * This packet must be forwarded
13257 						 * to Reverse Tunnel
13258 						 */
13259 						ip_mrtun_forward(ire, ill, mp);
13260 					}
13261 					ire_refrele(ire);
13262 					if (tmp_ire != NULL)
13263 						ire_refrele(tmp_ire);
13264 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13265 					    "ip_input_end: q %p (%S)",
13266 					    q, "uninit");
13267 					continue;
13268 				}
13269 			}
13270 			/*
13271 			 * If this packet is from a non-mobilenode  or a
13272 			 * mobile-node which does not request reverse
13273 			 * tunnel service
13274 			 */
13275 			ire = tmp_ire;
13276 		}
13277 
13278 
13279 		/*
13280 		 * If we reach here that means the incoming packet satisfies
13281 		 * one of the following conditions:
13282 		 *   - packet is from a mobile node which does not request
13283 		 *	reverse tunnel
13284 		 *   - packet is from a non-mobile node, which is the most
13285 		 *	common case
13286 		 *   - packet is from a reverse tunnel enabled mobile node
13287 		 *	and destined to foreign agent only
13288 		 */
13289 
13290 		if (ire == NULL) {
13291 			/*
13292 			 * No IRE for this destination, so it can't be for us.
13293 			 * Unless we are forwarding, drop the packet.
13294 			 * We have to let source routed packets through
13295 			 * since we don't yet know if they are 'ping -l'
13296 			 * packets i.e. if they will go out over the
13297 			 * same interface as they came in on.
13298 			 */
13299 			ip_rput_noire(q, NULL, mp, ll_multicast, dst);
13300 			continue;
13301 		}
13302 
13303 		/* broadcast? */
13304 		if (ire->ire_type == IRE_BROADCAST) {
13305 			if (ip_rput_process_broadcast(&q, mp, &ire, ipha, ill,
13306 			    dst, cgtp_flt_pkt, ll_multicast)) {
13307 				continue;
13308 			}
13309 		} else if (ire->ire_stq != NULL) {
13310 			/* fowarding? */
13311 			ip_rput_process_forward(q, mp, ire, ipha, ill,
13312 			    ll_multicast);
13313 			continue;
13314 		}
13315 
13316 		/* packet not for us */
13317 		if (ire->ire_rfq != q) {
13318 			if (ip_rput_notforus(&q, mp, ire, ill)) {
13319 				continue;
13320 			}
13321 		}
13322 
13323 		switch (ipha->ipha_protocol) {
13324 		case IPPROTO_TCP:
13325 			ASSERT(first_mp == mp);
13326 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
13327 				mp, 0, q, ip_ring)) != NULL) {
13328 				if (curr_sqp == NULL) {
13329 					curr_sqp = GET_SQUEUE(mp);
13330 					ASSERT(cnt == 0);
13331 					cnt++;
13332 					head = tail = mp;
13333 				} else if (curr_sqp == GET_SQUEUE(mp)) {
13334 					ASSERT(tail != NULL);
13335 					cnt++;
13336 					tail->b_next = mp;
13337 					tail = mp;
13338 				} else {
13339 					/*
13340 					 * A different squeue. Send the
13341 					 * chain for the previous squeue on
13342 					 * its way. This shouldn't happen
13343 					 * often unless interrupt binding
13344 					 * changes.
13345 					 */
13346 					IP_STAT(ip_input_multi_squeue);
13347 					squeue_enter_chain(curr_sqp, head,
13348 					    tail, cnt, SQTAG_IP_INPUT);
13349 					curr_sqp = GET_SQUEUE(mp);
13350 					head = mp;
13351 					tail = mp;
13352 					cnt = 1;
13353 				}
13354 			}
13355 			IRE_REFRELE(ire);
13356 			continue;
13357 		case IPPROTO_UDP:
13358 			ASSERT(first_mp == mp);
13359 			ip_udp_input(q, mp, ipha, ire, ill);
13360 			IRE_REFRELE(ire);
13361 			continue;
13362 		case IPPROTO_SCTP:
13363 			ASSERT(first_mp == mp);
13364 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
13365 			    q, dst);
13366 			continue;
13367 		default:
13368 			ip_proto_input(q, first_mp, ipha, ire, ill);
13369 			IRE_REFRELE(ire);
13370 			continue;
13371 		}
13372 	}
13373 
13374 	if (head != NULL)
13375 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
13376 
13377 	/*
13378 	 * This code is there just to make netperf/ttcp look good.
13379 	 *
13380 	 * Its possible that after being in polling mode (and having cleared
13381 	 * the backlog), squeues have turned the interrupt frequency higher
13382 	 * to improve latency at the expense of more CPU utilization (less
13383 	 * packets per interrupts or more number of interrupts). Workloads
13384 	 * like ttcp/netperf do manage to tickle polling once in a while
13385 	 * but for the remaining time, stay in higher interrupt mode since
13386 	 * their packet arrival rate is pretty uniform and this shows up
13387 	 * as higher CPU utilization. Since people care about CPU utilization
13388 	 * while running netperf/ttcp, turn the interrupt frequency back to
13389 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
13390 	 */
13391 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
13392 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
13393 			ip_ring->rr_poll_state &= ~ILL_POLLING;
13394 			ip_ring->rr_blank(ip_ring->rr_handle,
13395 			    ip_ring->rr_normal_blank_time,
13396 			    ip_ring->rr_normal_pkt_cnt);
13397 		}
13398 	}
13399 
13400 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13401 	    "ip_input_end: q %p (%S)", q, "end");
13402 #undef	rptr
13403 }
13404 
13405 static void
13406 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
13407     t_uscalar_t err)
13408 {
13409 	if (dl_err == DL_SYSERR) {
13410 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
13411 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
13412 		    ill->ill_name, dlpi_prim_str(prim), err);
13413 		return;
13414 	}
13415 
13416 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
13417 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
13418 	    dlpi_err_str(dl_err));
13419 }
13420 
13421 /*
13422  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
13423  * than DL_UNITDATA_IND messages. If we need to process this message
13424  * exclusively, we call qwriter_ip, in which case we also need to call
13425  * ill_refhold before that, since qwriter_ip does an ill_refrele.
13426  */
13427 void
13428 ip_rput_dlpi(queue_t *q, mblk_t *mp)
13429 {
13430 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
13431 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
13432 	ill_t		*ill;
13433 
13434 	ip1dbg(("ip_rput_dlpi"));
13435 	ill = (ill_t *)q->q_ptr;
13436 	switch (dloa->dl_primitive) {
13437 	case DL_ERROR_ACK:
13438 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
13439 		    "%s (0x%x), unix %u\n", ill->ill_name,
13440 		    dlpi_prim_str(dlea->dl_error_primitive),
13441 		    dlea->dl_error_primitive,
13442 		    dlpi_err_str(dlea->dl_errno),
13443 		    dlea->dl_errno,
13444 		    dlea->dl_unix_errno));
13445 		switch (dlea->dl_error_primitive) {
13446 		case DL_NOTIFY_REQ:
13447 		case DL_UNBIND_REQ:
13448 		case DL_ATTACH_REQ:
13449 		case DL_DETACH_REQ:
13450 		case DL_INFO_REQ:
13451 		case DL_BIND_REQ:
13452 		case DL_ENABMULTI_REQ:
13453 		case DL_PHYS_ADDR_REQ:
13454 		case DL_CAPABILITY_REQ:
13455 		case DL_CONTROL_REQ:
13456 			/*
13457 			 * Refhold the ill to match qwriter_ip which does a
13458 			 * refrele. Since this is on the ill stream we
13459 			 * unconditionally bump up the refcount without
13460 			 * checking for ILL_CAN_LOOKUP
13461 			 */
13462 			ill_refhold(ill);
13463 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13464 			    CUR_OP, B_FALSE);
13465 			return;
13466 		case DL_DISABMULTI_REQ:
13467 			freemsg(mp);	/* Don't want to pass this up */
13468 			return;
13469 		default:
13470 			break;
13471 		}
13472 		ip_dlpi_error(ill, dlea->dl_error_primitive,
13473 		    dlea->dl_errno, dlea->dl_unix_errno);
13474 		freemsg(mp);
13475 		return;
13476 	case DL_INFO_ACK:
13477 	case DL_BIND_ACK:
13478 	case DL_PHYS_ADDR_ACK:
13479 	case DL_NOTIFY_ACK:
13480 	case DL_CAPABILITY_ACK:
13481 	case DL_CONTROL_ACK:
13482 		/*
13483 		 * Refhold the ill to match qwriter_ip which does a refrele
13484 		 * Since this is on the ill stream we unconditionally
13485 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
13486 		 */
13487 		ill_refhold(ill);
13488 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13489 		    CUR_OP, B_FALSE);
13490 		return;
13491 	case DL_NOTIFY_IND:
13492 		ill_refhold(ill);
13493 		/*
13494 		 * The DL_NOTIFY_IND is an asynchronous message that has no
13495 		 * relation to the current ioctl in progress (if any). Hence we
13496 		 * pass in NEW_OP in this case.
13497 		 */
13498 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13499 		    NEW_OP, B_FALSE);
13500 		return;
13501 	case DL_OK_ACK:
13502 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
13503 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
13504 		switch (dloa->dl_correct_primitive) {
13505 		case DL_UNBIND_REQ:
13506 			mutex_enter(&ill->ill_lock);
13507 			ill->ill_state_flags |= ILL_DL_UNBIND_DONE;
13508 			cv_signal(&ill->ill_cv);
13509 			mutex_exit(&ill->ill_lock);
13510 			/* FALLTHRU */
13511 		case DL_ATTACH_REQ:
13512 		case DL_DETACH_REQ:
13513 			/*
13514 			 * Refhold the ill to match qwriter_ip which does a
13515 			 * refrele. Since this is on the ill stream we
13516 			 * unconditionally bump up the refcount
13517 			 */
13518 			ill_refhold(ill);
13519 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
13520 			    CUR_OP, B_FALSE);
13521 			return;
13522 		case DL_ENABMULTI_REQ:
13523 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
13524 				ill->ill_dlpi_multicast_state = IDMS_OK;
13525 			break;
13526 
13527 		}
13528 		break;
13529 	default:
13530 		break;
13531 	}
13532 	freemsg(mp);
13533 }
13534 
13535 /*
13536  * This function is used to free a message that has gone through
13537  * mi_copyin processing which modifies the M_IOCTL mblk's b_next
13538  * and b_prev pointers. We use this function to set b_next/b_prev
13539  * to NULL and free them.
13540  */
13541 void
13542 ip_ioctl_freemsg(mblk_t *mp)
13543 {
13544 	mblk_t	*bp = mp;
13545 
13546 	for (; bp != NULL; bp = bp->b_cont) {
13547 		bp->b_prev = NULL;
13548 		bp->b_next = NULL;
13549 	}
13550 	freemsg(mp);
13551 }
13552 
13553 /*
13554  * Handling of DLPI messages that require exclusive access to the ipsq.
13555  *
13556  * Need to do ill_pending_mp_release on ioctl completion, which could
13557  * happen here. (along with mi_copy_done)
13558  */
13559 /* ARGSUSED */
13560 static void
13561 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
13562 {
13563 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
13564 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
13565 	int		err = 0;
13566 	ill_t		*ill;
13567 	ipif_t		*ipif = NULL;
13568 	mblk_t		*mp1 = NULL;
13569 	conn_t		*connp = NULL;
13570 	t_uscalar_t	physaddr_req;
13571 	mblk_t		*mp_hw;
13572 	union DL_primitives *dlp;
13573 	boolean_t	success;
13574 	boolean_t	ioctl_aborted = B_FALSE;
13575 	boolean_t	log = B_TRUE;
13576 
13577 	ip1dbg(("ip_rput_dlpi_writer .."));
13578 	ill = (ill_t *)q->q_ptr;
13579 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
13580 
13581 	ASSERT(IAM_WRITER_ILL(ill));
13582 
13583 	/*
13584 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
13585 	 * both are null or non-null. However we can assert that only
13586 	 * after grabbing the ipsq_lock. So we don't make any assertion
13587 	 * here and in other places in the code.
13588 	 */
13589 	ipif = ipsq->ipsq_pending_ipif;
13590 	/*
13591 	 * The current ioctl could have been aborted by the user and a new
13592 	 * ioctl to bring up another ill could have started. We could still
13593 	 * get a response from the driver later.
13594 	 */
13595 	if (ipif != NULL && ipif->ipif_ill != ill)
13596 		ioctl_aborted = B_TRUE;
13597 
13598 	switch (dloa->dl_primitive) {
13599 	case DL_ERROR_ACK:
13600 		switch (dlea->dl_error_primitive) {
13601 		case DL_UNBIND_REQ:
13602 		case DL_ATTACH_REQ:
13603 		case DL_DETACH_REQ:
13604 		case DL_INFO_REQ:
13605 			ill_dlpi_done(ill, dlea->dl_error_primitive);
13606 			break;
13607 		case DL_NOTIFY_REQ:
13608 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
13609 			log = B_FALSE;
13610 			break;
13611 		case DL_PHYS_ADDR_REQ:
13612 			/*
13613 			 * For IPv6 only, there are two additional
13614 			 * phys_addr_req's sent to the driver to get the
13615 			 * IPv6 token and lla. This allows IP to acquire
13616 			 * the hardware address format for a given interface
13617 			 * without having built in knowledge of the hardware
13618 			 * address. ill_phys_addr_pend keeps track of the last
13619 			 * DL_PAR sent so we know which response we are
13620 			 * dealing with. ill_dlpi_done will update
13621 			 * ill_phys_addr_pend when it sends the next req.
13622 			 * We don't complete the IOCTL until all three DL_PARs
13623 			 * have been attempted, so set *_len to 0 and break.
13624 			 */
13625 			physaddr_req = ill->ill_phys_addr_pend;
13626 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
13627 			if (physaddr_req == DL_IPV6_TOKEN) {
13628 				ill->ill_token_length = 0;
13629 				log = B_FALSE;
13630 				break;
13631 			} else if (physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
13632 				ill->ill_nd_lla_len = 0;
13633 				log = B_FALSE;
13634 				break;
13635 			}
13636 			/*
13637 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
13638 			 * We presumably have an IOCTL hanging out waiting
13639 			 * for completion. Find it and complete the IOCTL
13640 			 * with the error noted.
13641 			 * However, ill_dl_phys was called on an ill queue
13642 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
13643 			 * set. But the ioctl is known to be pending on ill_wq.
13644 			 */
13645 			if (!ill->ill_ifname_pending)
13646 				break;
13647 			ill->ill_ifname_pending = 0;
13648 			if (!ioctl_aborted)
13649 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
13650 			if (mp1 != NULL) {
13651 				/*
13652 				 * This operation (SIOCSLIFNAME) must have
13653 				 * happened on the ill. Assert there is no conn
13654 				 */
13655 				ASSERT(connp == NULL);
13656 				q = ill->ill_wq;
13657 			}
13658 			break;
13659 		case DL_BIND_REQ:
13660 			ill_dlpi_done(ill, DL_BIND_REQ);
13661 			if (ill->ill_ifname_pending)
13662 				break;
13663 			/*
13664 			 * Something went wrong with the bind.  We presumably
13665 			 * have an IOCTL hanging out waiting for completion.
13666 			 * Find it, take down the interface that was coming
13667 			 * up, and complete the IOCTL with the error noted.
13668 			 */
13669 			if (!ioctl_aborted)
13670 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
13671 			if (mp1 != NULL) {
13672 				/*
13673 				 * This operation (SIOCSLIFFLAGS) must have
13674 				 * happened from a conn.
13675 				 */
13676 				ASSERT(connp != NULL);
13677 				q = CONNP_TO_WQ(connp);
13678 				if (ill->ill_move_in_progress) {
13679 					ILL_CLEAR_MOVE(ill);
13680 				}
13681 				(void) ipif_down(ipif, NULL, NULL);
13682 				/* error is set below the switch */
13683 			}
13684 			break;
13685 		case DL_ENABMULTI_REQ:
13686 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
13687 
13688 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
13689 				ill->ill_dlpi_multicast_state = IDMS_FAILED;
13690 			if (ill->ill_dlpi_multicast_state == IDMS_FAILED) {
13691 				ipif_t *ipif;
13692 
13693 				log = B_FALSE;
13694 				printf("ip: joining multicasts failed (%d)"
13695 				    " on %s - will use link layer "
13696 				    "broadcasts for multicast\n",
13697 				    dlea->dl_errno, ill->ill_name);
13698 
13699 				/*
13700 				 * Set up the multicast mapping alone.
13701 				 * writer, so ok to access ill->ill_ipif
13702 				 * without any lock.
13703 				 */
13704 				ipif = ill->ill_ipif;
13705 				mutex_enter(&ill->ill_phyint->phyint_lock);
13706 				ill->ill_phyint->phyint_flags |=
13707 				    PHYI_MULTI_BCAST;
13708 				mutex_exit(&ill->ill_phyint->phyint_lock);
13709 
13710 				if (!ill->ill_isv6) {
13711 					(void) ipif_arp_setup_multicast(ipif,
13712 					    NULL);
13713 				} else {
13714 					(void) ipif_ndp_setup_multicast(ipif,
13715 					    NULL);
13716 				}
13717 			}
13718 			freemsg(mp);	/* Don't want to pass this up */
13719 			return;
13720 		case DL_CAPABILITY_REQ:
13721 		case DL_CONTROL_REQ:
13722 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
13723 			    "DL_CAPABILITY/CONTROL REQ\n"));
13724 			ill_dlpi_done(ill, dlea->dl_error_primitive);
13725 			ill->ill_capab_state = IDMS_FAILED;
13726 			freemsg(mp);
13727 			return;
13728 		}
13729 		/*
13730 		 * Note the error for IOCTL completion (mp1 is set when
13731 		 * ready to complete ioctl). If ill_ifname_pending_err is
13732 		 * set, an error occured during plumbing (ill_ifname_pending),
13733 		 * so we want to report that error.
13734 		 *
13735 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
13736 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
13737 		 * expected to get errack'd if the driver doesn't support
13738 		 * these flags (e.g. ethernet). log will be set to B_FALSE
13739 		 * if these error conditions are encountered.
13740 		 */
13741 		if (mp1 != NULL) {
13742 			if (ill->ill_ifname_pending_err != 0)  {
13743 				err = ill->ill_ifname_pending_err;
13744 				ill->ill_ifname_pending_err = 0;
13745 			} else {
13746 				err = dlea->dl_unix_errno ?
13747 				    dlea->dl_unix_errno : ENXIO;
13748 			}
13749 		/*
13750 		 * If we're plumbing an interface and an error hasn't already
13751 		 * been saved, set ill_ifname_pending_err to the error passed
13752 		 * up. Ignore the error if log is B_FALSE (see comment above).
13753 		 */
13754 		} else if (log && ill->ill_ifname_pending &&
13755 		    ill->ill_ifname_pending_err == 0) {
13756 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
13757 			dlea->dl_unix_errno : ENXIO;
13758 		}
13759 
13760 		if (log)
13761 			ip_dlpi_error(ill, dlea->dl_error_primitive,
13762 			    dlea->dl_errno, dlea->dl_unix_errno);
13763 		break;
13764 	case DL_CAPABILITY_ACK: {
13765 		boolean_t reneg_flag = B_FALSE;
13766 		/* Call a routine to handle this one. */
13767 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
13768 		/*
13769 		 * Check if the ACK is due to renegotiation case since we
13770 		 * will need to send a new CAPABILITY_REQ later.
13771 		 */
13772 		if (ill->ill_capab_state == IDMS_RENEG) {
13773 			/* This is the ack for a renogiation case */
13774 			reneg_flag = B_TRUE;
13775 			ill->ill_capab_state = IDMS_UNKNOWN;
13776 		}
13777 		ill_capability_ack(ill, mp);
13778 		if (reneg_flag)
13779 			ill_capability_probe(ill);
13780 		break;
13781 	}
13782 	case DL_CONTROL_ACK:
13783 		/* We treat all of these as "fire and forget" */
13784 		ill_dlpi_done(ill, DL_CONTROL_REQ);
13785 		break;
13786 	case DL_INFO_ACK:
13787 		/* Call a routine to handle this one. */
13788 		ill_dlpi_done(ill, DL_INFO_REQ);
13789 		ip_ll_subnet_defaults(ill, mp);
13790 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
13791 		return;
13792 	case DL_BIND_ACK:
13793 		/*
13794 		 * We should have an IOCTL waiting on this unless
13795 		 * sent by ill_dl_phys, in which case just return
13796 		 */
13797 		ill_dlpi_done(ill, DL_BIND_REQ);
13798 		if (ill->ill_ifname_pending)
13799 			break;
13800 
13801 		if (!ioctl_aborted)
13802 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
13803 		if (mp1 == NULL)
13804 			break;
13805 		ASSERT(connp != NULL);
13806 		q = CONNP_TO_WQ(connp);
13807 
13808 		/*
13809 		 * We are exclusive. So nothing can change even after
13810 		 * we get the pending mp. If need be we can put it back
13811 		 * and restart, as in calling ipif_arp_up()  below.
13812 		 */
13813 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
13814 
13815 		mutex_enter(&ill->ill_lock);
13816 		ill->ill_dl_up = 1;
13817 		mutex_exit(&ill->ill_lock);
13818 
13819 		/*
13820 		 * Now bring up the resolver, when that is
13821 		 * done we'll create IREs and we are done.
13822 		 */
13823 		if (ill->ill_isv6) {
13824 			/*
13825 			 * v6 interfaces.
13826 			 * Unlike ARP which has to do another bind
13827 			 * and attach, once we get here we are
13828 			 * done withh NDP. Except in the case of
13829 			 * ILLF_XRESOLV, in which case we send an
13830 			 * AR_INTERFACE_UP to the external resolver.
13831 			 * If all goes well, the ioctl will complete
13832 			 * in ip_rput(). If there's an error, we
13833 			 * complete it here.
13834 			 */
13835 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr,
13836 			    B_FALSE);
13837 			if (err == 0) {
13838 				if (ill->ill_flags & ILLF_XRESOLV) {
13839 					mutex_enter(&connp->conn_lock);
13840 					mutex_enter(&ill->ill_lock);
13841 					success = ipsq_pending_mp_add(
13842 					    connp, ipif, q, mp1, 0);
13843 					mutex_exit(&ill->ill_lock);
13844 					mutex_exit(&connp->conn_lock);
13845 					if (success) {
13846 						err = ipif_resolver_up(ipif,
13847 						    B_FALSE);
13848 						if (err == EINPROGRESS) {
13849 							freemsg(mp);
13850 							return;
13851 						}
13852 						ASSERT(err != 0);
13853 						mp1 = ipsq_pending_mp_get(ipsq,
13854 						    &connp);
13855 						ASSERT(mp1 != NULL);
13856 					} else {
13857 						/* conn has started closing */
13858 						err = EINTR;
13859 					}
13860 				} else { /* Non XRESOLV interface */
13861 					err = ipif_up_done_v6(ipif);
13862 				}
13863 			}
13864 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
13865 			/*
13866 			 * ARP and other v4 external resolvers.
13867 			 * Leave the pending mblk intact so that
13868 			 * the ioctl completes in ip_rput().
13869 			 */
13870 			mutex_enter(&connp->conn_lock);
13871 			mutex_enter(&ill->ill_lock);
13872 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
13873 			mutex_exit(&ill->ill_lock);
13874 			mutex_exit(&connp->conn_lock);
13875 			if (success) {
13876 				err = ipif_resolver_up(ipif, B_FALSE);
13877 				if (err == EINPROGRESS) {
13878 					freemsg(mp);
13879 					return;
13880 				}
13881 				ASSERT(err != 0);
13882 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
13883 			} else {
13884 				/* The conn has started closing */
13885 				err = EINTR;
13886 			}
13887 		} else {
13888 			/*
13889 			 * This one is complete. Reply to pending ioctl.
13890 			 */
13891 			err = ipif_up_done(ipif);
13892 		}
13893 
13894 		if ((err == 0) && (ill->ill_up_ipifs)) {
13895 			err = ill_up_ipifs(ill, q, mp1);
13896 			if (err == EINPROGRESS) {
13897 				freemsg(mp);
13898 				return;
13899 			}
13900 		}
13901 
13902 		if (ill->ill_up_ipifs) {
13903 			ill_group_cleanup(ill);
13904 		}
13905 
13906 		break;
13907 	case DL_NOTIFY_IND: {
13908 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
13909 		ire_t *ire;
13910 		boolean_t need_ire_walk_v4 = B_FALSE;
13911 		boolean_t need_ire_walk_v6 = B_FALSE;
13912 
13913 		/*
13914 		 * Change the address everywhere we need to.
13915 		 * What we're getting here is a link-level addr or phys addr.
13916 		 * The new addr is at notify + notify->dl_addr_offset
13917 		 * The address length is notify->dl_addr_length;
13918 		 */
13919 		switch (notify->dl_notification) {
13920 		case DL_NOTE_PHYS_ADDR:
13921 			mp_hw = copyb(mp);
13922 			if (mp_hw == NULL) {
13923 				err = ENOMEM;
13924 				break;
13925 			}
13926 			dlp = (union DL_primitives *)mp_hw->b_rptr;
13927 			/*
13928 			 * We currently don't support changing
13929 			 * the token via DL_NOTIFY_IND.
13930 			 * When we do support it, we have to consider
13931 			 * what the implications are with respect to
13932 			 * the token and the link local address.
13933 			 */
13934 			mutex_enter(&ill->ill_lock);
13935 			if (dlp->notify_ind.dl_data ==
13936 			    DL_IPV6_LINK_LAYER_ADDR) {
13937 				if (ill->ill_nd_lla_mp != NULL)
13938 					freemsg(ill->ill_nd_lla_mp);
13939 				ill->ill_nd_lla_mp = mp_hw;
13940 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
13941 				    dlp->notify_ind.dl_addr_offset;
13942 				ill->ill_nd_lla_len =
13943 				    dlp->notify_ind.dl_addr_length -
13944 				    ABS(ill->ill_sap_length);
13945 				mutex_exit(&ill->ill_lock);
13946 				break;
13947 			} else if (dlp->notify_ind.dl_data ==
13948 			    DL_CURR_PHYS_ADDR) {
13949 				if (ill->ill_phys_addr_mp != NULL)
13950 					freemsg(ill->ill_phys_addr_mp);
13951 				ill->ill_phys_addr_mp = mp_hw;
13952 				ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
13953 				    dlp->notify_ind.dl_addr_offset;
13954 				ill->ill_phys_addr_length =
13955 				    dlp->notify_ind.dl_addr_length -
13956 				    ABS(ill->ill_sap_length);
13957 				if (ill->ill_isv6 &&
13958 				    !(ill->ill_flags & ILLF_XRESOLV)) {
13959 					if (ill->ill_nd_lla_mp != NULL)
13960 						freemsg(ill->ill_nd_lla_mp);
13961 					ill->ill_nd_lla_mp = copyb(mp_hw);
13962 					ill->ill_nd_lla = (uchar_t *)
13963 					    ill->ill_nd_lla_mp->b_rptr +
13964 					    dlp->notify_ind.dl_addr_offset;
13965 					ill->ill_nd_lla_len =
13966 					    ill->ill_phys_addr_length;
13967 				}
13968 			}
13969 			mutex_exit(&ill->ill_lock);
13970 			/*
13971 			 * Send out gratuitous arp request for our new
13972 			 * hardware address.
13973 			 */
13974 			for (ipif = ill->ill_ipif; ipif != NULL;
13975 			    ipif = ipif->ipif_next) {
13976 				if (!(ipif->ipif_flags & IPIF_UP))
13977 					continue;
13978 				if (ill->ill_isv6) {
13979 					ipif_ndp_down(ipif);
13980 					/*
13981 					 * Set B_TRUE to enable
13982 					 * ipif_ndp_up() to send out
13983 					 * unsolicited advertisements.
13984 					 */
13985 					err = ipif_ndp_up(ipif,
13986 					    &ipif->ipif_v6lcl_addr,
13987 					    B_TRUE);
13988 					if (err) {
13989 						ip1dbg((
13990 						    "ip_rput_dlpi_writer: "
13991 						    "Failed to update ndp "
13992 						    "err %d\n", err));
13993 					}
13994 				} else {
13995 					/*
13996 					 * IPv4 ARP case
13997 					 *
13998 					 * Set B_TRUE, as we only want
13999 					 * ipif_resolver_up to send an
14000 					 * AR_ENTRY_ADD request up to
14001 					 * ARP.
14002 					 */
14003 					err = ipif_resolver_up(ipif,
14004 					    B_TRUE);
14005 					if (err) {
14006 						ip1dbg((
14007 						    "ip_rput_dlpi_writer: "
14008 						    "Failed to update arp "
14009 						    "err %d\n", err));
14010 					}
14011 				}
14012 			}
14013 			/*
14014 			 * Allow "fall through" to the DL_NOTE_FASTPATH_FLUSH
14015 			 * case so that all old fastpath information can be
14016 			 * purged from IRE caches.
14017 			 */
14018 		/* FALLTHRU */
14019 		case DL_NOTE_FASTPATH_FLUSH:
14020 			/*
14021 			 * Any fastpath probe sent henceforth will get the
14022 			 * new fp mp. So we first delete any ires that are
14023 			 * waiting for the fastpath. Then walk all ires and
14024 			 * delete the ire or delete the fp mp. In the case of
14025 			 * IRE_MIPRTUN and IRE_BROADCAST it is difficult to
14026 			 * recreate the ire's without going through a complex
14027 			 * ipif up/down dance. So we don't delete the ire
14028 			 * itself, but just the ire_fp_mp for these 2 ire's
14029 			 * In the case of the other ire's we delete the ire's
14030 			 * themselves. Access to ire_fp_mp is completely
14031 			 * protected by ire_lock for IRE_MIPRTUN and
14032 			 * IRE_BROADCAST. Deleting the ire is preferable in the
14033 			 * other cases for performance.
14034 			 */
14035 			if (ill->ill_isv6) {
14036 				nce_fastpath_list_dispatch(ill, NULL, NULL);
14037 				ndp_walk(ill, (pfi_t)ndp_fastpath_flush,
14038 				    NULL);
14039 			} else {
14040 				ire_fastpath_list_dispatch(ill, NULL, NULL);
14041 				ire_walk_ill_v4(MATCH_IRE_WQ | MATCH_IRE_TYPE,
14042 				    IRE_CACHE | IRE_BROADCAST,
14043 				    ire_fastpath_flush, NULL, ill);
14044 				mutex_enter(&ire_mrtun_lock);
14045 				if (ire_mrtun_count != 0) {
14046 					mutex_exit(&ire_mrtun_lock);
14047 					ire_walk_ill_mrtun(MATCH_IRE_WQ,
14048 					    IRE_MIPRTUN, ire_fastpath_flush,
14049 					    NULL, ill);
14050 				} else {
14051 					mutex_exit(&ire_mrtun_lock);
14052 				}
14053 			}
14054 			break;
14055 		case DL_NOTE_SDU_SIZE:
14056 			/*
14057 			 * Change the MTU size of the interface, of all
14058 			 * attached ipif's, and of all relevant ire's.  The
14059 			 * new value's a uint32_t at notify->dl_data.
14060 			 * Mtu change Vs. new ire creation - protocol below.
14061 			 *
14062 			 * a Mark the ipif as IPIF_CHANGING.
14063 			 * b Set the new mtu in the ipif.
14064 			 * c Change the ire_max_frag on all affected ires
14065 			 * d Unmark the IPIF_CHANGING
14066 			 *
14067 			 * To see how the protocol works, assume an interface
14068 			 * route is also being added simultaneously by
14069 			 * ip_rt_add and let 'ipif' be the ipif referenced by
14070 			 * the ire. If the ire is created before step a,
14071 			 * it will be cleaned up by step c. If the ire is
14072 			 * created after step d, it will see the new value of
14073 			 * ipif_mtu. Any attempt to create the ire between
14074 			 * steps a to d will fail because of the IPIF_CHANGING
14075 			 * flag. Note that ire_create() is passed a pointer to
14076 			 * the ipif_mtu, and not the value. During ire_add
14077 			 * under the bucket lock, the ire_max_frag of the
14078 			 * new ire being created is set from the ipif/ire from
14079 			 * which it is being derived.
14080 			 */
14081 			mutex_enter(&ill->ill_lock);
14082 			ill->ill_max_frag = (uint_t)notify->dl_data;
14083 
14084 			/*
14085 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
14086 			 * leave it alone
14087 			 */
14088 			if (ill->ill_mtu_userspecified) {
14089 				mutex_exit(&ill->ill_lock);
14090 				break;
14091 			}
14092 			ill->ill_max_mtu = ill->ill_max_frag;
14093 			if (ill->ill_isv6) {
14094 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
14095 					ill->ill_max_mtu = IPV6_MIN_MTU;
14096 			} else {
14097 				if (ill->ill_max_mtu < IP_MIN_MTU)
14098 					ill->ill_max_mtu = IP_MIN_MTU;
14099 			}
14100 			for (ipif = ill->ill_ipif; ipif != NULL;
14101 			    ipif = ipif->ipif_next) {
14102 				/*
14103 				 * Don't override the mtu if the user
14104 				 * has explicitly set it.
14105 				 */
14106 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
14107 					continue;
14108 				ipif->ipif_mtu = (uint_t)notify->dl_data;
14109 				if (ipif->ipif_isv6)
14110 					ire = ipif_to_ire_v6(ipif);
14111 				else
14112 					ire = ipif_to_ire(ipif);
14113 				if (ire != NULL) {
14114 					ire->ire_max_frag = ipif->ipif_mtu;
14115 					ire_refrele(ire);
14116 				}
14117 				if (ipif->ipif_flags & IPIF_UP) {
14118 					if (ill->ill_isv6)
14119 						need_ire_walk_v6 = B_TRUE;
14120 					else
14121 						need_ire_walk_v4 = B_TRUE;
14122 				}
14123 			}
14124 			mutex_exit(&ill->ill_lock);
14125 			if (need_ire_walk_v4)
14126 				ire_walk_v4(ill_mtu_change, (char *)ill,
14127 				    ALL_ZONES);
14128 			if (need_ire_walk_v6)
14129 				ire_walk_v6(ill_mtu_change, (char *)ill,
14130 				    ALL_ZONES);
14131 			break;
14132 		case DL_NOTE_LINK_UP:
14133 		case DL_NOTE_LINK_DOWN: {
14134 			/*
14135 			 * We are writer. ill / phyint / ipsq assocs stable.
14136 			 * The RUNNING flag reflects the state of the link.
14137 			 */
14138 			phyint_t *phyint = ill->ill_phyint;
14139 			uint64_t new_phyint_flags;
14140 			boolean_t changed = B_FALSE;
14141 
14142 			mutex_enter(&phyint->phyint_lock);
14143 			new_phyint_flags =
14144 			    (notify->dl_notification == DL_NOTE_LINK_UP) ?
14145 			    phyint->phyint_flags | PHYI_RUNNING :
14146 			    phyint->phyint_flags & ~PHYI_RUNNING;
14147 			if (new_phyint_flags != phyint->phyint_flags) {
14148 				phyint->phyint_flags = new_phyint_flags;
14149 				changed = B_TRUE;
14150 			}
14151 			mutex_exit(&phyint->phyint_lock);
14152 			/*
14153 			 * If the flags have changed, send a message to
14154 			 * the routing socket.
14155 			 */
14156 			if (changed) {
14157 				if (phyint->phyint_illv4 != NULL) {
14158 					ip_rts_ifmsg(
14159 					    phyint->phyint_illv4->ill_ipif);
14160 				}
14161 				if (phyint->phyint_illv6 != NULL) {
14162 					ip_rts_ifmsg(
14163 					    phyint->phyint_illv6->ill_ipif);
14164 				}
14165 			}
14166 			break;
14167 		}
14168 		case DL_NOTE_PROMISC_ON_PHYS:
14169 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
14170 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
14171 			mutex_enter(&ill->ill_lock);
14172 			ill->ill_promisc_on_phys = B_TRUE;
14173 			mutex_exit(&ill->ill_lock);
14174 			break;
14175 		case DL_NOTE_PROMISC_OFF_PHYS:
14176 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
14177 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
14178 			mutex_enter(&ill->ill_lock);
14179 			ill->ill_promisc_on_phys = B_FALSE;
14180 			mutex_exit(&ill->ill_lock);
14181 			break;
14182 		case DL_NOTE_CAPAB_RENEG:
14183 			/*
14184 			 * Something changed on the driver side.
14185 			 * It wants us to renegotiate the capabilities
14186 			 * on this ill. The most likely cause is the
14187 			 * aggregation interface under us where a
14188 			 * port got added or went away.
14189 			 *
14190 			 * We reset the capabilities and set the
14191 			 * state to IDMS_RENG so that when the ack
14192 			 * comes back, we can start the
14193 			 * renegotiation process.
14194 			 */
14195 			ill_capability_reset(ill);
14196 			ill->ill_capab_state = IDMS_RENEG;
14197 			break;
14198 		default:
14199 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
14200 			    "type 0x%x for DL_NOTIFY_IND\n",
14201 			    notify->dl_notification));
14202 			break;
14203 		}
14204 
14205 		/*
14206 		 * As this is an asynchronous operation, we
14207 		 * should not call ill_dlpi_done
14208 		 */
14209 		break;
14210 	}
14211 	case DL_NOTIFY_ACK:
14212 		/*
14213 		 * Don't really need to check for what notifications
14214 		 * are supported; we'll process what gets sent upstream,
14215 		 * and we know it'll be something we support changing
14216 		 * based on our DL_NOTIFY_REQ.
14217 		 */
14218 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
14219 		break;
14220 	case DL_PHYS_ADDR_ACK: {
14221 		/*
14222 		 * We should have an IOCTL waiting on this when request
14223 		 * sent by ill_dl_phys.
14224 		 * However, ill_dl_phys was called on an ill queue (from
14225 		 * SIOCSLIFNAME), thus conn_pending_ill is not set. But the
14226 		 * ioctl is known to be pending on ill_wq.
14227 		 * There are two additional phys_addr_req's sent to the
14228 		 * driver to get the token and lla. ill_phys_addr_pend
14229 		 * keeps track of the last one sent so we know which
14230 		 * response we are dealing with. ill_dlpi_done will
14231 		 * update ill_phys_addr_pend when it sends the next req.
14232 		 * We don't complete the IOCTL until all three DL_PARs
14233 		 * have been attempted.
14234 		 *
14235 		 * We don't need any lock to update ill_nd_lla* fields,
14236 		 * since the ill is not yet up, We grab the lock just
14237 		 * for uniformity with other code that accesses ill_nd_lla.
14238 		 */
14239 		physaddr_req = ill->ill_phys_addr_pend;
14240 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
14241 		if (physaddr_req == DL_IPV6_TOKEN ||
14242 		    physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
14243 			if (physaddr_req == DL_IPV6_TOKEN) {
14244 				/*
14245 				 * bcopy to low-order bits of ill_token
14246 				 *
14247 				 * XXX Temporary hack - currently,
14248 				 * all known tokens are 64 bits,
14249 				 * so I'll cheat for the moment.
14250 				 */
14251 				dlp = (union DL_primitives *)mp->b_rptr;
14252 
14253 				mutex_enter(&ill->ill_lock);
14254 				bcopy((uchar_t *)(mp->b_rptr +
14255 				dlp->physaddr_ack.dl_addr_offset),
14256 				(void *)&ill->ill_token.s6_addr32[2],
14257 				dlp->physaddr_ack.dl_addr_length);
14258 				ill->ill_token_length =
14259 					dlp->physaddr_ack.dl_addr_length;
14260 				mutex_exit(&ill->ill_lock);
14261 			} else {
14262 				ASSERT(ill->ill_nd_lla_mp == NULL);
14263 				mp_hw = copyb(mp);
14264 				if (mp_hw == NULL) {
14265 					err = ENOMEM;
14266 					break;
14267 				}
14268 				dlp = (union DL_primitives *)mp_hw->b_rptr;
14269 				mutex_enter(&ill->ill_lock);
14270 				ill->ill_nd_lla_mp = mp_hw;
14271 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
14272 				dlp->physaddr_ack.dl_addr_offset;
14273 				ill->ill_nd_lla_len =
14274 					dlp->physaddr_ack.dl_addr_length;
14275 				mutex_exit(&ill->ill_lock);
14276 			}
14277 			break;
14278 		}
14279 		ASSERT(physaddr_req == DL_CURR_PHYS_ADDR);
14280 		ASSERT(ill->ill_phys_addr_mp == NULL);
14281 		if (!ill->ill_ifname_pending)
14282 			break;
14283 		ill->ill_ifname_pending = 0;
14284 		if (!ioctl_aborted)
14285 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
14286 		if (mp1 != NULL) {
14287 			ASSERT(connp == NULL);
14288 			q = ill->ill_wq;
14289 		}
14290 		/*
14291 		 * If any error acks received during the plumbing sequence,
14292 		 * ill_ifname_pending_err will be set. Break out and send up
14293 		 * the error to the pending ioctl.
14294 		 */
14295 		if (ill->ill_ifname_pending_err != 0) {
14296 			err = ill->ill_ifname_pending_err;
14297 			ill->ill_ifname_pending_err = 0;
14298 			break;
14299 		}
14300 		/*
14301 		 * Get the interface token.  If the zeroth interface
14302 		 * address is zero then set the address to the link local
14303 		 * address
14304 		 */
14305 		mp_hw = copyb(mp);
14306 		if (mp_hw == NULL) {
14307 			err = ENOMEM;
14308 			break;
14309 		}
14310 		dlp = (union DL_primitives *)mp_hw->b_rptr;
14311 		ill->ill_phys_addr_mp = mp_hw;
14312 		ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
14313 				dlp->physaddr_ack.dl_addr_offset;
14314 		if (dlp->physaddr_ack.dl_addr_length == 0 ||
14315 		    ill->ill_phys_addr_length == 0 ||
14316 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
14317 			/*
14318 			 * Compatibility: atun driver returns a length of 0.
14319 			 * ipdptp has an ill_phys_addr_length of zero(from
14320 			 * DL_BIND_ACK) but a non-zero length here.
14321 			 * ipd has an ill_phys_addr_length of 4(from
14322 			 * DL_BIND_ACK) but a non-zero length here.
14323 			 */
14324 			ill->ill_phys_addr = NULL;
14325 		} else if (dlp->physaddr_ack.dl_addr_length !=
14326 		    ill->ill_phys_addr_length) {
14327 			ip0dbg(("DL_PHYS_ADDR_ACK: "
14328 			    "Address length mismatch %d %d\n",
14329 			    dlp->physaddr_ack.dl_addr_length,
14330 			    ill->ill_phys_addr_length));
14331 			err = EINVAL;
14332 			break;
14333 		}
14334 		mutex_enter(&ill->ill_lock);
14335 		if (ill->ill_nd_lla_mp == NULL) {
14336 			ill->ill_nd_lla_mp = copyb(mp_hw);
14337 			if (ill->ill_nd_lla_mp == NULL) {
14338 				err = ENOMEM;
14339 				mutex_exit(&ill->ill_lock);
14340 				break;
14341 			}
14342 			ill->ill_nd_lla =
14343 			    (uchar_t *)ill->ill_nd_lla_mp->b_rptr +
14344 			    dlp->physaddr_ack.dl_addr_offset;
14345 			ill->ill_nd_lla_len = ill->ill_phys_addr_length;
14346 		}
14347 		mutex_exit(&ill->ill_lock);
14348 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
14349 			(void) ill_setdefaulttoken(ill);
14350 
14351 		/*
14352 		 * If the ill zero interface has a zero address assign
14353 		 * it the proper link local address.
14354 		 */
14355 		ASSERT(ill->ill_ipif->ipif_id == 0);
14356 		if (ipif != NULL &&
14357 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
14358 			(void) ipif_setlinklocal(ipif);
14359 		break;
14360 	}
14361 	case DL_OK_ACK:
14362 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
14363 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
14364 		    dloa->dl_correct_primitive));
14365 		switch (dloa->dl_correct_primitive) {
14366 		case DL_UNBIND_REQ:
14367 		case DL_ATTACH_REQ:
14368 		case DL_DETACH_REQ:
14369 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
14370 			break;
14371 		}
14372 		break;
14373 	default:
14374 		break;
14375 	}
14376 
14377 	freemsg(mp);
14378 	if (mp1) {
14379 		struct iocblk *iocp;
14380 		int mode;
14381 
14382 		/*
14383 		 * Complete the waiting IOCTL. For SIOCLIFADDIF or
14384 		 * SIOCSLIFNAME do a copyout.
14385 		 */
14386 		iocp = (struct iocblk *)mp1->b_rptr;
14387 
14388 		if (iocp->ioc_cmd == SIOCLIFADDIF ||
14389 		    iocp->ioc_cmd == SIOCSLIFNAME)
14390 			mode = COPYOUT;
14391 		else
14392 			mode = NO_COPYOUT;
14393 		/*
14394 		 * The ioctl must complete now without EINPROGRESS
14395 		 * since ipsq_pending_mp_get has removed the ioctl mblk
14396 		 * from ipsq_pending_mp. Otherwise the ioctl will be
14397 		 * stuck for ever in the ipsq.
14398 		 */
14399 		ASSERT(err != EINPROGRESS);
14400 		ip_ioctl_finish(q, mp1, err, mode, ipif, ipsq);
14401 
14402 	}
14403 }
14404 
14405 /*
14406  * ip_rput_other is called by ip_rput to handle messages modifying the global
14407  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
14408  */
14409 /* ARGSUSED */
14410 void
14411 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
14412 {
14413 	ill_t		*ill;
14414 	struct iocblk	*iocp;
14415 	mblk_t		*mp1;
14416 	conn_t		*connp = NULL;
14417 
14418 	ip1dbg(("ip_rput_other "));
14419 	ill = (ill_t *)q->q_ptr;
14420 	/*
14421 	 * This routine is not a writer in the case of SIOCGTUNPARAM
14422 	 * in which case ipsq is NULL.
14423 	 */
14424 	if (ipsq != NULL) {
14425 		ASSERT(IAM_WRITER_IPSQ(ipsq));
14426 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
14427 	}
14428 
14429 	switch (mp->b_datap->db_type) {
14430 	case M_ERROR:
14431 	case M_HANGUP:
14432 		/*
14433 		 * The device has a problem.  We force the ILL down.  It can
14434 		 * be brought up again manually using SIOCSIFFLAGS (via
14435 		 * ifconfig or equivalent).
14436 		 */
14437 		ASSERT(ipsq != NULL);
14438 		if (mp->b_rptr < mp->b_wptr)
14439 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
14440 		if (ill->ill_error == 0)
14441 			ill->ill_error = ENXIO;
14442 		if (!ill_down_start(q, mp))
14443 			return;
14444 		ipif_all_down_tail(ipsq, q, mp, NULL);
14445 		break;
14446 	case M_IOCACK:
14447 		iocp = (struct iocblk *)mp->b_rptr;
14448 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
14449 		switch (iocp->ioc_cmd) {
14450 		case SIOCSTUNPARAM:
14451 		case OSIOCSTUNPARAM:
14452 			ASSERT(ipsq != NULL);
14453 			/*
14454 			 * Finish socket ioctl passed through to tun.
14455 			 * We should have an IOCTL waiting on this.
14456 			 */
14457 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
14458 			if (ill->ill_isv6) {
14459 				struct iftun_req *ta;
14460 
14461 				/*
14462 				 * if a source or destination is
14463 				 * being set, try and set the link
14464 				 * local address for the tunnel
14465 				 */
14466 				ta = (struct iftun_req *)mp->b_cont->
14467 				    b_cont->b_rptr;
14468 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
14469 					ipif_set_tun_llink(ill, ta);
14470 				}
14471 
14472 			}
14473 			if (mp1 != NULL) {
14474 				/*
14475 				 * Now copy back the b_next/b_prev used by
14476 				 * mi code for the mi_copy* functions.
14477 				 * See ip_sioctl_tunparam() for the reason.
14478 				 * Also protect against missing b_cont.
14479 				 */
14480 				if (mp->b_cont != NULL) {
14481 					mp->b_cont->b_next =
14482 					    mp1->b_cont->b_next;
14483 					mp->b_cont->b_prev =
14484 					    mp1->b_cont->b_prev;
14485 				}
14486 				ip_ioctl_freemsg(mp1);
14487 				ASSERT(ipsq->ipsq_current_ipif != NULL);
14488 				ASSERT(connp != NULL);
14489 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
14490 				    iocp->ioc_error, NO_COPYOUT,
14491 				    ipsq->ipsq_current_ipif, ipsq);
14492 			} else {
14493 				ASSERT(connp == NULL);
14494 				putnext(q, mp);
14495 			}
14496 			break;
14497 		case SIOCGTUNPARAM:
14498 		case OSIOCGTUNPARAM:
14499 			/*
14500 			 * This is really M_IOCDATA from the tunnel driver.
14501 			 * convert back and complete the ioctl.
14502 			 * We should have an IOCTL waiting on this.
14503 			 */
14504 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
14505 			if (mp1) {
14506 				/*
14507 				 * Now copy back the b_next/b_prev used by
14508 				 * mi code for the mi_copy* functions.
14509 				 * See ip_sioctl_tunparam() for the reason.
14510 				 * Also protect against missing b_cont.
14511 				 */
14512 				if (mp->b_cont != NULL) {
14513 					mp->b_cont->b_next =
14514 					    mp1->b_cont->b_next;
14515 					mp->b_cont->b_prev =
14516 					    mp1->b_cont->b_prev;
14517 				}
14518 				ip_ioctl_freemsg(mp1);
14519 				if (iocp->ioc_error == 0)
14520 					mp->b_datap->db_type = M_IOCDATA;
14521 				ASSERT(connp != NULL);
14522 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
14523 				    iocp->ioc_error, COPYOUT, NULL, NULL);
14524 			} else {
14525 				ASSERT(connp == NULL);
14526 				putnext(q, mp);
14527 			}
14528 			break;
14529 		default:
14530 			break;
14531 		}
14532 		break;
14533 	case M_IOCNAK:
14534 		iocp = (struct iocblk *)mp->b_rptr;
14535 
14536 		switch (iocp->ioc_cmd) {
14537 		int mode;
14538 		ipif_t	*ipif;
14539 
14540 		case DL_IOC_HDR_INFO:
14541 			/*
14542 			 * If this was the first attempt turn of the
14543 			 * fastpath probing.
14544 			 */
14545 			mutex_enter(&ill->ill_lock);
14546 			if (ill->ill_dlpi_fastpath_state == IDMS_INPROGRESS) {
14547 				ill->ill_dlpi_fastpath_state = IDMS_FAILED;
14548 				mutex_exit(&ill->ill_lock);
14549 				ill_fastpath_nack(ill);
14550 				ip1dbg(("ip_rput: DLPI fastpath off on "
14551 				    "interface %s\n",
14552 				    ill->ill_name));
14553 			} else {
14554 				mutex_exit(&ill->ill_lock);
14555 			}
14556 			freemsg(mp);
14557 			break;
14558 		case SIOCSTUNPARAM:
14559 		case OSIOCSTUNPARAM:
14560 			ASSERT(ipsq != NULL);
14561 			/*
14562 			 * Finish socket ioctl passed through to tun
14563 			 * We should have an IOCTL waiting on this.
14564 			 */
14565 			/* FALLTHRU */
14566 		case SIOCGTUNPARAM:
14567 		case OSIOCGTUNPARAM:
14568 			/*
14569 			 * This is really M_IOCDATA from the tunnel driver.
14570 			 * convert back and complete the ioctl.
14571 			 * We should have an IOCTL waiting on this.
14572 			 */
14573 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
14574 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
14575 				mp1 = ill_pending_mp_get(ill, &connp,
14576 				    iocp->ioc_id);
14577 				mode = COPYOUT;
14578 				ipsq = NULL;
14579 				ipif = NULL;
14580 			} else {
14581 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14582 				mode = NO_COPYOUT;
14583 				ASSERT(ipsq->ipsq_current_ipif != NULL);
14584 				ipif = ipsq->ipsq_current_ipif;
14585 			}
14586 			if (mp1 != NULL) {
14587 				/*
14588 				 * Now copy back the b_next/b_prev used by
14589 				 * mi code for the mi_copy* functions.
14590 				 * See ip_sioctl_tunparam() for the reason.
14591 				 * Also protect against missing b_cont.
14592 				 */
14593 				if (mp->b_cont != NULL) {
14594 					mp->b_cont->b_next =
14595 					    mp1->b_cont->b_next;
14596 					mp->b_cont->b_prev =
14597 					    mp1->b_cont->b_prev;
14598 				}
14599 				ip_ioctl_freemsg(mp1);
14600 				if (iocp->ioc_error == 0)
14601 					iocp->ioc_error = EINVAL;
14602 				ASSERT(connp != NULL);
14603 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
14604 				    iocp->ioc_error, mode, ipif, ipsq);
14605 			} else {
14606 				ASSERT(connp == NULL);
14607 				putnext(q, mp);
14608 			}
14609 			break;
14610 		default:
14611 			break;
14612 		}
14613 	default:
14614 		break;
14615 	}
14616 }
14617 
14618 /*
14619  * NOTE : This function does not ire_refrele the ire argument passed in.
14620  *
14621  * IPQoS notes
14622  * IP policy is invoked twice for a forwarded packet, once on the read side
14623  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
14624  * enabled. An additional parameter, in_ill, has been added for this purpose.
14625  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
14626  * because ip_mroute drops this information.
14627  *
14628  */
14629 void
14630 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
14631 {
14632 	uint32_t	pkt_len;
14633 	queue_t	*q;
14634 	uint32_t	sum;
14635 #define	rptr	((uchar_t *)ipha)
14636 	uint32_t	max_frag;
14637 	uint32_t	ill_index;
14638 
14639 	/* Get the ill_index of the incoming ILL */
14640 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
14641 
14642 	/* Initiate Read side IPPF processing */
14643 	if (IPP_ENABLED(IPP_FWD_IN)) {
14644 		ip_process(IPP_FWD_IN, &mp, ill_index);
14645 		if (mp == NULL) {
14646 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
14647 			    "during IPPF processing\n"));
14648 			return;
14649 		}
14650 	}
14651 	pkt_len = ntohs(ipha->ipha_length);
14652 
14653 	/* Adjust the checksum to reflect the ttl decrement. */
14654 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14655 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14656 
14657 	if (ipha->ipha_ttl-- <= 1) {
14658 		if (ip_csum_hdr(ipha)) {
14659 			BUMP_MIB(&ip_mib, ipInCksumErrs);
14660 			goto drop_pkt;
14661 		}
14662 		/*
14663 		 * Note: ire_stq this will be NULL for multicast
14664 		 * datagrams using the long path through arp (the IRE
14665 		 * is not an IRE_CACHE). This should not cause
14666 		 * problems since we don't generate ICMP errors for
14667 		 * multicast packets.
14668 		 */
14669 		q = ire->ire_stq;
14670 		if (q)
14671 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED);
14672 		else
14673 			freemsg(mp);
14674 		return;
14675 	}
14676 
14677 	/*
14678 	 * Don't forward if the interface is down
14679 	 */
14680 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
14681 		BUMP_MIB(&ip_mib, ipInDiscards);
14682 		goto drop_pkt;
14683 	}
14684 
14685 	/* Get the ill_index of the outgoing ILL */
14686 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
14687 
14688 	/* Check if there are options to update */
14689 	if (!IS_SIMPLE_IPH(ipha)) {
14690 		if (ip_csum_hdr(ipha)) {
14691 			BUMP_MIB(&ip_mib, ipInCksumErrs);
14692 			goto drop_pkt;
14693 		}
14694 		if (ip_rput_forward_options(mp, ipha, ire)) {
14695 			return;
14696 		}
14697 
14698 		ipha->ipha_hdr_checksum = 0;
14699 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14700 	}
14701 	max_frag = ire->ire_max_frag;
14702 	if (pkt_len > max_frag) {
14703 		/*
14704 		 * It needs fragging on its way out.  We haven't
14705 		 * verified the header checksum yet.  Since we
14706 		 * are going to put a surely good checksum in the
14707 		 * outgoing header, we have to make sure that it
14708 		 * was good coming in.
14709 		 */
14710 		if (ip_csum_hdr(ipha)) {
14711 			BUMP_MIB(&ip_mib, ipInCksumErrs);
14712 			goto drop_pkt;
14713 		}
14714 		/* Initiate Write side IPPF processing */
14715 		if (IPP_ENABLED(IPP_FWD_OUT)) {
14716 			ip_process(IPP_FWD_OUT, &mp, ill_index);
14717 			if (mp == NULL) {
14718 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
14719 				    " during IPPF processing\n"));
14720 				return;
14721 			}
14722 		}
14723 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0);
14724 		return;
14725 	}
14726 
14727 	mp = ip_wput_attach_llhdr(mp, ire, IPP_FWD_OUT, ill_index);
14728 	if (mp == NULL) {
14729 		BUMP_MIB(&ip_mib, ipInDiscards);
14730 		return;
14731 	}
14732 
14733 	q = ire->ire_stq;
14734 	UPDATE_IB_PKT_COUNT(ire);
14735 	ire->ire_last_used_time = lbolt;
14736 	BUMP_MIB(&ip_mib, ipForwDatagrams);
14737 	putnext(q, mp);
14738 	return;
14739 
14740 drop_pkt:;
14741 	ip1dbg(("ip_rput_forward: drop pkt\n"));
14742 	freemsg(mp);
14743 #undef	rptr
14744 }
14745 
14746 void
14747 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
14748 {
14749 	ire_t	*ire;
14750 
14751 	ASSERT(!ipif->ipif_isv6);
14752 	/*
14753 	 * Find an IRE which matches the destination and the outgoing
14754 	 * queue in the cache table. All we need is an IRE_CACHE which
14755 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
14756 	 * then it is enough to have some IRE_CACHE in the group.
14757 	 */
14758 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
14759 		dst = ipif->ipif_pp_dst_addr;
14760 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES,
14761 	    MATCH_IRE_ILL_GROUP);
14762 	if (!ire) {
14763 		/*
14764 		 * Mark this packet to make it be delivered to
14765 		 * ip_rput_forward after the new ire has been
14766 		 * created.
14767 		 */
14768 		mp->b_prev = NULL;
14769 		mp->b_next = mp;
14770 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
14771 		    NULL, 0);
14772 	} else {
14773 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
14774 		IRE_REFRELE(ire);
14775 	}
14776 }
14777 
14778 /* Update any source route, record route or timestamp options */
14779 static int
14780 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire)
14781 {
14782 	ipoptp_t	opts;
14783 	uchar_t		*opt;
14784 	uint8_t		optval;
14785 	uint8_t		optlen;
14786 	ipaddr_t	dst;
14787 	uint32_t	ts;
14788 	ire_t		*dst_ire = NULL;
14789 	ire_t		*tmp_ire = NULL;
14790 	timestruc_t	now;
14791 
14792 	ip2dbg(("ip_rput_forward_options\n"));
14793 	dst = ipha->ipha_dst;
14794 	for (optval = ipoptp_first(&opts, ipha);
14795 	    optval != IPOPT_EOL;
14796 	    optval = ipoptp_next(&opts)) {
14797 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
14798 		opt = opts.ipoptp_cur;
14799 		optlen = opts.ipoptp_len;
14800 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
14801 		    optval, opts.ipoptp_len));
14802 		switch (optval) {
14803 			uint32_t off;
14804 		case IPOPT_SSRR:
14805 		case IPOPT_LSRR:
14806 			/* Check if adminstratively disabled */
14807 			if (!ip_forward_src_routed) {
14808 				BUMP_MIB(&ip_mib, ipForwProhibits);
14809 				if (ire->ire_stq)
14810 					icmp_unreachable(ire->ire_stq, mp,
14811 					    ICMP_SOURCE_ROUTE_FAILED);
14812 				else {
14813 					ip0dbg(("ip_rput_forward_options: "
14814 					    "unable to send unreach\n"));
14815 					freemsg(mp);
14816 				}
14817 				return (-1);
14818 			}
14819 
14820 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
14821 			    NULL, ALL_ZONES, MATCH_IRE_TYPE);
14822 			if (dst_ire == NULL) {
14823 				/*
14824 				 * Must be partial since ip_rput_options
14825 				 * checked for strict.
14826 				 */
14827 				break;
14828 			}
14829 			off = opt[IPOPT_OFFSET];
14830 			off--;
14831 		redo_srr:
14832 			if (optlen < IP_ADDR_LEN ||
14833 			    off > optlen - IP_ADDR_LEN) {
14834 				/* End of source route */
14835 				ip1dbg((
14836 				    "ip_rput_forward_options: end of SR\n"));
14837 				ire_refrele(dst_ire);
14838 				break;
14839 			}
14840 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
14841 			bcopy(&ire->ire_src_addr, (char *)opt + off,
14842 			    IP_ADDR_LEN);
14843 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
14844 			    ntohl(dst)));
14845 
14846 			/*
14847 			 * Check if our address is present more than
14848 			 * once as consecutive hops in source route.
14849 			 */
14850 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
14851 			    NULL, ALL_ZONES, MATCH_IRE_TYPE);
14852 			if (tmp_ire != NULL) {
14853 				ire_refrele(tmp_ire);
14854 				off += IP_ADDR_LEN;
14855 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
14856 				goto redo_srr;
14857 			}
14858 			ipha->ipha_dst = dst;
14859 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
14860 			ire_refrele(dst_ire);
14861 			break;
14862 		case IPOPT_RR:
14863 			off = opt[IPOPT_OFFSET];
14864 			off--;
14865 			if (optlen < IP_ADDR_LEN ||
14866 			    off > optlen - IP_ADDR_LEN) {
14867 				/* No more room - ignore */
14868 				ip1dbg((
14869 				    "ip_rput_forward_options: end of RR\n"));
14870 				break;
14871 			}
14872 			bcopy(&ire->ire_src_addr, (char *)opt + off,
14873 			    IP_ADDR_LEN);
14874 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
14875 			break;
14876 		case IPOPT_TS:
14877 			/* Insert timestamp if there is room */
14878 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
14879 			case IPOPT_TS_TSONLY:
14880 				off = IPOPT_TS_TIMELEN;
14881 				break;
14882 			case IPOPT_TS_PRESPEC:
14883 			case IPOPT_TS_PRESPEC_RFC791:
14884 				/* Verify that the address matched */
14885 				off = opt[IPOPT_OFFSET] - 1;
14886 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
14887 				dst_ire = ire_ctable_lookup(dst, 0,
14888 				    IRE_LOCAL, NULL, ALL_ZONES, MATCH_IRE_TYPE);
14889 				if (dst_ire == NULL) {
14890 					/* Not for us */
14891 					break;
14892 				}
14893 				ire_refrele(dst_ire);
14894 				/* FALLTHRU */
14895 			case IPOPT_TS_TSANDADDR:
14896 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
14897 				break;
14898 			default:
14899 				/*
14900 				 * ip_*put_options should have already
14901 				 * dropped this packet.
14902 				 */
14903 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
14904 				    "unknown IT - bug in ip_rput_options?\n");
14905 				return (0);	/* Keep "lint" happy */
14906 			}
14907 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
14908 				/* Increase overflow counter */
14909 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
14910 				opt[IPOPT_POS_OV_FLG] =
14911 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
14912 				    (off << 4));
14913 				break;
14914 			}
14915 			off = opt[IPOPT_OFFSET] - 1;
14916 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
14917 			case IPOPT_TS_PRESPEC:
14918 			case IPOPT_TS_PRESPEC_RFC791:
14919 			case IPOPT_TS_TSANDADDR:
14920 				bcopy(&ire->ire_src_addr,
14921 				    (char *)opt + off, IP_ADDR_LEN);
14922 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
14923 				/* FALLTHRU */
14924 			case IPOPT_TS_TSONLY:
14925 				off = opt[IPOPT_OFFSET] - 1;
14926 				/* Compute # of milliseconds since midnight */
14927 				gethrestime(&now);
14928 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
14929 				    now.tv_nsec / (NANOSEC / MILLISEC);
14930 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
14931 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
14932 				break;
14933 			}
14934 			break;
14935 		}
14936 	}
14937 	return (0);
14938 }
14939 
14940 /*
14941  * This is called after processing at least one of AH/ESP headers.
14942  *
14943  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
14944  * the actual, physical interface on which the packet was received,
14945  * but, when ip_strict_dst_multihoming is set to 1, could be the
14946  * interface which had the ipha_dst configured when the packet went
14947  * through ip_rput. The ill_index corresponding to the recv_ill
14948  * is saved in ipsec_in_rill_index
14949  */
14950 void
14951 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
14952 {
14953 	mblk_t *mp;
14954 	ipaddr_t dst;
14955 	in6_addr_t *v6dstp;
14956 	ipha_t *ipha;
14957 	ip6_t *ip6h;
14958 	ipsec_in_t *ii;
14959 	boolean_t ill_need_rele = B_FALSE;
14960 	boolean_t rill_need_rele = B_FALSE;
14961 	boolean_t ire_need_rele = B_FALSE;
14962 
14963 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
14964 	ASSERT(ii->ipsec_in_ill_index != 0);
14965 
14966 	mp = ipsec_mp->b_cont;
14967 	ASSERT(mp != NULL);
14968 
14969 
14970 	if (ill == NULL) {
14971 		ASSERT(recv_ill == NULL);
14972 		/*
14973 		 * We need to get the original queue on which ip_rput_local
14974 		 * or ip_rput_data_v6 was called.
14975 		 */
14976 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
14977 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL);
14978 		ill_need_rele = B_TRUE;
14979 
14980 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
14981 			recv_ill = ill_lookup_on_ifindex(
14982 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
14983 			    NULL, NULL, NULL, NULL);
14984 			rill_need_rele = B_TRUE;
14985 		} else {
14986 			recv_ill = ill;
14987 		}
14988 
14989 		if ((ill == NULL) || (recv_ill == NULL)) {
14990 			ip0dbg(("ip_fanout_proto_again: interface "
14991 			    "disappeared\n"));
14992 			if (ill != NULL)
14993 				ill_refrele(ill);
14994 			if (recv_ill != NULL)
14995 				ill_refrele(recv_ill);
14996 			freemsg(ipsec_mp);
14997 			return;
14998 		}
14999 	}
15000 
15001 	ASSERT(ill != NULL && recv_ill != NULL);
15002 
15003 	if (mp->b_datap->db_type == M_CTL) {
15004 		/*
15005 		 * AH/ESP is returning the ICMP message after
15006 		 * removing their headers. Fanout again till
15007 		 * it gets to the right protocol.
15008 		 */
15009 		if (ii->ipsec_in_v4) {
15010 			icmph_t *icmph;
15011 			int iph_hdr_length;
15012 			int hdr_length;
15013 
15014 			ipha = (ipha_t *)mp->b_rptr;
15015 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
15016 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
15017 			ipha = (ipha_t *)&icmph[1];
15018 			hdr_length = IPH_HDR_LENGTH(ipha);
15019 			/*
15020 			 * icmp_inbound_error_fanout may need to do pullupmsg.
15021 			 * Reset the type to M_DATA.
15022 			 */
15023 			mp->b_datap->db_type = M_DATA;
15024 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
15025 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
15026 			    B_FALSE, ill, ii->ipsec_in_zoneid);
15027 		} else {
15028 			icmp6_t *icmp6;
15029 			int hdr_length;
15030 
15031 			ip6h = (ip6_t *)mp->b_rptr;
15032 			/* Don't call hdr_length_v6() unless you have to. */
15033 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
15034 				hdr_length = ip_hdr_length_v6(mp, ip6h);
15035 			else
15036 				hdr_length = IPV6_HDR_LEN;
15037 
15038 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
15039 			/*
15040 			 * icmp_inbound_error_fanout_v6 may need to do
15041 			 * pullupmsg.  Reset the type to M_DATA.
15042 			 */
15043 			mp->b_datap->db_type = M_DATA;
15044 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
15045 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
15046 		}
15047 		if (ill_need_rele)
15048 			ill_refrele(ill);
15049 		if (rill_need_rele)
15050 			ill_refrele(recv_ill);
15051 		return;
15052 	}
15053 
15054 	if (ii->ipsec_in_v4) {
15055 		ipha = (ipha_t *)mp->b_rptr;
15056 		dst = ipha->ipha_dst;
15057 		if (CLASSD(dst)) {
15058 			/*
15059 			 * Multicast has to be delivered to all streams.
15060 			 */
15061 			dst = INADDR_BROADCAST;
15062 		}
15063 
15064 		if (ire == NULL) {
15065 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid);
15066 			if (ire == NULL) {
15067 				if (ill_need_rele)
15068 					ill_refrele(ill);
15069 				if (rill_need_rele)
15070 					ill_refrele(recv_ill);
15071 				ip1dbg(("ip_fanout_proto_again: "
15072 				    "IRE not found"));
15073 				freemsg(ipsec_mp);
15074 				return;
15075 			}
15076 			ire_need_rele = B_TRUE;
15077 		}
15078 
15079 		switch (ipha->ipha_protocol) {
15080 			case IPPROTO_UDP:
15081 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
15082 				    recv_ill);
15083 				if (ire_need_rele)
15084 					ire_refrele(ire);
15085 				break;
15086 			case IPPROTO_TCP:
15087 				if (!ire_need_rele)
15088 					IRE_REFHOLD(ire);
15089 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
15090 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
15091 				IRE_REFRELE(ire);
15092 				if (mp != NULL)
15093 					squeue_enter_chain(GET_SQUEUE(mp), mp,
15094 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
15095 				break;
15096 			case IPPROTO_SCTP:
15097 				if (!ire_need_rele)
15098 					IRE_REFHOLD(ire);
15099 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
15100 				    ipsec_mp, 0, ill->ill_rq, dst);
15101 				break;
15102 			default:
15103 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
15104 				    recv_ill);
15105 				if (ire_need_rele)
15106 					ire_refrele(ire);
15107 				break;
15108 		}
15109 	} else {
15110 		uint32_t rput_flags = 0;
15111 
15112 		ip6h = (ip6_t *)mp->b_rptr;
15113 		v6dstp = &ip6h->ip6_dst;
15114 		/*
15115 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
15116 		 * address.
15117 		 *
15118 		 * Currently, we don't store that state in the IPSEC_IN
15119 		 * message, and we may need to.
15120 		 */
15121 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
15122 		    IP6_IN_LLMCAST : 0);
15123 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
15124 		    NULL);
15125 	}
15126 	if (ill_need_rele)
15127 		ill_refrele(ill);
15128 	if (rill_need_rele)
15129 		ill_refrele(recv_ill);
15130 }
15131 
15132 /*
15133  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
15134  * returns 'true' if there are still fragments left on the queue, in
15135  * which case we restart the timer.
15136  */
15137 void
15138 ill_frag_timer(void *arg)
15139 {
15140 	ill_t	*ill = (ill_t *)arg;
15141 	boolean_t frag_pending;
15142 
15143 	mutex_enter(&ill->ill_lock);
15144 	ASSERT(!ill->ill_fragtimer_executing);
15145 	if (ill->ill_state_flags & ILL_CONDEMNED) {
15146 		ill->ill_frag_timer_id = 0;
15147 		mutex_exit(&ill->ill_lock);
15148 		return;
15149 	}
15150 	ill->ill_fragtimer_executing = 1;
15151 	mutex_exit(&ill->ill_lock);
15152 
15153 	frag_pending = ill_frag_timeout(ill, ip_g_frag_timeout);
15154 
15155 	/*
15156 	 * Restart the timer, if we have fragments pending or if someone
15157 	 * wanted us to be scheduled again.
15158 	 */
15159 	mutex_enter(&ill->ill_lock);
15160 	ill->ill_fragtimer_executing = 0;
15161 	ill->ill_frag_timer_id = 0;
15162 	if (frag_pending || ill->ill_fragtimer_needrestart)
15163 		ill_frag_timer_start(ill);
15164 	mutex_exit(&ill->ill_lock);
15165 }
15166 
15167 void
15168 ill_frag_timer_start(ill_t *ill)
15169 {
15170 	ASSERT(MUTEX_HELD(&ill->ill_lock));
15171 
15172 	/* If the ill is closing or opening don't proceed */
15173 	if (ill->ill_state_flags & ILL_CONDEMNED)
15174 		return;
15175 
15176 	if (ill->ill_fragtimer_executing) {
15177 		/*
15178 		 * ill_frag_timer is currently executing. Just record the
15179 		 * the fact that we want the timer to be restarted.
15180 		 * ill_frag_timer will post a timeout before it returns,
15181 		 * ensuring it will be called again.
15182 		 */
15183 		ill->ill_fragtimer_needrestart = 1;
15184 		return;
15185 	}
15186 
15187 	if (ill->ill_frag_timer_id == 0) {
15188 		/*
15189 		 * The timer is neither running nor is the timeout handler
15190 		 * executing. Post a timeout so that ill_frag_timer will be
15191 		 * called
15192 		 */
15193 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
15194 		    MSEC_TO_TICK(ip_g_frag_timo_ms >> 1));
15195 		ill->ill_fragtimer_needrestart = 0;
15196 	}
15197 }
15198 
15199 /*
15200  * This routine is needed for loopback when forwarding multicasts.
15201  *
15202  * IPQoS Notes:
15203  * IPPF processing is done in fanout routines.
15204  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
15205  * processing for IPSec packets is done when it comes back in clear.
15206  * NOTE : The callers of this function need to do the ire_refrele for the
15207  *	  ire that is being passed in.
15208  */
15209 void
15210 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
15211     ill_t *recv_ill)
15212 {
15213 	ill_t	*ill = (ill_t *)q->q_ptr;
15214 	uint32_t	sum;
15215 	uint32_t	u1;
15216 	uint32_t	u2;
15217 	int		hdr_length;
15218 	boolean_t	mctl_present;
15219 	mblk_t		*first_mp = mp;
15220 	mblk_t		*hada_mp = NULL;
15221 	ipha_t		*inner_ipha;
15222 
15223 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
15224 	    "ip_rput_locl_start: q %p", q);
15225 
15226 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
15227 
15228 
15229 #define	rptr	((uchar_t *)ipha)
15230 #define	iphs	((uint16_t *)ipha)
15231 
15232 	/*
15233 	 * no UDP or TCP packet should come here anymore.
15234 	 */
15235 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
15236 	    (ipha->ipha_protocol != IPPROTO_UDP));
15237 
15238 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
15239 	if (mctl_present &&
15240 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
15241 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
15242 
15243 		/*
15244 		 * It's an IPsec accelerated packet.
15245 		 * Keep a pointer to the data attributes around until
15246 		 * we allocate the ipsec_info_t.
15247 		 */
15248 		IPSECHW_DEBUG(IPSECHW_PKT,
15249 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
15250 		hada_mp = first_mp;
15251 		hada_mp->b_cont = NULL;
15252 		/*
15253 		 * Since it is accelerated, it comes directly from
15254 		 * the ill and the data attributes is followed by
15255 		 * the packet data.
15256 		 */
15257 		ASSERT(mp->b_datap->db_type != M_CTL);
15258 		first_mp = mp;
15259 		mctl_present = B_FALSE;
15260 	}
15261 
15262 	/*
15263 	 * IF M_CTL is not present, then ipsec_in_is_secure
15264 	 * should return B_TRUE. There is a case where loopback
15265 	 * packets has an M_CTL in the front with all the
15266 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
15267 	 * ipsec_in_is_secure will return B_FALSE. As loopback
15268 	 * packets never comes here, it is safe to ASSERT the
15269 	 * following.
15270 	 */
15271 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
15272 
15273 
15274 	/* u1 is # words of IP options */
15275 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
15276 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
15277 
15278 	if (u1) {
15279 		if (!ip_options_cksum(q, mp, ipha, ire)) {
15280 			if (hada_mp != NULL)
15281 				freemsg(hada_mp);
15282 			return;
15283 		}
15284 	} else {
15285 		/* Check the IP header checksum.  */
15286 #define	uph	((uint16_t *)ipha)
15287 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
15288 		    uph[6] + uph[7] + uph[8] + uph[9];
15289 #undef  uph
15290 		/* finish doing IP checksum */
15291 		sum = (sum & 0xFFFF) + (sum >> 16);
15292 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
15293 		/*
15294 		 * Don't verify header checksum if this packet is coming
15295 		 * back from AH/ESP as we already did it.
15296 		 */
15297 		if (!mctl_present && (sum && sum != 0xFFFF)) {
15298 			BUMP_MIB(&ip_mib, ipInCksumErrs);
15299 			goto drop_pkt;
15300 		}
15301 	}
15302 
15303 	/*
15304 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
15305 	 * might be called more than once for secure packets, count only
15306 	 * the first time.
15307 	 */
15308 	if (!mctl_present) {
15309 		UPDATE_IB_PKT_COUNT(ire);
15310 		ire->ire_last_used_time = lbolt;
15311 	}
15312 
15313 	/* Check for fragmentation offset. */
15314 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
15315 	u1 = u2 & (IPH_MF | IPH_OFFSET);
15316 	if (u1) {
15317 		/*
15318 		 * We re-assemble fragments before we do the AH/ESP
15319 		 * processing. Thus, M_CTL should not be present
15320 		 * while we are re-assembling.
15321 		 */
15322 		ASSERT(!mctl_present);
15323 		ASSERT(first_mp == mp);
15324 		if (!ip_rput_fragment(q, &mp, ipha)) {
15325 			return;
15326 		}
15327 		/*
15328 		 * Make sure that first_mp points back to mp as
15329 		 * the mp we came in with could have changed in
15330 		 * ip_rput_fragment().
15331 		 */
15332 		ipha = (ipha_t *)mp->b_rptr;
15333 		first_mp = mp;
15334 	}
15335 
15336 	/*
15337 	 * Clear hardware checksumming flag as it is currently only
15338 	 * used by TCP and UDP.
15339 	 */
15340 	mp->b_datap->db_struioun.cksum.flags = 0;
15341 
15342 	/* Now we have a complete datagram, destined for this machine. */
15343 	u1 = IPH_HDR_LENGTH(ipha);
15344 	switch (ipha->ipha_protocol) {
15345 	case IPPROTO_ICMP: {
15346 		ire_t		*ire_zone;
15347 		ilm_t		*ilm;
15348 		mblk_t		*mp1;
15349 		zoneid_t	last_zoneid;
15350 
15351 		if (CLASSD(ipha->ipha_dst) &&
15352 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
15353 			ASSERT(ire->ire_type == IRE_BROADCAST);
15354 			/*
15355 			 * In the multicast case, applications may have joined
15356 			 * the group from different zones, so we need to deliver
15357 			 * the packet to each of them. Loop through the
15358 			 * multicast memberships structures (ilm) on the receive
15359 			 * ill and send a copy of the packet up each matching
15360 			 * one. However, we don't do this for multicasts sent on
15361 			 * the loopback interface (PHYI_LOOPBACK flag set) as
15362 			 * they must stay in the sender's zone.
15363 			 *
15364 			 * ilm_add_v6() ensures that ilms in the same zone are
15365 			 * contiguous in the ill_ilm list. We use this property
15366 			 * to avoid sending duplicates needed when two
15367 			 * applications in the same zone join the same group on
15368 			 * different logical interfaces: we ignore the ilm if
15369 			 * its zoneid is the same as the last matching one.
15370 			 * In addition, the sending of the packet for
15371 			 * ire_zoneid is delayed until all of the other ilms
15372 			 * have been exhausted.
15373 			 */
15374 			last_zoneid = -1;
15375 			ILM_WALKER_HOLD(recv_ill);
15376 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
15377 			    ilm = ilm->ilm_next) {
15378 				if ((ilm->ilm_flags & ILM_DELETED) ||
15379 				    ipha->ipha_dst != ilm->ilm_addr ||
15380 				    ilm->ilm_zoneid == last_zoneid ||
15381 				    ilm->ilm_zoneid == ire->ire_zoneid ||
15382 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
15383 					continue;
15384 				mp1 = ip_copymsg(first_mp);
15385 				if (mp1 == NULL)
15386 					continue;
15387 				icmp_inbound(q, mp1, B_TRUE, ill,
15388 				    0, sum, mctl_present, B_TRUE,
15389 				    recv_ill, ilm->ilm_zoneid);
15390 				last_zoneid = ilm->ilm_zoneid;
15391 			}
15392 			ILM_WALKER_RELE(recv_ill);
15393 		} else if (ire->ire_type == IRE_BROADCAST) {
15394 			/*
15395 			 * In the broadcast case, there may be many zones
15396 			 * which need a copy of the packet delivered to them.
15397 			 * There is one IRE_BROADCAST per broadcast address
15398 			 * and per zone; we walk those using a helper function.
15399 			 * In addition, the sending of the packet for ire is
15400 			 * delayed until all of the other ires have been
15401 			 * processed.
15402 			 */
15403 			IRB_REFHOLD(ire->ire_bucket);
15404 			ire_zone = NULL;
15405 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
15406 			    ire)) != NULL) {
15407 				mp1 = ip_copymsg(first_mp);
15408 				if (mp1 == NULL)
15409 					continue;
15410 
15411 				UPDATE_IB_PKT_COUNT(ire_zone);
15412 				ire_zone->ire_last_used_time = lbolt;
15413 				icmp_inbound(q, mp1, B_TRUE, ill,
15414 				    0, sum, mctl_present, B_TRUE,
15415 				    recv_ill, ire_zone->ire_zoneid);
15416 			}
15417 			IRB_REFRELE(ire->ire_bucket);
15418 		}
15419 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
15420 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
15421 		    ire->ire_zoneid);
15422 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15423 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
15424 		return;
15425 	}
15426 	case IPPROTO_IGMP:
15427 		/*
15428 		 * If we are not willing to accept IGMP packets in clear,
15429 		 * then check with global policy.
15430 		 */
15431 		if (igmp_accept_clear_messages == 0) {
15432 			first_mp = ipsec_check_global_policy(first_mp, NULL,
15433 			    ipha, NULL, mctl_present);
15434 			if (first_mp == NULL)
15435 				return;
15436 		}
15437 		if (igmp_input(q, mp, ill)) {
15438 			/* Bad packet - discarded by igmp_input */
15439 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15440 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
15441 			if (mctl_present)
15442 				freeb(first_mp);
15443 			return;
15444 		}
15445 		/*
15446 		 * igmp_input() may have pulled up the message so ipha needs to
15447 		 * be reinitialized.
15448 		 */
15449 		ipha = (ipha_t *)mp->b_rptr;
15450 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
15451 			/* No user-level listener for IGMP packets */
15452 			goto drop_pkt;
15453 		}
15454 		/* deliver to local raw users */
15455 		break;
15456 	case IPPROTO_PIM:
15457 		/*
15458 		 * If we are not willing to accept PIM packets in clear,
15459 		 * then check with global policy.
15460 		 */
15461 		if (pim_accept_clear_messages == 0) {
15462 			first_mp = ipsec_check_global_policy(first_mp, NULL,
15463 			    ipha, NULL, mctl_present);
15464 			if (first_mp == NULL)
15465 				return;
15466 		}
15467 		if (pim_input(q, mp) != 0) {
15468 			/* Bad packet - discarded by pim_input */
15469 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15470 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
15471 			if (mctl_present)
15472 				freeb(first_mp);
15473 			return;
15474 		}
15475 
15476 		/*
15477 		 * pim_input() may have pulled up the message so ipha needs to
15478 		 * be reinitialized.
15479 		 */
15480 		ipha = (ipha_t *)mp->b_rptr;
15481 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
15482 			/* No user-level listener for PIM packets */
15483 			goto drop_pkt;
15484 		}
15485 		/* deliver to local raw users */
15486 		break;
15487 	case IPPROTO_ENCAP:
15488 		/*
15489 		 * Handle self-encapsulated packets (IP-in-IP where
15490 		 * the inner addresses == the outer addresses).
15491 		 */
15492 		hdr_length = IPH_HDR_LENGTH(ipha);
15493 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
15494 		    mp->b_wptr) {
15495 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
15496 			    sizeof (ipha_t) - mp->b_rptr)) {
15497 				BUMP_MIB(&ip_mib, ipInDiscards);
15498 				freemsg(first_mp);
15499 				return;
15500 			}
15501 			ipha = (ipha_t *)mp->b_rptr;
15502 		}
15503 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
15504 		/*
15505 		 * Check the sanity of the inner IP header.
15506 		 */
15507 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
15508 			BUMP_MIB(&ip_mib, ipInDiscards);
15509 			freemsg(first_mp);
15510 			return;
15511 		}
15512 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
15513 			BUMP_MIB(&ip_mib, ipInDiscards);
15514 			freemsg(first_mp);
15515 			return;
15516 		}
15517 		if (inner_ipha->ipha_src == ipha->ipha_src &&
15518 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
15519 			ipsec_in_t *ii;
15520 
15521 			/*
15522 			 * Self-encapsulated tunnel packet. Remove
15523 			 * the outer IP header and fanout again.
15524 			 * We also need to make sure that the inner
15525 			 * header is pulled up until options.
15526 			 */
15527 			mp->b_rptr = (uchar_t *)inner_ipha;
15528 			ipha = inner_ipha;
15529 			hdr_length = IPH_HDR_LENGTH(ipha);
15530 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
15531 				if (!pullupmsg(mp, (uchar_t *)ipha +
15532 				    + hdr_length - mp->b_rptr)) {
15533 					freemsg(first_mp);
15534 					return;
15535 				}
15536 				ipha = (ipha_t *)mp->b_rptr;
15537 			}
15538 			if (!mctl_present) {
15539 				ASSERT(first_mp == mp);
15540 				/*
15541 				 * This means that somebody is sending
15542 				 * Self-encapsualted packets without AH/ESP.
15543 				 * If AH/ESP was present, we would have already
15544 				 * allocated the first_mp.
15545 				 */
15546 				if ((first_mp = ipsec_in_alloc(B_TRUE)) ==
15547 				    NULL) {
15548 					ip1dbg(("ip_proto_input: IPSEC_IN "
15549 					    "allocation failure.\n"));
15550 					BUMP_MIB(&ip_mib, ipInDiscards);
15551 					freemsg(mp);
15552 					return;
15553 				}
15554 				first_mp->b_cont = mp;
15555 			}
15556 			/*
15557 			 * We generally store the ill_index if we need to
15558 			 * do IPSEC processing as we lose the ill queue when
15559 			 * we come back. But in this case, we never should
15560 			 * have to store the ill_index here as it should have
15561 			 * been stored previously when we processed the
15562 			 * AH/ESP header in this routine or for non-ipsec
15563 			 * cases, we still have the queue. But for some bad
15564 			 * packets from the wire, we can get to IPSEC after
15565 			 * this and we better store the index for that case.
15566 			 */
15567 			ill = (ill_t *)q->q_ptr;
15568 			ii = (ipsec_in_t *)first_mp->b_rptr;
15569 			ii->ipsec_in_ill_index =
15570 			    ill->ill_phyint->phyint_ifindex;
15571 			ii->ipsec_in_rill_index =
15572 			    recv_ill->ill_phyint->phyint_ifindex;
15573 			if (ii->ipsec_in_decaps) {
15574 				/*
15575 				 * This packet is self-encapsulated multiple
15576 				 * times. We don't want to recurse infinitely.
15577 				 * To keep it simple, drop the packet.
15578 				 */
15579 				BUMP_MIB(&ip_mib, ipInDiscards);
15580 				freemsg(first_mp);
15581 				return;
15582 			}
15583 			ii->ipsec_in_decaps = B_TRUE;
15584 			ip_proto_input(q, first_mp, ipha, ire, recv_ill);
15585 			return;
15586 		}
15587 		break;
15588 	case IPPROTO_AH:
15589 	case IPPROTO_ESP: {
15590 		/*
15591 		 * Fast path for AH/ESP. If this is the first time
15592 		 * we are sending a datagram to AH/ESP, allocate
15593 		 * a IPSEC_IN message and prepend it. Otherwise,
15594 		 * just fanout.
15595 		 */
15596 
15597 		int ipsec_rc;
15598 		ipsec_in_t *ii;
15599 
15600 		IP_STAT(ipsec_proto_ahesp);
15601 		if (!mctl_present) {
15602 			ASSERT(first_mp == mp);
15603 			if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
15604 				ip1dbg(("ip_proto_input: IPSEC_IN "
15605 				    "allocation failure.\n"));
15606 				freemsg(hada_mp); /* okay ifnull */
15607 				BUMP_MIB(&ip_mib, ipInDiscards);
15608 				freemsg(mp);
15609 				return;
15610 			}
15611 			/*
15612 			 * Store the ill_index so that when we come back
15613 			 * from IPSEC we ride on the same queue.
15614 			 */
15615 			ill = (ill_t *)q->q_ptr;
15616 			ii = (ipsec_in_t *)first_mp->b_rptr;
15617 			ii->ipsec_in_ill_index =
15618 			    ill->ill_phyint->phyint_ifindex;
15619 			ii->ipsec_in_rill_index =
15620 			    recv_ill->ill_phyint->phyint_ifindex;
15621 			first_mp->b_cont = mp;
15622 			/*
15623 			 * Cache hardware acceleration info.
15624 			 */
15625 			if (hada_mp != NULL) {
15626 				IPSECHW_DEBUG(IPSECHW_PKT,
15627 				    ("ip_rput_local: caching data attr.\n"));
15628 				ii->ipsec_in_accelerated = B_TRUE;
15629 				ii->ipsec_in_da = hada_mp;
15630 				hada_mp = NULL;
15631 			}
15632 		} else {
15633 			ii = (ipsec_in_t *)first_mp->b_rptr;
15634 		}
15635 
15636 		if (!ipsec_loaded()) {
15637 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
15638 			    ire->ire_zoneid);
15639 			return;
15640 		}
15641 
15642 		/* select inbound SA and have IPsec process the pkt */
15643 		if (ipha->ipha_protocol == IPPROTO_ESP) {
15644 			esph_t *esph = ipsec_inbound_esp_sa(first_mp);
15645 			if (esph == NULL)
15646 				return;
15647 			ASSERT(ii->ipsec_in_esp_sa != NULL);
15648 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
15649 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
15650 			    first_mp, esph);
15651 		} else {
15652 			ah_t *ah = ipsec_inbound_ah_sa(first_mp);
15653 			if (ah == NULL)
15654 				return;
15655 			ASSERT(ii->ipsec_in_ah_sa != NULL);
15656 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
15657 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
15658 			    first_mp, ah);
15659 		}
15660 
15661 		switch (ipsec_rc) {
15662 		case IPSEC_STATUS_SUCCESS:
15663 			break;
15664 		case IPSEC_STATUS_FAILED:
15665 			BUMP_MIB(&ip_mib, ipInDiscards);
15666 			/* FALLTHRU */
15667 		case IPSEC_STATUS_PENDING:
15668 			return;
15669 		}
15670 		/* we're done with IPsec processing, send it up */
15671 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
15672 		return;
15673 	}
15674 	default:
15675 		break;
15676 	}
15677 	/*
15678 	 * Handle protocols with which IP is less intimate.  There
15679 	 * can be more than one stream bound to a particular
15680 	 * protocol.  When this is the case, each one gets a copy
15681 	 * of any incoming packets.
15682 	 */
15683 	ip_fanout_proto(q, first_mp, ill, ipha,
15684 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
15685 	    B_TRUE, recv_ill, ire->ire_zoneid);
15686 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15687 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
15688 	return;
15689 
15690 drop_pkt:
15691 	freemsg(first_mp);
15692 	if (hada_mp != NULL)
15693 		freeb(hada_mp);
15694 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
15695 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
15696 #undef	rptr
15697 #undef  iphs
15698 
15699 }
15700 
15701 /*
15702  * Update any source route, record route or timestamp options.
15703  * Check that we are at end of strict source route.
15704  * The options have already been checked for sanity in ip_rput_options().
15705  */
15706 static boolean_t
15707 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
15708 {
15709 	ipoptp_t	opts;
15710 	uchar_t		*opt;
15711 	uint8_t		optval;
15712 	uint8_t		optlen;
15713 	ipaddr_t	dst;
15714 	uint32_t	ts;
15715 	ire_t		*dst_ire;
15716 	timestruc_t	now;
15717 
15718 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
15719 
15720 	ip2dbg(("ip_rput_local_options\n"));
15721 
15722 	for (optval = ipoptp_first(&opts, ipha);
15723 	    optval != IPOPT_EOL;
15724 	    optval = ipoptp_next(&opts)) {
15725 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
15726 		opt = opts.ipoptp_cur;
15727 		optlen = opts.ipoptp_len;
15728 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
15729 		    optval, optlen));
15730 		switch (optval) {
15731 			uint32_t off;
15732 		case IPOPT_SSRR:
15733 		case IPOPT_LSRR:
15734 			off = opt[IPOPT_OFFSET];
15735 			off--;
15736 			if (optlen < IP_ADDR_LEN ||
15737 			    off > optlen - IP_ADDR_LEN) {
15738 				/* End of source route */
15739 				ip1dbg(("ip_rput_local_options: end of SR\n"));
15740 				break;
15741 			}
15742 			/*
15743 			 * This will only happen if two consecutive entries
15744 			 * in the source route contains our address or if
15745 			 * it is a packet with a loose source route which
15746 			 * reaches us before consuming the whole source route
15747 			 */
15748 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
15749 			if (optval == IPOPT_SSRR) {
15750 				goto bad_src_route;
15751 			}
15752 			/*
15753 			 * Hack: instead of dropping the packet truncate the
15754 			 * source route to what has been used by filling the
15755 			 * rest with IPOPT_NOP.
15756 			 */
15757 			opt[IPOPT_OLEN] = (uint8_t)off;
15758 			while (off < optlen) {
15759 				opt[off++] = IPOPT_NOP;
15760 			}
15761 			break;
15762 		case IPOPT_RR:
15763 			off = opt[IPOPT_OFFSET];
15764 			off--;
15765 			if (optlen < IP_ADDR_LEN ||
15766 			    off > optlen - IP_ADDR_LEN) {
15767 				/* No more room - ignore */
15768 				ip1dbg((
15769 				    "ip_rput_local_options: end of RR\n"));
15770 				break;
15771 			}
15772 			bcopy(&ire->ire_src_addr, (char *)opt + off,
15773 			    IP_ADDR_LEN);
15774 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15775 			break;
15776 		case IPOPT_TS:
15777 			/* Insert timestamp if there is romm */
15778 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15779 			case IPOPT_TS_TSONLY:
15780 				off = IPOPT_TS_TIMELEN;
15781 				break;
15782 			case IPOPT_TS_PRESPEC:
15783 			case IPOPT_TS_PRESPEC_RFC791:
15784 				/* Verify that the address matched */
15785 				off = opt[IPOPT_OFFSET] - 1;
15786 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
15787 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
15788 				    NULL, ALL_ZONES, MATCH_IRE_TYPE);
15789 				if (dst_ire == NULL) {
15790 					/* Not for us */
15791 					break;
15792 				}
15793 				ire_refrele(dst_ire);
15794 				/* FALLTHRU */
15795 			case IPOPT_TS_TSANDADDR:
15796 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
15797 				break;
15798 			default:
15799 				/*
15800 				 * ip_*put_options should have already
15801 				 * dropped this packet.
15802 				 */
15803 				cmn_err(CE_PANIC, "ip_rput_local_options: "
15804 				    "unknown IT - bug in ip_rput_options?\n");
15805 				return (B_TRUE);	/* Keep "lint" happy */
15806 			}
15807 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
15808 				/* Increase overflow counter */
15809 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
15810 				opt[IPOPT_POS_OV_FLG] =
15811 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
15812 				    (off << 4));
15813 				break;
15814 			}
15815 			off = opt[IPOPT_OFFSET] - 1;
15816 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15817 			case IPOPT_TS_PRESPEC:
15818 			case IPOPT_TS_PRESPEC_RFC791:
15819 			case IPOPT_TS_TSANDADDR:
15820 				bcopy(&ire->ire_src_addr, (char *)opt + off,
15821 				    IP_ADDR_LEN);
15822 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15823 				/* FALLTHRU */
15824 			case IPOPT_TS_TSONLY:
15825 				off = opt[IPOPT_OFFSET] - 1;
15826 				/* Compute # of milliseconds since midnight */
15827 				gethrestime(&now);
15828 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
15829 				    now.tv_nsec / (NANOSEC / MILLISEC);
15830 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
15831 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
15832 				break;
15833 			}
15834 			break;
15835 		}
15836 	}
15837 	return (B_TRUE);
15838 
15839 bad_src_route:
15840 	q = WR(q);
15841 	/* make sure we clear any indication of a hardware checksum */
15842 	mp->b_datap->db_struioun.cksum.flags = 0;
15843 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
15844 	return (B_FALSE);
15845 
15846 }
15847 
15848 /*
15849  * Process IP options in an inbound packet.  If an option affects the
15850  * effective destination address, return the next hop address via dstp.
15851  * Returns -1 if something fails in which case an ICMP error has been sent
15852  * and mp freed.
15853  */
15854 static int
15855 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp)
15856 {
15857 	ipoptp_t	opts;
15858 	uchar_t		*opt;
15859 	uint8_t		optval;
15860 	uint8_t		optlen;
15861 	ipaddr_t	dst;
15862 	intptr_t	code = 0;
15863 	ire_t		*ire = NULL;
15864 
15865 	ip2dbg(("ip_rput_options\n"));
15866 	dst = ipha->ipha_dst;
15867 	for (optval = ipoptp_first(&opts, ipha);
15868 	    optval != IPOPT_EOL;
15869 	    optval = ipoptp_next(&opts)) {
15870 		opt = opts.ipoptp_cur;
15871 		optlen = opts.ipoptp_len;
15872 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
15873 		    optval, optlen));
15874 		/*
15875 		 * Note: we need to verify the checksum before we
15876 		 * modify anything thus this routine only extracts the next
15877 		 * hop dst from any source route.
15878 		 */
15879 		switch (optval) {
15880 			uint32_t off;
15881 		case IPOPT_SSRR:
15882 		case IPOPT_LSRR:
15883 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
15884 			    ALL_ZONES, MATCH_IRE_TYPE);
15885 			if (ire == NULL) {
15886 				if (optval == IPOPT_SSRR) {
15887 					ip1dbg(("ip_rput_options: not next"
15888 					    " strict source route 0x%x\n",
15889 					    ntohl(dst)));
15890 					code = (char *)&ipha->ipha_dst -
15891 					    (char *)ipha;
15892 					goto param_prob; /* RouterReq's */
15893 				}
15894 				ip2dbg(("ip_rput_options: "
15895 				    "not next source route 0x%x\n",
15896 				    ntohl(dst)));
15897 				break;
15898 			}
15899 			ire_refrele(ire);
15900 
15901 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
15902 				ip1dbg((
15903 				    "ip_rput_options: bad option offset\n"));
15904 				code = (char *)&opt[IPOPT_OLEN] -
15905 				    (char *)ipha;
15906 				goto param_prob;
15907 			}
15908 			off = opt[IPOPT_OFFSET];
15909 			off--;
15910 		redo_srr:
15911 			if (optlen < IP_ADDR_LEN ||
15912 			    off > optlen - IP_ADDR_LEN) {
15913 				/* End of source route */
15914 				ip1dbg(("ip_rput_options: end of SR\n"));
15915 				break;
15916 			}
15917 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
15918 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
15919 			    ntohl(dst)));
15920 
15921 			/*
15922 			 * Check if our address is present more than
15923 			 * once as consecutive hops in source route.
15924 			 * XXX verify per-interface ip_forwarding
15925 			 * for source route?
15926 			 */
15927 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
15928 			    ALL_ZONES, MATCH_IRE_TYPE);
15929 
15930 			if (ire != NULL) {
15931 				ire_refrele(ire);
15932 				off += IP_ADDR_LEN;
15933 				goto redo_srr;
15934 			}
15935 
15936 			if (dst == htonl(INADDR_LOOPBACK)) {
15937 				ip1dbg(("ip_rput_options: loopback addr in "
15938 				    "source route!\n"));
15939 				goto bad_src_route;
15940 			}
15941 			/*
15942 			 * For strict: verify that dst is directly
15943 			 * reachable.
15944 			 */
15945 			if (optval == IPOPT_SSRR) {
15946 				ire = ire_ftable_lookup(dst, 0, 0,
15947 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
15948 				    MATCH_IRE_TYPE);
15949 				if (ire == NULL) {
15950 					ip1dbg(("ip_rput_options: SSRR not "
15951 					    "directly reachable: 0x%x\n",
15952 					    ntohl(dst)));
15953 					goto bad_src_route;
15954 				}
15955 				ire_refrele(ire);
15956 			}
15957 			/*
15958 			 * Defer update of the offset and the record route
15959 			 * until the packet is forwarded.
15960 			 */
15961 			break;
15962 		case IPOPT_RR:
15963 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
15964 				ip1dbg((
15965 				    "ip_rput_options: bad option offset\n"));
15966 				code = (char *)&opt[IPOPT_OLEN] -
15967 				    (char *)ipha;
15968 				goto param_prob;
15969 			}
15970 			break;
15971 		case IPOPT_TS:
15972 			/*
15973 			 * Verify that length >= 5 and that there is either
15974 			 * room for another timestamp or that the overflow
15975 			 * counter is not maxed out.
15976 			 */
15977 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
15978 			if (optlen < IPOPT_MINLEN_IT) {
15979 				goto param_prob;
15980 			}
15981 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
15982 				ip1dbg((
15983 				    "ip_rput_options: bad option offset\n"));
15984 				code = (char *)&opt[IPOPT_OFFSET] -
15985 				    (char *)ipha;
15986 				goto param_prob;
15987 			}
15988 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15989 			case IPOPT_TS_TSONLY:
15990 				off = IPOPT_TS_TIMELEN;
15991 				break;
15992 			case IPOPT_TS_TSANDADDR:
15993 			case IPOPT_TS_PRESPEC:
15994 			case IPOPT_TS_PRESPEC_RFC791:
15995 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
15996 				break;
15997 			default:
15998 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
15999 				    (char *)ipha;
16000 				goto param_prob;
16001 			}
16002 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
16003 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
16004 				/*
16005 				 * No room and the overflow counter is 15
16006 				 * already.
16007 				 */
16008 				goto param_prob;
16009 			}
16010 			break;
16011 		}
16012 	}
16013 
16014 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
16015 		*dstp = dst;
16016 		return (0);
16017 	}
16018 
16019 	ip1dbg(("ip_rput_options: error processing IP options."));
16020 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
16021 
16022 param_prob:
16023 	q = WR(q);
16024 	/* make sure we clear any indication of a hardware checksum */
16025 	mp->b_datap->db_struioun.cksum.flags = 0;
16026 	icmp_param_problem(q, mp, (uint8_t)code);
16027 	return (-1);
16028 
16029 bad_src_route:
16030 	q = WR(q);
16031 	/* make sure we clear any indication of a hardware checksum */
16032 	mp->b_datap->db_struioun.cksum.flags = 0;
16033 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
16034 	return (-1);
16035 }
16036 
16037 /*
16038  * IP & ICMP info in >=14 msg's ...
16039  *  - ip fixed part (mib2_ip_t)
16040  *  - icmp fixed part (mib2_icmp_t)
16041  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
16042  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
16043  *  - ipNetToMediaEntryTable (ip 22)	IPv4 IREs for on-link destinations
16044  *  - ip multicast membership (ip_member_t)
16045  *  - ip multicast source filtering (ip_grpsrc_t)
16046  *  - igmp fixed part (struct igmpstat)
16047  *  - multicast routing stats (struct mrtstat)
16048  *  - multicast routing vifs (array of struct vifctl)
16049  *  - multicast routing routes (array of struct mfcctl)
16050  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
16051  *					One per ill plus one generic
16052  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
16053  *					One per ill plus one generic
16054  *  - ipv6RouteEntry			all IPv6 IREs
16055  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
16056  *  - ipv6AddrEntry			all IPv6 ipifs
16057  *  - ipv6 multicast membership (ipv6_member_t)
16058  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
16059  *
16060  * IP_ROUTE and IP_MEDIA are augmented in arp to include arp cache entries not
16061  * already present.
16062  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part
16063  * already filled in by caller.
16064  * Return value of 0 indicates that no messages were sent and caller
16065  * should free mpctl.
16066  */
16067 int
16068 ip_snmp_get(queue_t *q, mblk_t *mpctl)
16069 {
16070 
16071 	if (mpctl == NULL || mpctl->b_cont == NULL) {
16072 		return (0);
16073 	}
16074 
16075 	if ((mpctl = ip_snmp_get_mib2_ip(q, mpctl)) == NULL) {
16076 		return (1);
16077 	}
16078 
16079 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl)) == NULL) {
16080 		return (1);
16081 	}
16082 
16083 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl)) == NULL) {
16084 		return (1);
16085 	}
16086 
16087 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl)) == NULL) {
16088 		return (1);
16089 	}
16090 
16091 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl)) == NULL) {
16092 		return (1);
16093 	}
16094 
16095 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl)) == NULL) {
16096 		return (1);
16097 	}
16098 
16099 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl)) == NULL) {
16100 		return (1);
16101 	}
16102 
16103 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl)) == NULL) {
16104 		return (1);
16105 	}
16106 
16107 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl)) == NULL) {
16108 		return (1);
16109 	}
16110 
16111 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl)) == NULL) {
16112 		return (1);
16113 	}
16114 
16115 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl)) == NULL) {
16116 		return (1);
16117 	}
16118 
16119 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl)) == NULL) {
16120 		return (1);
16121 	}
16122 
16123 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl)) == NULL) {
16124 		return (1);
16125 	}
16126 
16127 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl)) == NULL) {
16128 		return (1);
16129 	}
16130 
16131 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl)) == NULL) {
16132 		return (1);
16133 	}
16134 
16135 	if ((mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl)) == NULL) {
16136 		return (1);
16137 	}
16138 
16139 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl)) == NULL) {
16140 		return (1);
16141 	}
16142 	freemsg(mpctl);
16143 	return (1);
16144 }
16145 
16146 
16147 /* Get global IPv4 statistics */
16148 static mblk_t *
16149 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl)
16150 {
16151 	struct opthdr		*optp;
16152 	mblk_t			*mp2ctl;
16153 
16154 	/*
16155 	 * make a copy of the original message
16156 	 */
16157 	mp2ctl = copymsg(mpctl);
16158 
16159 	/* fixed length IP structure... */
16160 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16161 	optp->level = MIB2_IP;
16162 	optp->name = 0;
16163 	SET_MIB(ip_mib.ipForwarding,
16164 	    (WE_ARE_FORWARDING ? 1 : 2));
16165 	SET_MIB(ip_mib.ipDefaultTTL,
16166 	    (uint32_t)ip_def_ttl);
16167 	SET_MIB(ip_mib.ipReasmTimeout,
16168 	    ip_g_frag_timeout);
16169 	SET_MIB(ip_mib.ipAddrEntrySize,
16170 	    sizeof (mib2_ipAddrEntry_t));
16171 	SET_MIB(ip_mib.ipRouteEntrySize,
16172 	    sizeof (mib2_ipRouteEntry_t));
16173 	SET_MIB(ip_mib.ipNetToMediaEntrySize,
16174 	    sizeof (mib2_ipNetToMediaEntry_t));
16175 	SET_MIB(ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
16176 	SET_MIB(ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
16177 	if (!snmp_append_data(mpctl->b_cont, (char *)&ip_mib,
16178 	    (int)sizeof (ip_mib))) {
16179 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
16180 		    (uint_t)sizeof (ip_mib)));
16181 	}
16182 
16183 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16184 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
16185 	    (int)optp->level, (int)optp->name, (int)optp->len));
16186 	qreply(q, mpctl);
16187 	return (mp2ctl);
16188 }
16189 
16190 /* Global IPv4 ICMP statistics */
16191 static mblk_t *
16192 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl)
16193 {
16194 	struct opthdr		*optp;
16195 	mblk_t			*mp2ctl;
16196 
16197 	/*
16198 	 * Make a copy of the original message
16199 	 */
16200 	mp2ctl = copymsg(mpctl);
16201 
16202 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16203 	optp->level = MIB2_ICMP;
16204 	optp->name = 0;
16205 	if (!snmp_append_data(mpctl->b_cont, (char *)&icmp_mib,
16206 	    (int)sizeof (icmp_mib))) {
16207 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
16208 		    (uint_t)sizeof (icmp_mib)));
16209 	}
16210 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16211 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
16212 	    (int)optp->level, (int)optp->name, (int)optp->len));
16213 	qreply(q, mpctl);
16214 	return (mp2ctl);
16215 }
16216 
16217 /* Global IPv4 IGMP statistics */
16218 static mblk_t *
16219 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl)
16220 {
16221 	struct opthdr		*optp;
16222 	mblk_t			*mp2ctl;
16223 
16224 	/*
16225 	 * make a copy of the original message
16226 	 */
16227 	mp2ctl = copymsg(mpctl);
16228 
16229 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16230 	optp->level = EXPER_IGMP;
16231 	optp->name = 0;
16232 	if (!snmp_append_data(mpctl->b_cont, (char *)&igmpstat,
16233 	    (int)sizeof (igmpstat))) {
16234 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
16235 		    (uint_t)sizeof (igmpstat)));
16236 	}
16237 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16238 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
16239 	    (int)optp->level, (int)optp->name, (int)optp->len));
16240 	qreply(q, mpctl);
16241 	return (mp2ctl);
16242 }
16243 
16244 /* Global IPv4 Multicast Routing statistics */
16245 static mblk_t *
16246 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl)
16247 {
16248 	struct opthdr		*optp;
16249 	mblk_t			*mp2ctl;
16250 
16251 	/*
16252 	 * make a copy of the original message
16253 	 */
16254 	mp2ctl = copymsg(mpctl);
16255 
16256 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16257 	optp->level = EXPER_DVMRP;
16258 	optp->name = 0;
16259 	if (!ip_mroute_stats(mpctl->b_cont)) {
16260 		ip0dbg(("ip_mroute_stats: failed\n"));
16261 	}
16262 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16263 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
16264 	    (int)optp->level, (int)optp->name, (int)optp->len));
16265 	qreply(q, mpctl);
16266 	return (mp2ctl);
16267 }
16268 
16269 /* IPv4 address information */
16270 static mblk_t *
16271 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl)
16272 {
16273 	struct opthdr		*optp;
16274 	mblk_t			*mp2ctl;
16275 	mblk_t			*mp_tail = NULL;
16276 	ill_t			*ill;
16277 	ipif_t			*ipif;
16278 	uint_t			bitval;
16279 	mib2_ipAddrEntry_t	mae;
16280 	zoneid_t		zoneid;
16281 	ill_walk_context_t ctx;
16282 
16283 	/*
16284 	 * make a copy of the original message
16285 	 */
16286 	mp2ctl = copymsg(mpctl);
16287 
16288 	/* ipAddrEntryTable */
16289 
16290 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16291 	optp->level = MIB2_IP;
16292 	optp->name = MIB2_IP_ADDR;
16293 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16294 
16295 	rw_enter(&ill_g_lock, RW_READER);
16296 	ill = ILL_START_WALK_V4(&ctx);
16297 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16298 		for (ipif = ill->ill_ipif; ipif != NULL;
16299 		    ipif = ipif->ipif_next) {
16300 			if (ipif->ipif_zoneid != zoneid)
16301 				continue;
16302 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
16303 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
16304 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
16305 
16306 			(void) ipif_get_name(ipif,
16307 			    mae.ipAdEntIfIndex.o_bytes,
16308 			    OCTET_LENGTH);
16309 			mae.ipAdEntIfIndex.o_length =
16310 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
16311 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
16312 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
16313 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
16314 			mae.ipAdEntInfo.ae_subnet_len =
16315 			    ip_mask_to_plen(ipif->ipif_net_mask);
16316 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
16317 			for (bitval = 1;
16318 			    bitval &&
16319 			    !(bitval & ipif->ipif_brd_addr);
16320 			    bitval <<= 1)
16321 				noop;
16322 			mae.ipAdEntBcastAddr = bitval;
16323 			mae.ipAdEntReasmMaxSize = 65535;
16324 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
16325 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
16326 			mae.ipAdEntInfo.ae_broadcast_addr =
16327 			    ipif->ipif_brd_addr;
16328 			mae.ipAdEntInfo.ae_pp_dst_addr =
16329 			    ipif->ipif_pp_dst_addr;
16330 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
16331 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
16332 
16333 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16334 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
16335 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
16336 				    "allocate %u bytes\n",
16337 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
16338 			}
16339 		}
16340 	}
16341 	rw_exit(&ill_g_lock);
16342 
16343 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16344 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
16345 	    (int)optp->level, (int)optp->name, (int)optp->len));
16346 	qreply(q, mpctl);
16347 	return (mp2ctl);
16348 }
16349 
16350 /* IPv6 address information */
16351 static mblk_t *
16352 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl)
16353 {
16354 	struct opthdr		*optp;
16355 	mblk_t			*mp2ctl;
16356 	mblk_t			*mp_tail = NULL;
16357 	ill_t			*ill;
16358 	ipif_t			*ipif;
16359 	mib2_ipv6AddrEntry_t	mae6;
16360 	zoneid_t		zoneid;
16361 	ill_walk_context_t	ctx;
16362 
16363 	/*
16364 	 * make a copy of the original message
16365 	 */
16366 	mp2ctl = copymsg(mpctl);
16367 
16368 	/* ipv6AddrEntryTable */
16369 
16370 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16371 	optp->level = MIB2_IP6;
16372 	optp->name = MIB2_IP6_ADDR;
16373 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16374 
16375 	rw_enter(&ill_g_lock, RW_READER);
16376 	ill = ILL_START_WALK_V6(&ctx);
16377 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16378 		for (ipif = ill->ill_ipif; ipif; ipif = ipif->ipif_next) {
16379 			if (ipif->ipif_zoneid != zoneid)
16380 				continue;
16381 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
16382 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
16383 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
16384 
16385 			(void) ipif_get_name(ipif,
16386 			    mae6.ipv6AddrIfIndex.o_bytes,
16387 			    OCTET_LENGTH);
16388 			mae6.ipv6AddrIfIndex.o_length =
16389 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
16390 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
16391 			mae6.ipv6AddrPfxLength =
16392 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
16393 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
16394 			mae6.ipv6AddrInfo.ae_subnet_len =
16395 			    mae6.ipv6AddrPfxLength;
16396 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
16397 
16398 			/* Type: stateless(1), stateful(2), unknown(3) */
16399 			if (ipif->ipif_flags & IPIF_ADDRCONF)
16400 				mae6.ipv6AddrType = 1;
16401 			else
16402 				mae6.ipv6AddrType = 2;
16403 			/* Anycast: true(1), false(2) */
16404 			if (ipif->ipif_flags & IPIF_ANYCAST)
16405 				mae6.ipv6AddrAnycastFlag = 1;
16406 			else
16407 				mae6.ipv6AddrAnycastFlag = 2;
16408 
16409 			/*
16410 			 * Address status: preferred(1), deprecated(2),
16411 			 * invalid(3), inaccessible(4), unknown(5)
16412 			 */
16413 			if (ipif->ipif_flags & IPIF_NOLOCAL)
16414 				mae6.ipv6AddrStatus = 3;
16415 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
16416 				mae6.ipv6AddrStatus = 2;
16417 			else
16418 				mae6.ipv6AddrStatus = 1;
16419 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
16420 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
16421 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
16422 						ipif->ipif_v6pp_dst_addr;
16423 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
16424 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
16425 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16426 				(char *)&mae6,
16427 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
16428 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
16429 				    "allocate %u bytes\n",
16430 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
16431 			}
16432 		}
16433 	}
16434 	rw_exit(&ill_g_lock);
16435 
16436 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16437 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
16438 	    (int)optp->level, (int)optp->name, (int)optp->len));
16439 	qreply(q, mpctl);
16440 	return (mp2ctl);
16441 }
16442 
16443 /* IPv4 multicast group membership. */
16444 static mblk_t *
16445 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl)
16446 {
16447 	struct opthdr		*optp;
16448 	mblk_t			*mp2ctl;
16449 	ill_t			*ill;
16450 	ipif_t			*ipif;
16451 	ilm_t			*ilm;
16452 	ip_member_t		ipm;
16453 	mblk_t			*mp_tail = NULL;
16454 	ill_walk_context_t	ctx;
16455 	zoneid_t		zoneid;
16456 
16457 	/*
16458 	 * make a copy of the original message
16459 	 */
16460 	mp2ctl = copymsg(mpctl);
16461 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16462 
16463 	/* ipGroupMember table */
16464 	optp = (struct opthdr *)&mpctl->b_rptr[
16465 	    sizeof (struct T_optmgmt_ack)];
16466 	optp->level = MIB2_IP;
16467 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
16468 
16469 	rw_enter(&ill_g_lock, RW_READER);
16470 	ill = ILL_START_WALK_V4(&ctx);
16471 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16472 		ILM_WALKER_HOLD(ill);
16473 		for (ipif = ill->ill_ipif; ipif != NULL;
16474 		    ipif = ipif->ipif_next) {
16475 			if (ipif->ipif_zoneid != zoneid)
16476 				continue;	/* not this zone */
16477 			(void) ipif_get_name(ipif,
16478 			    ipm.ipGroupMemberIfIndex.o_bytes,
16479 			    OCTET_LENGTH);
16480 			ipm.ipGroupMemberIfIndex.o_length =
16481 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
16482 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16483 				ASSERT(ilm->ilm_ipif != NULL);
16484 				ASSERT(ilm->ilm_ill == NULL);
16485 				if (ilm->ilm_ipif != ipif)
16486 					continue;
16487 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
16488 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
16489 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
16490 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16491 				    (char *)&ipm, (int)sizeof (ipm))) {
16492 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
16493 					    "failed to allocate %u bytes\n",
16494 						(uint_t)sizeof (ipm)));
16495 				}
16496 			}
16497 		}
16498 		ILM_WALKER_RELE(ill);
16499 	}
16500 	rw_exit(&ill_g_lock);
16501 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16502 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16503 	    (int)optp->level, (int)optp->name, (int)optp->len));
16504 	qreply(q, mpctl);
16505 	return (mp2ctl);
16506 }
16507 
16508 /* IPv6 multicast group membership. */
16509 static mblk_t *
16510 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl)
16511 {
16512 	struct opthdr		*optp;
16513 	mblk_t			*mp2ctl;
16514 	ill_t			*ill;
16515 	ilm_t			*ilm;
16516 	ipv6_member_t		ipm6;
16517 	mblk_t			*mp_tail = NULL;
16518 	ill_walk_context_t	ctx;
16519 	zoneid_t		zoneid;
16520 
16521 	/*
16522 	 * make a copy of the original message
16523 	 */
16524 	mp2ctl = copymsg(mpctl);
16525 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16526 
16527 	/* ip6GroupMember table */
16528 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16529 	optp->level = MIB2_IP6;
16530 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
16531 
16532 	rw_enter(&ill_g_lock, RW_READER);
16533 	ill = ILL_START_WALK_V6(&ctx);
16534 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16535 		ILM_WALKER_HOLD(ill);
16536 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
16537 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16538 			ASSERT(ilm->ilm_ipif == NULL);
16539 			ASSERT(ilm->ilm_ill != NULL);
16540 			if (ilm->ilm_zoneid != zoneid)
16541 				continue;	/* not this zone */
16542 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
16543 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
16544 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
16545 			if (!snmp_append_data2(mpctl->b_cont,
16546 			    &mp_tail,
16547 			    (char *)&ipm6, (int)sizeof (ipm6))) {
16548 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
16549 				    "failed to allocate %u bytes\n",
16550 				    (uint_t)sizeof (ipm6)));
16551 			}
16552 		}
16553 		ILM_WALKER_RELE(ill);
16554 	}
16555 	rw_exit(&ill_g_lock);
16556 
16557 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16558 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16559 	    (int)optp->level, (int)optp->name, (int)optp->len));
16560 	qreply(q, mpctl);
16561 	return (mp2ctl);
16562 }
16563 
16564 /* IP multicast filtered sources */
16565 static mblk_t *
16566 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl)
16567 {
16568 	struct opthdr		*optp;
16569 	mblk_t			*mp2ctl;
16570 	ill_t			*ill;
16571 	ipif_t			*ipif;
16572 	ilm_t			*ilm;
16573 	ip_grpsrc_t		ips;
16574 	mblk_t			*mp_tail = NULL;
16575 	ill_walk_context_t	ctx;
16576 	zoneid_t		zoneid;
16577 	int			i;
16578 	slist_t			*sl;
16579 
16580 	/*
16581 	 * make a copy of the original message
16582 	 */
16583 	mp2ctl = copymsg(mpctl);
16584 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16585 
16586 	/* ipGroupSource table */
16587 	optp = (struct opthdr *)&mpctl->b_rptr[
16588 	    sizeof (struct T_optmgmt_ack)];
16589 	optp->level = MIB2_IP;
16590 	optp->name = EXPER_IP_GROUP_SOURCES;
16591 
16592 	rw_enter(&ill_g_lock, RW_READER);
16593 	ill = ILL_START_WALK_V4(&ctx);
16594 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16595 		ILM_WALKER_HOLD(ill);
16596 		for (ipif = ill->ill_ipif; ipif != NULL;
16597 		    ipif = ipif->ipif_next) {
16598 			if (ipif->ipif_zoneid != zoneid)
16599 				continue;	/* not this zone */
16600 			(void) ipif_get_name(ipif,
16601 			    ips.ipGroupSourceIfIndex.o_bytes,
16602 			    OCTET_LENGTH);
16603 			ips.ipGroupSourceIfIndex.o_length =
16604 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
16605 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16606 				ASSERT(ilm->ilm_ipif != NULL);
16607 				ASSERT(ilm->ilm_ill == NULL);
16608 				sl = ilm->ilm_filter;
16609 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
16610 					continue;
16611 				ips.ipGroupSourceGroup = ilm->ilm_addr;
16612 				for (i = 0; i < sl->sl_numsrc; i++) {
16613 					if (!IN6_IS_ADDR_V4MAPPED(
16614 					    &sl->sl_addr[i]))
16615 						continue;
16616 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
16617 					    ips.ipGroupSourceAddress);
16618 					if (snmp_append_data2(mpctl->b_cont,
16619 					    &mp_tail, (char *)&ips,
16620 					    (int)sizeof (ips)) == 0) {
16621 						ip1dbg(("ip_snmp_get_mib2_"
16622 						    "ip_group_src: failed to "
16623 						    "allocate %u bytes\n",
16624 						    (uint_t)sizeof (ips)));
16625 					}
16626 				}
16627 			}
16628 		}
16629 		ILM_WALKER_RELE(ill);
16630 	}
16631 	rw_exit(&ill_g_lock);
16632 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16633 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16634 	    (int)optp->level, (int)optp->name, (int)optp->len));
16635 	qreply(q, mpctl);
16636 	return (mp2ctl);
16637 }
16638 
16639 /* IPv6 multicast filtered sources. */
16640 static mblk_t *
16641 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl)
16642 {
16643 	struct opthdr		*optp;
16644 	mblk_t			*mp2ctl;
16645 	ill_t			*ill;
16646 	ilm_t			*ilm;
16647 	ipv6_grpsrc_t		ips6;
16648 	mblk_t			*mp_tail = NULL;
16649 	ill_walk_context_t	ctx;
16650 	zoneid_t		zoneid;
16651 	int			i;
16652 	slist_t			*sl;
16653 
16654 	/*
16655 	 * make a copy of the original message
16656 	 */
16657 	mp2ctl = copymsg(mpctl);
16658 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16659 
16660 	/* ip6GroupMember table */
16661 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16662 	optp->level = MIB2_IP6;
16663 	optp->name = EXPER_IP6_GROUP_SOURCES;
16664 
16665 	rw_enter(&ill_g_lock, RW_READER);
16666 	ill = ILL_START_WALK_V6(&ctx);
16667 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16668 		ILM_WALKER_HOLD(ill);
16669 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
16670 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
16671 			ASSERT(ilm->ilm_ipif == NULL);
16672 			ASSERT(ilm->ilm_ill != NULL);
16673 			sl = ilm->ilm_filter;
16674 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
16675 				continue;
16676 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
16677 			for (i = 0; i < sl->sl_numsrc; i++) {
16678 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
16679 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16680 				    (char *)&ips6, (int)sizeof (ips6))) {
16681 					ip1dbg(("ip_snmp_get_mib2_ip6_"
16682 					    "group_src: failed to allocate "
16683 					    "%u bytes\n",
16684 					    (uint_t)sizeof (ips6)));
16685 				}
16686 			}
16687 		}
16688 		ILM_WALKER_RELE(ill);
16689 	}
16690 	rw_exit(&ill_g_lock);
16691 
16692 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16693 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
16694 	    (int)optp->level, (int)optp->name, (int)optp->len));
16695 	qreply(q, mpctl);
16696 	return (mp2ctl);
16697 }
16698 
16699 /* Multicast routing virtual interface table. */
16700 static mblk_t *
16701 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl)
16702 {
16703 	struct opthdr		*optp;
16704 	mblk_t			*mp2ctl;
16705 
16706 	/*
16707 	 * make a copy of the original message
16708 	 */
16709 	mp2ctl = copymsg(mpctl);
16710 
16711 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16712 	optp->level = EXPER_DVMRP;
16713 	optp->name = EXPER_DVMRP_VIF;
16714 	if (!ip_mroute_vif(mpctl->b_cont)) {
16715 		ip0dbg(("ip_mroute_vif: failed\n"));
16716 	}
16717 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16718 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
16719 	    (int)optp->level, (int)optp->name, (int)optp->len));
16720 	qreply(q, mpctl);
16721 	return (mp2ctl);
16722 }
16723 
16724 /* Multicast routing table. */
16725 static mblk_t *
16726 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl)
16727 {
16728 	struct opthdr		*optp;
16729 	mblk_t			*mp2ctl;
16730 
16731 	/*
16732 	 * make a copy of the original message
16733 	 */
16734 	mp2ctl = copymsg(mpctl);
16735 
16736 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16737 	optp->level = EXPER_DVMRP;
16738 	optp->name = EXPER_DVMRP_MRT;
16739 	if (!ip_mroute_mrt(mpctl->b_cont)) {
16740 		ip0dbg(("ip_mroute_mrt: failed\n"));
16741 	}
16742 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16743 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
16744 	    (int)optp->level, (int)optp->name, (int)optp->len));
16745 	qreply(q, mpctl);
16746 	return (mp2ctl);
16747 }
16748 
16749 /*
16750  * Return both ipRouteEntryTable, and ipNetToMediaEntryTable
16751  * in one IRE walk.
16752  */
16753 static mblk_t *
16754 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl)
16755 {
16756 	struct opthdr		*optp;
16757 	mblk_t			*mp2ctl;	/* Returned */
16758 	mblk_t			*mp3ctl;	/* nettomedia */
16759 	/*
16760 	 * We need two listptrs, for ipRouteEntryTable and
16761 	 * ipNetToMediaEntryTable to pass to ip_snmp_get2_v4()
16762 	 */
16763 	listptr_t		re_ntme_v4[2];
16764 	zoneid_t		zoneid;
16765 
16766 	/*
16767 	 * make a copy of the original message
16768 	 */
16769 	mp2ctl = copymsg(mpctl);
16770 	mp3ctl = copymsg(mpctl);
16771 	if (mp3ctl == NULL) {
16772 		freemsg(mp2ctl);
16773 		freemsg(mpctl);
16774 		return (NULL);
16775 	}
16776 
16777 	re_ntme_v4[0].lp_head = mpctl->b_cont;	/* ipRouteEntryTable */
16778 	re_ntme_v4[1].lp_head = mp3ctl->b_cont;	/* ipNetToMediaEntryTable */
16779 	/*
16780 	 * We assign NULL to tail ptrs as snmp_append_data2() will assign
16781 	 * proper values when called.
16782 	 */
16783 	re_ntme_v4[0].lp_tail = NULL;
16784 	re_ntme_v4[1].lp_tail = NULL;
16785 
16786 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16787 	ire_walk_v4(ip_snmp_get2_v4, (char *)re_ntme_v4, zoneid);
16788 	if (zoneid == GLOBAL_ZONEID) {
16789 		/*
16790 		 * Those IREs are used by Mobile-IP; since mipagent(1M) requires
16791 		 * the sys_net_config privilege, it can only run in the global
16792 		 * zone, so we don't display these IREs in the other zones.
16793 		 */
16794 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, (char *)re_ntme_v4);
16795 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, (char *)re_ntme_v4,
16796 		    NULL);
16797 	}
16798 
16799 	/* ipRouteEntryTable in mpctl */
16800 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16801 	optp->level = MIB2_IP;
16802 	optp->name = MIB2_IP_ROUTE;
16803 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v4[0].lp_head);
16804 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
16805 	    (int)optp->level, (int)optp->name, (int)optp->len));
16806 	qreply(q, mpctl);
16807 
16808 	/* ipNetToMediaEntryTable in mp3ctl */
16809 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16810 	optp->level = MIB2_IP;
16811 	optp->name = MIB2_IP_MEDIA;
16812 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v4[1].lp_head);
16813 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
16814 	    (int)optp->level, (int)optp->name, (int)optp->len));
16815 	qreply(q, mp3ctl);
16816 	return (mp2ctl);
16817 }
16818 
16819 /*
16820  * Return both ipv6RouteEntryTable, and ipv6NetToMediaEntryTable
16821  * in one IRE walk.
16822  */
16823 static mblk_t *
16824 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl)
16825 {
16826 	struct opthdr		*optp;
16827 	mblk_t			*mp2ctl;	/* Returned */
16828 	mblk_t			*mp3ctl;	/* nettomedia */
16829 	listptr_t		re_ntme_v6;
16830 	zoneid_t		zoneid;
16831 
16832 	/*
16833 	 * make a copy of the original message
16834 	 */
16835 	mp2ctl = copymsg(mpctl);
16836 	mp3ctl = copymsg(mpctl);
16837 	if (mp3ctl == NULL) {
16838 		freemsg(mp2ctl);
16839 		freemsg(mpctl);
16840 		return (NULL);
16841 	}
16842 
16843 	/*
16844 	 * We assign NULL to tail ptrs as snmp_append_data2() will assign
16845 	 * proper values when called.  ipv6RouteEntryTable in is placed
16846 	 * in mpctl.
16847 	 */
16848 	re_ntme_v6.lp_head = mpctl->b_cont;	/* ip6RouteEntryTable */
16849 	re_ntme_v6.lp_tail = NULL;
16850 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16851 	ire_walk_v6(ip_snmp_get2_v6_route, (char *)&re_ntme_v6, zoneid);
16852 
16853 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16854 	optp->level = MIB2_IP6;
16855 	optp->name = MIB2_IP6_ROUTE;
16856 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v6.lp_head);
16857 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
16858 	    (int)optp->level, (int)optp->name, (int)optp->len));
16859 	qreply(q, mpctl);
16860 
16861 	/* ipv6NetToMediaEntryTable in mp3ctl */
16862 	re_ntme_v6.lp_head = mp3ctl->b_cont;	/* ip6NetToMediaEntryTable */
16863 	re_ntme_v6.lp_tail = NULL;
16864 	ndp_walk(NULL, ip_snmp_get2_v6_media, (uchar_t *)&re_ntme_v6);
16865 
16866 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16867 	optp->level = MIB2_IP6;
16868 	optp->name = MIB2_IP6_MEDIA;
16869 	optp->len = (t_uscalar_t)msgdsize(re_ntme_v6.lp_head);
16870 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
16871 	    (int)optp->level, (int)optp->name, (int)optp->len));
16872 	qreply(q, mp3ctl);
16873 	return (mp2ctl);
16874 }
16875 
16876 /*
16877  * ICMPv6 mib: One per ill
16878  */
16879 static mblk_t *
16880 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl)
16881 {
16882 	struct opthdr		*optp;
16883 	mblk_t			*mp2ctl;
16884 	ill_t			*ill;
16885 	ill_walk_context_t	ctx;
16886 	mblk_t			*mp_tail = NULL;
16887 
16888 	/*
16889 	 * Make a copy of the original message
16890 	 */
16891 	mp2ctl = copymsg(mpctl);
16892 
16893 	/* fixed length IPv6 structure ... */
16894 
16895 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16896 	optp->level = MIB2_IP6;
16897 	optp->name = 0;
16898 	/* Include "unknown interface" ip6_mib */
16899 	ip6_mib.ipv6IfIndex = 0;	/* Flag to netstat */
16900 	SET_MIB(ip6_mib.ipv6Forwarding, ipv6_forward ? 1 : 2);
16901 	SET_MIB(ip6_mib.ipv6DefaultHopLimit, ipv6_def_hops);
16902 	SET_MIB(ip6_mib.ipv6IfStatsEntrySize,
16903 	    sizeof (mib2_ipv6IfStatsEntry_t));
16904 	SET_MIB(ip6_mib.ipv6AddrEntrySize, sizeof (mib2_ipv6AddrEntry_t));
16905 	SET_MIB(ip6_mib.ipv6RouteEntrySize, sizeof (mib2_ipv6RouteEntry_t));
16906 	SET_MIB(ip6_mib.ipv6NetToMediaEntrySize,
16907 	    sizeof (mib2_ipv6NetToMediaEntry_t));
16908 	SET_MIB(ip6_mib.ipv6MemberEntrySize, sizeof (ipv6_member_t));
16909 	SET_MIB(ip6_mib.ipv6GroupSourceEntrySize, sizeof (ipv6_grpsrc_t));
16910 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip6_mib,
16911 	    (int)sizeof (ip6_mib))) {
16912 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
16913 		    (uint_t)sizeof (ip6_mib)));
16914 	}
16915 
16916 	rw_enter(&ill_g_lock, RW_READER);
16917 	ill = ILL_START_WALK_V6(&ctx);
16918 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16919 		ill->ill_ip6_mib->ipv6IfIndex =
16920 		    ill->ill_phyint->phyint_ifindex;
16921 		SET_MIB(ill->ill_ip6_mib->ipv6Forwarding,
16922 		    ipv6_forward ? 1 : 2);
16923 		SET_MIB(ill->ill_ip6_mib->ipv6DefaultHopLimit,
16924 		    ill->ill_max_hops);
16925 		SET_MIB(ill->ill_ip6_mib->ipv6IfStatsEntrySize,
16926 		    sizeof (mib2_ipv6IfStatsEntry_t));
16927 		SET_MIB(ill->ill_ip6_mib->ipv6AddrEntrySize,
16928 		    sizeof (mib2_ipv6AddrEntry_t));
16929 		SET_MIB(ill->ill_ip6_mib->ipv6RouteEntrySize,
16930 		    sizeof (mib2_ipv6RouteEntry_t));
16931 		SET_MIB(ill->ill_ip6_mib->ipv6NetToMediaEntrySize,
16932 		    sizeof (mib2_ipv6NetToMediaEntry_t));
16933 		SET_MIB(ill->ill_ip6_mib->ipv6MemberEntrySize,
16934 		    sizeof (ipv6_member_t));
16935 
16936 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16937 		    (char *)ill->ill_ip6_mib,
16938 		    (int)sizeof (*ill->ill_ip6_mib))) {
16939 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
16940 				"%u bytes\n",
16941 				(uint_t)sizeof (*ill->ill_ip6_mib)));
16942 		}
16943 	}
16944 	rw_exit(&ill_g_lock);
16945 
16946 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16947 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
16948 	    (int)optp->level, (int)optp->name, (int)optp->len));
16949 	qreply(q, mpctl);
16950 	return (mp2ctl);
16951 }
16952 
16953 /*
16954  * ICMPv6 mib: One per ill
16955  */
16956 static mblk_t *
16957 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl)
16958 {
16959 	struct opthdr		*optp;
16960 	mblk_t			*mp2ctl;
16961 	ill_t			*ill;
16962 	ill_walk_context_t	ctx;
16963 	mblk_t			*mp_tail = NULL;
16964 	/*
16965 	 * Make a copy of the original message
16966 	 */
16967 	mp2ctl = copymsg(mpctl);
16968 
16969 	/* fixed length ICMPv6 structure ... */
16970 
16971 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16972 	optp->level = MIB2_ICMP6;
16973 	optp->name = 0;
16974 	/* Include "unknown interface" icmp6_mib */
16975 	icmp6_mib.ipv6IfIcmpIfIndex = 0;	/* Flag to netstat */
16976 	icmp6_mib.ipv6IfIcmpEntrySize = sizeof (mib2_ipv6IfIcmpEntry_t);
16977 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&icmp6_mib,
16978 	    (int)sizeof (icmp6_mib))) {
16979 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
16980 		    (uint_t)sizeof (icmp6_mib)));
16981 	}
16982 
16983 	rw_enter(&ill_g_lock, RW_READER);
16984 	ill = ILL_START_WALK_V6(&ctx);
16985 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
16986 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
16987 		    ill->ill_phyint->phyint_ifindex;
16988 		ill->ill_icmp6_mib->ipv6IfIcmpEntrySize =
16989 		    sizeof (mib2_ipv6IfIcmpEntry_t);
16990 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
16991 		    (char *)ill->ill_icmp6_mib,
16992 		    (int)sizeof (*ill->ill_icmp6_mib))) {
16993 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
16994 			    "%u bytes\n",
16995 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
16996 		}
16997 	}
16998 	rw_exit(&ill_g_lock);
16999 
17000 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17001 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
17002 	    (int)optp->level, (int)optp->name, (int)optp->len));
17003 	qreply(q, mpctl);
17004 	return (mp2ctl);
17005 }
17006 
17007 /*
17008  * ire_walk routine to create both ipRouteEntryTable and
17009  * ipNetToMediaEntryTable in one IRE walk
17010  */
17011 static void
17012 ip_snmp_get2_v4(ire_t *ire, listptr_t re_ntme[])
17013 {
17014 	ill_t				*ill;
17015 	ipif_t				*ipif;
17016 	mblk_t				*llmp;
17017 	dl_unitdata_req_t		*dlup;
17018 	mib2_ipRouteEntry_t		re;
17019 	mib2_ipNetToMediaEntry_t	ntme;
17020 	ipaddr_t			gw_addr;
17021 
17022 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17023 
17024 	/*
17025 	 * Return all IRE types for route table... let caller pick and choose
17026 	 */
17027 	re.ipRouteDest = ire->ire_addr;
17028 	ipif = ire->ire_ipif;
17029 	re.ipRouteIfIndex.o_length = 0;
17030 	if (ire->ire_type == IRE_CACHE) {
17031 		ill = (ill_t *)ire->ire_stq->q_ptr;
17032 		re.ipRouteIfIndex.o_length =
17033 		    ill->ill_name_length == 0 ? 0 :
17034 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17035 		bcopy(ill->ill_name, re.ipRouteIfIndex.o_bytes,
17036 		    re.ipRouteIfIndex.o_length);
17037 	} else if (ipif != NULL) {
17038 		(void) ipif_get_name(ipif, re.ipRouteIfIndex.o_bytes,
17039 		    OCTET_LENGTH);
17040 		re.ipRouteIfIndex.o_length =
17041 		    mi_strlen(re.ipRouteIfIndex.o_bytes);
17042 	}
17043 	re.ipRouteMetric1 = -1;
17044 	re.ipRouteMetric2 = -1;
17045 	re.ipRouteMetric3 = -1;
17046 	re.ipRouteMetric4 = -1;
17047 
17048 	gw_addr = ire->ire_gateway_addr;
17049 
17050 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
17051 		re.ipRouteNextHop = ire->ire_src_addr;
17052 	else
17053 		re.ipRouteNextHop = gw_addr;
17054 	/* indirect(4), direct(3), or invalid(2) */
17055 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
17056 		re.ipRouteType = 2;
17057 	else
17058 		re.ipRouteType = (gw_addr != 0) ? 4 : 3;
17059 	re.ipRouteProto = -1;
17060 	re.ipRouteAge = gethrestime_sec() - ire->ire_create_time;
17061 	re.ipRouteMask = ire->ire_mask;
17062 	re.ipRouteMetric5 = -1;
17063 	re.ipRouteInfo.re_max_frag  = ire->ire_max_frag;
17064 	re.ipRouteInfo.re_frag_flag = ire->ire_frag_flag;
17065 	re.ipRouteInfo.re_rtt	    = ire->ire_uinfo.iulp_rtt;
17066 	llmp = ire->ire_dlureq_mp;
17067 	re.ipRouteInfo.re_ref	    = ire->ire_refcnt;
17068 	re.ipRouteInfo.re_src_addr  = ire->ire_src_addr;
17069 	re.ipRouteInfo.re_ire_type  = ire->ire_type;
17070 	re.ipRouteInfo.re_obpkt	    = ire->ire_ob_pkt_count;
17071 	re.ipRouteInfo.re_ibpkt	    = ire->ire_ib_pkt_count;
17072 	re.ipRouteInfo.re_flags	    = ire->ire_flags;
17073 	re.ipRouteInfo.re_in_ill.o_length = 0;
17074 	if (ire->ire_in_ill != NULL) {
17075 		re.ipRouteInfo.re_in_ill.o_length =
17076 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
17077 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
17078 		bcopy(ire->ire_in_ill->ill_name,
17079 		    re.ipRouteInfo.re_in_ill.o_bytes,
17080 		    re.ipRouteInfo.re_in_ill.o_length);
17081 	}
17082 	re.ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
17083 	if (!snmp_append_data2(re_ntme[0].lp_head, &(re_ntme[0].lp_tail),
17084 	    (char *)&re, (int)sizeof (re))) {
17085 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
17086 		    (uint_t)sizeof (re)));
17087 	}
17088 
17089 	if (ire->ire_type != IRE_CACHE || gw_addr != 0)
17090 		return;
17091 	/*
17092 	 * only IRE_CACHE entries that are for a directly connected subnet
17093 	 * get appended to net -> phys addr table
17094 	 * (others in arp)
17095 	 */
17096 	ntme.ipNetToMediaIfIndex.o_length = 0;
17097 	ill = ire_to_ill(ire);
17098 	ASSERT(ill != NULL);
17099 	ntme.ipNetToMediaIfIndex.o_length =
17100 	    ill->ill_name_length == 0 ? 0 :
17101 	    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17102 	bcopy(ill->ill_name, ntme.ipNetToMediaIfIndex.o_bytes,
17103 		    ntme.ipNetToMediaIfIndex.o_length);
17104 
17105 	ntme.ipNetToMediaPhysAddress.o_length = 0;
17106 	if (llmp) {
17107 		uchar_t *addr;
17108 
17109 		dlup = (dl_unitdata_req_t *)llmp->b_rptr;
17110 		/* Remove sap from  address */
17111 		if (ill->ill_sap_length < 0)
17112 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset;
17113 		else
17114 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset +
17115 			    ill->ill_sap_length;
17116 
17117 		ntme.ipNetToMediaPhysAddress.o_length =
17118 		    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
17119 		bcopy(addr, ntme.ipNetToMediaPhysAddress.o_bytes,
17120 		    ntme.ipNetToMediaPhysAddress.o_length);
17121 	}
17122 	ntme.ipNetToMediaNetAddress = ire->ire_addr;
17123 	/* assume dynamic (may be changed in arp) */
17124 	ntme.ipNetToMediaType = 3;
17125 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (uint32_t);
17126 	bcopy(&ire->ire_mask, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
17127 	    ntme.ipNetToMediaInfo.ntm_mask.o_length);
17128 	ntme.ipNetToMediaInfo.ntm_flags = ACE_F_RESOLVED;
17129 	if (!snmp_append_data2(re_ntme[1].lp_head, &(re_ntme[1].lp_tail),
17130 	    (char *)&ntme, (int)sizeof (ntme))) {
17131 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
17132 		    (uint_t)sizeof (ntme)));
17133 	}
17134 }
17135 
17136 /*
17137  * ire_walk routine to create ipv6RouteEntryTable.
17138  */
17139 static void
17140 ip_snmp_get2_v6_route(ire_t *ire, listptr_t *re_ntme)
17141 {
17142 	ill_t				*ill;
17143 	ipif_t				*ipif;
17144 	mib2_ipv6RouteEntry_t		re;
17145 	in6_addr_t			gw_addr_v6;
17146 
17147 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
17148 
17149 	/*
17150 	 * Return all IRE types for route table... let caller pick and choose
17151 	 */
17152 	re.ipv6RouteDest = ire->ire_addr_v6;
17153 	re.ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
17154 	re.ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
17155 	re.ipv6RouteIfIndex.o_length = 0;
17156 	ipif = ire->ire_ipif;
17157 	if (ire->ire_type == IRE_CACHE) {
17158 		ill = (ill_t *)ire->ire_stq->q_ptr;
17159 		re.ipv6RouteIfIndex.o_length =
17160 		    ill->ill_name_length == 0 ? 0 :
17161 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17162 		bcopy(ill->ill_name, re.ipv6RouteIfIndex.o_bytes,
17163 		    re.ipv6RouteIfIndex.o_length);
17164 	} else if (ipif != NULL) {
17165 		(void) ipif_get_name(ipif, re.ipv6RouteIfIndex.o_bytes,
17166 		    OCTET_LENGTH);
17167 		re.ipv6RouteIfIndex.o_length =
17168 		    mi_strlen(re.ipv6RouteIfIndex.o_bytes);
17169 	}
17170 
17171 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
17172 
17173 	mutex_enter(&ire->ire_lock);
17174 	gw_addr_v6 = ire->ire_gateway_addr_v6;
17175 	mutex_exit(&ire->ire_lock);
17176 
17177 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
17178 		re.ipv6RouteNextHop = ire->ire_src_addr_v6;
17179 	else
17180 		re.ipv6RouteNextHop = gw_addr_v6;
17181 
17182 	/* remote(4), local(3), or discard(2) */
17183 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
17184 		re.ipv6RouteType = 2;
17185 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
17186 		re.ipv6RouteType = 3;
17187 	else
17188 		re.ipv6RouteType = 4;
17189 
17190 	re.ipv6RouteProtocol		= -1;
17191 	re.ipv6RoutePolicy		= 0;
17192 	re.ipv6RouteAge		= gethrestime_sec() - ire->ire_create_time;
17193 	re.ipv6RouteNextHopRDI		= 0;
17194 	re.ipv6RouteWeight		= 0;
17195 	re.ipv6RouteMetric		= 0;
17196 	re.ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
17197 	re.ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
17198 	re.ipv6RouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
17199 	re.ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
17200 	re.ipv6RouteInfo.re_ire_type	= ire->ire_type;
17201 	re.ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
17202 	re.ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
17203 	re.ipv6RouteInfo.re_ref		= ire->ire_refcnt;
17204 	re.ipv6RouteInfo.re_flags	= ire->ire_flags;
17205 
17206 	if (!snmp_append_data2(re_ntme->lp_head, &(re_ntme->lp_tail),
17207 	    (char *)&re, (int)sizeof (re))) {
17208 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
17209 		    (uint_t)sizeof (re)));
17210 	}
17211 }
17212 
17213 /*
17214  * ndp_walk routine to create ipv6NetToMediaEntryTable
17215  */
17216 static int
17217 ip_snmp_get2_v6_media(nce_t *nce, listptr_t *re_ntme)
17218 {
17219 	ill_t				*ill;
17220 	mib2_ipv6NetToMediaEntry_t	ntme;
17221 	dl_unitdata_req_t		*dl;
17222 
17223 	ill = nce->nce_ill;
17224 	ASSERT(ill->ill_isv6);
17225 
17226 	/*
17227 	 * Neighbor cache entry attached to IRE with on-link
17228 	 * destination.
17229 	 */
17230 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
17231 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
17232 	if ((ill->ill_flags & ILLF_XRESOLV) &&
17233 	    (nce->nce_res_mp != NULL)) {
17234 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
17235 		ntme.ipv6NetToMediaPhysAddress.o_length =
17236 		    dl->dl_dest_addr_length;
17237 	} else {
17238 		ntme.ipv6NetToMediaPhysAddress.o_length =
17239 		    ill->ill_phys_addr_length;
17240 	}
17241 	if (nce->nce_res_mp != NULL) {
17242 		bcopy((char *)nce->nce_res_mp->b_rptr +
17243 		    NCE_LL_ADDR_OFFSET(ill),
17244 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
17245 		    ntme.ipv6NetToMediaPhysAddress.o_length);
17246 	} else {
17247 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
17248 		    ill->ill_phys_addr_length);
17249 	}
17250 	/*
17251 	 * Note: Returns ND_* states. Should be:
17252 	 * reachable(1), stale(2), delay(3), probe(4),
17253 	 * invalid(5), unknown(6)
17254 	 */
17255 	ntme.ipv6NetToMediaState = nce->nce_state;
17256 	ntme.ipv6NetToMediaLastUpdated = 0;
17257 
17258 	/* other(1), dynamic(2), static(3), local(4) */
17259 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
17260 		ntme.ipv6NetToMediaType = 4;
17261 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
17262 		ntme.ipv6NetToMediaType = 1;
17263 	} else {
17264 		ntme.ipv6NetToMediaType = 2;
17265 	}
17266 
17267 	if (!snmp_append_data2(re_ntme->lp_head,
17268 	    &(re_ntme->lp_tail), (char *)&ntme, (int)sizeof (ntme))) {
17269 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
17270 		    (uint_t)sizeof (ntme)));
17271 	}
17272 	return (0);
17273 }
17274 
17275 /*
17276  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
17277  */
17278 /* ARGSUSED */
17279 int
17280 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
17281 {
17282 	switch (level) {
17283 	case MIB2_IP:
17284 	case MIB2_ICMP:
17285 		switch (name) {
17286 		default:
17287 			break;
17288 		}
17289 		return (1);
17290 	default:
17291 		return (1);
17292 	}
17293 }
17294 
17295 /*
17296  * Called before the options are updated to check if this packet will
17297  * be source routed from here.
17298  * This routine assumes that the options are well formed i.e. that they
17299  * have already been checked.
17300  */
17301 static boolean_t
17302 ip_source_routed(ipha_t *ipha)
17303 {
17304 	ipoptp_t	opts;
17305 	uchar_t		*opt;
17306 	uint8_t		optval;
17307 	uint8_t		optlen;
17308 	ipaddr_t	dst;
17309 	ire_t		*ire;
17310 
17311 	if (IS_SIMPLE_IPH(ipha)) {
17312 		ip2dbg(("not source routed\n"));
17313 		return (B_FALSE);
17314 	}
17315 	dst = ipha->ipha_dst;
17316 	for (optval = ipoptp_first(&opts, ipha);
17317 	    optval != IPOPT_EOL;
17318 	    optval = ipoptp_next(&opts)) {
17319 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17320 		opt = opts.ipoptp_cur;
17321 		optlen = opts.ipoptp_len;
17322 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
17323 		    optval, optlen));
17324 		switch (optval) {
17325 			uint32_t off;
17326 		case IPOPT_SSRR:
17327 		case IPOPT_LSRR:
17328 			/*
17329 			 * If dst is one of our addresses and there are some
17330 			 * entries left in the source route return (true).
17331 			 */
17332 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17333 			    ALL_ZONES, MATCH_IRE_TYPE);
17334 			if (ire == NULL) {
17335 				ip2dbg(("ip_source_routed: not next"
17336 				    " source route 0x%x\n",
17337 				    ntohl(dst)));
17338 				return (B_FALSE);
17339 			}
17340 			ire_refrele(ire);
17341 			off = opt[IPOPT_OFFSET];
17342 			off--;
17343 			if (optlen < IP_ADDR_LEN ||
17344 			    off > optlen - IP_ADDR_LEN) {
17345 				/* End of source route */
17346 				ip1dbg(("ip_source_routed: end of SR\n"));
17347 				return (B_FALSE);
17348 			}
17349 			return (B_TRUE);
17350 		}
17351 	}
17352 	ip2dbg(("not source routed\n"));
17353 	return (B_FALSE);
17354 }
17355 
17356 /*
17357  * Check if the packet contains any source route.
17358  */
17359 static boolean_t
17360 ip_source_route_included(ipha_t *ipha)
17361 {
17362 	ipoptp_t	opts;
17363 	uint8_t		optval;
17364 
17365 	if (IS_SIMPLE_IPH(ipha))
17366 		return (B_FALSE);
17367 	for (optval = ipoptp_first(&opts, ipha);
17368 	    optval != IPOPT_EOL;
17369 	    optval = ipoptp_next(&opts)) {
17370 		switch (optval) {
17371 		case IPOPT_SSRR:
17372 		case IPOPT_LSRR:
17373 			return (B_TRUE);
17374 		}
17375 	}
17376 	return (B_FALSE);
17377 }
17378 
17379 /*
17380  * Called when the IRE expiration timer fires.
17381  */
17382 /* ARGSUSED */
17383 void
17384 ip_trash_timer_expire(void *args)
17385 {
17386 	int	flush_flag = 0;
17387 
17388 	/*
17389 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
17390 	 * This lock makes sure that a new invocation of this function
17391 	 * that occurs due to an almost immediate timer firing will not
17392 	 * progress beyond this point until the current invocation is done
17393 	 */
17394 	mutex_enter(&ip_trash_timer_lock);
17395 	ip_ire_expire_id = 0;
17396 	mutex_exit(&ip_trash_timer_lock);
17397 
17398 	/* Periodic timer */
17399 	if (ip_ire_arp_time_elapsed >= ip_ire_arp_interval) {
17400 		/*
17401 		 * Remove all IRE_CACHE entries since they might
17402 		 * contain arp information.
17403 		 */
17404 		flush_flag |= FLUSH_ARP_TIME;
17405 		ip_ire_arp_time_elapsed = 0;
17406 		IP_STAT(ip_ire_arp_timer_expired);
17407 	}
17408 	if (ip_ire_rd_time_elapsed >= ip_ire_redir_interval) {
17409 		/* Remove all redirects */
17410 		flush_flag |= FLUSH_REDIRECT_TIME;
17411 		ip_ire_rd_time_elapsed = 0;
17412 		IP_STAT(ip_ire_redirect_timer_expired);
17413 	}
17414 	if (ip_ire_pmtu_time_elapsed >= ip_ire_pathmtu_interval) {
17415 		/* Increase path mtu */
17416 		flush_flag |= FLUSH_MTU_TIME;
17417 		ip_ire_pmtu_time_elapsed = 0;
17418 		IP_STAT(ip_ire_pmtu_timer_expired);
17419 	}
17420 	if (flush_flag != 0) {
17421 		/* Walk all IPv4 IRE's and update them */
17422 		ire_walk_v4(ire_expire, (char *)(uintptr_t)flush_flag,
17423 		    ALL_ZONES);
17424 	}
17425 	if (flush_flag & FLUSH_MTU_TIME) {
17426 		/*
17427 		 * Walk all IPv6 IRE's and update them
17428 		 * Note that ARP and redirect timers are not
17429 		 * needed since NUD handles stale entries.
17430 		 */
17431 		flush_flag = FLUSH_MTU_TIME;
17432 		ire_walk_v6(ire_expire, (char *)(uintptr_t)flush_flag,
17433 		    ALL_ZONES);
17434 	}
17435 
17436 	ip_ire_arp_time_elapsed += ip_timer_interval;
17437 	ip_ire_rd_time_elapsed += ip_timer_interval;
17438 	ip_ire_pmtu_time_elapsed += ip_timer_interval;
17439 
17440 	/*
17441 	 * Hold the lock to serialize timeout calls and prevent
17442 	 * stale values in ip_ire_expire_id. Otherwise it is possible
17443 	 * for the timer to fire and a new invocation of this function
17444 	 * to start before the return value of timeout has been stored
17445 	 * in ip_ire_expire_id by the current invocation.
17446 	 */
17447 	mutex_enter(&ip_trash_timer_lock);
17448 	ip_ire_expire_id = timeout(ip_trash_timer_expire, NULL,
17449 	    MSEC_TO_TICK(ip_timer_interval));
17450 	mutex_exit(&ip_trash_timer_lock);
17451 }
17452 
17453 /*
17454  * Called by the memory allocator subsystem directly, when the system
17455  * is running low on memory.
17456  */
17457 /* ARGSUSED */
17458 void
17459 ip_trash_ire_reclaim(void *args)
17460 {
17461 	ire_cache_count_t icc;
17462 	ire_cache_reclaim_t icr;
17463 	ncc_cache_count_t ncc;
17464 	nce_cache_reclaim_t ncr;
17465 	uint_t delete_cnt;
17466 	/*
17467 	 * Memory reclaim call back.
17468 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
17469 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
17470 	 * entries, determine what fraction to free for
17471 	 * each category of IRE_CACHE entries giving absolute priority
17472 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
17473 	 * entry will be freed unless all offlink entries are freed).
17474 	 */
17475 	icc.icc_total = 0;
17476 	icc.icc_unused = 0;
17477 	icc.icc_offlink = 0;
17478 	icc.icc_pmtu = 0;
17479 	icc.icc_onlink = 0;
17480 	ire_walk(ire_cache_count, (char *)&icc);
17481 
17482 	/*
17483 	 * Free NCEs for IPv6 like the onlink ires.
17484 	 */
17485 	ncc.ncc_total = 0;
17486 	ncc.ncc_host = 0;
17487 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc);
17488 
17489 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
17490 	    icc.icc_pmtu + icc.icc_onlink);
17491 	delete_cnt = icc.icc_total/ip_ire_reclaim_fraction;
17492 	IP_STAT(ip_trash_ire_reclaim_calls);
17493 	if (delete_cnt == 0)
17494 		return;
17495 	IP_STAT(ip_trash_ire_reclaim_success);
17496 	/* Always delete all unused offlink entries */
17497 	icr.icr_unused = 1;
17498 	if (delete_cnt <= icc.icc_unused) {
17499 		/*
17500 		 * Only need to free unused entries.  In other words,
17501 		 * there are enough unused entries to free to meet our
17502 		 * target number of freed ire cache entries.
17503 		 */
17504 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
17505 		ncr.ncr_host = 0;
17506 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
17507 		/*
17508 		 * Only need to free unused entries, plus a fraction of offlink
17509 		 * entries.  It follows from the first if statement that
17510 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
17511 		 */
17512 		delete_cnt -= icc.icc_unused;
17513 		/* Round up # deleted by truncating fraction */
17514 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
17515 		icr.icr_pmtu = icr.icr_onlink = 0;
17516 		ncr.ncr_host = 0;
17517 	} else if (delete_cnt <=
17518 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
17519 		/*
17520 		 * Free all unused and offlink entries, plus a fraction of
17521 		 * pmtu entries.  It follows from the previous if statement
17522 		 * that icc_pmtu is non-zero, and that
17523 		 * delete_cnt != icc_unused + icc_offlink.
17524 		 */
17525 		icr.icr_offlink = 1;
17526 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
17527 		/* Round up # deleted by truncating fraction */
17528 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
17529 		icr.icr_onlink = 0;
17530 		ncr.ncr_host = 0;
17531 	} else {
17532 		/*
17533 		 * Free all unused, offlink, and pmtu entries, plus a fraction
17534 		 * of onlink entries.  If we're here, then we know that
17535 		 * icc_onlink is non-zero, and that
17536 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
17537 		 */
17538 		icr.icr_offlink = icr.icr_pmtu = 1;
17539 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
17540 		    icc.icc_pmtu;
17541 		/* Round up # deleted by truncating fraction */
17542 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
17543 		/* Using the same delete fraction as for onlink IREs */
17544 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
17545 	}
17546 #ifdef DEBUG
17547 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
17548 	    "fractions %d/%d/%d/%d\n",
17549 	    icc.icc_total/ip_ire_reclaim_fraction, icc.icc_total,
17550 	    icc.icc_unused, icc.icc_offlink,
17551 	    icc.icc_pmtu, icc.icc_onlink,
17552 	    icr.icr_unused, icr.icr_offlink,
17553 	    icr.icr_pmtu, icr.icr_onlink));
17554 #endif
17555 	ire_walk(ire_cache_reclaim, (char *)&icr);
17556 	if (ncr.ncr_host != 0)
17557 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
17558 		    (uchar_t *)&ncr);
17559 #ifdef DEBUG
17560 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
17561 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
17562 	ire_walk(ire_cache_count, (char *)&icc);
17563 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
17564 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
17565 	    icc.icc_pmtu, icc.icc_onlink));
17566 #endif
17567 }
17568 
17569 /*
17570  * ip_unbind is called when a copy of an unbind request is received from the
17571  * upper level protocol.  We remove this conn from any fanout hash list it is
17572  * on, and zero out the bind information.  No reply is expected up above.
17573  */
17574 static void
17575 ip_unbind(queue_t *q, mblk_t *mp)
17576 {
17577 	conn_t	*connp = Q_TO_CONN(q);
17578 
17579 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
17580 
17581 	ipcl_hash_remove(connp);
17582 
17583 	ASSERT(mp->b_cont == NULL);
17584 	/*
17585 	 * Convert mp into a T_OK_ACK
17586 	 */
17587 	mp = mi_tpi_ok_ack_alloc(mp);
17588 
17589 	/*
17590 	 * should not happen in practice... T_OK_ACK is smaller than the
17591 	 * original message.
17592 	 */
17593 	if (mp == NULL)
17594 		return;
17595 
17596 	/*
17597 	 * Don't bzero the ports if its TCP since TCP still needs the
17598 	 * lport to remove it from its own bind hash. TCP will do the
17599 	 * cleanup.
17600 	 */
17601 	if (!IPCL_IS_TCP(connp))
17602 		bzero(&connp->u_port, sizeof (connp->u_port));
17603 
17604 	qreply(q, mp);
17605 }
17606 
17607 /*
17608  * Write side put procedure.  Outbound data, IOCTLs, responses from
17609  * resolvers, etc, come down through here.
17610  */
17611 void
17612 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
17613 {
17614 	conn_t		*connp = NULL;
17615 	queue_t		*q = (queue_t *)arg2;
17616 	ipha_t		*ipha;
17617 #define	rptr	((uchar_t *)ipha)
17618 	ire_t		*ire = NULL;
17619 	ire_t		*sctp_ire = NULL;
17620 	uint32_t	v_hlen_tos_len;
17621 	ipaddr_t	dst;
17622 	mblk_t		*first_mp = NULL;
17623 	boolean_t	mctl_present;
17624 	ipsec_out_t	*io;
17625 	int		match_flags;
17626 	ill_t		*attach_ill = NULL;
17627 					/* Bind to IPIF_NOFAILOVER ill etc. */
17628 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
17629 	ipif_t		*dst_ipif;
17630 	boolean_t	multirt_need_resolve = B_FALSE;
17631 	mblk_t		*copy_mp = NULL;
17632 	int		err;
17633 	zoneid_t	zoneid;
17634 	boolean_t	need_decref = B_FALSE;
17635 	boolean_t	ignore_dontroute = B_FALSE;
17636 
17637 #ifdef	_BIG_ENDIAN
17638 #define	V_HLEN	(v_hlen_tos_len >> 24)
17639 #else
17640 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
17641 #endif
17642 
17643 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
17644 	    "ip_wput_start: q %p", q);
17645 
17646 	/*
17647 	 * ip_wput fast path
17648 	 */
17649 
17650 	/* is packet from ARP ? */
17651 	if (q->q_next != NULL)
17652 		goto qnext;
17653 
17654 	connp = (conn_t *)arg;
17655 	zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
17656 
17657 	/* is queue flow controlled? */
17658 	if ((q->q_first != NULL || connp->conn_draining) &&
17659 	    (caller == IP_WPUT)) {
17660 		goto doputq;
17661 	}
17662 
17663 	/* Multidata transmit? */
17664 	if (DB_TYPE(mp) == M_MULTIDATA) {
17665 		/*
17666 		 * We should never get here, since all Multidata messages
17667 		 * originating from tcp should have been directed over to
17668 		 * tcp_multisend() in the first place.
17669 		 */
17670 		BUMP_MIB(&ip_mib, ipOutDiscards);
17671 		freemsg(mp);
17672 		return;
17673 	} else if (DB_TYPE(mp) != M_DATA)
17674 		goto notdata;
17675 	if (mp->b_flag & MSGHASREF) {
17676 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
17677 		mp->b_flag &= ~MSGHASREF;
17678 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
17679 		need_decref = B_TRUE;
17680 	}
17681 	ipha = (ipha_t *)mp->b_rptr;
17682 
17683 	/* is IP header non-aligned or mblk smaller than basic IP header */
17684 #ifndef SAFETY_BEFORE_SPEED
17685 	if (!OK_32PTR(rptr) ||
17686 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
17687 		goto hdrtoosmall;
17688 #endif
17689 
17690 	/*
17691 	 * If there is a policy, try to attach an ipsec_out in
17692 	 * the front. At the end, first_mp either points to a
17693 	 * M_DATA message or IPSEC_OUT message linked to a
17694 	 * M_DATA message. We have to do it now as we might
17695 	 * lose the "conn" if we go through ip_newroute.
17696 	 */
17697 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
17698 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
17699 		    ipha->ipha_protocol)) == NULL)) {
17700 			if (need_decref)
17701 				CONN_DEC_REF(connp);
17702 			return;
17703 		} else {
17704 			ASSERT(mp->b_datap->db_type == M_CTL);
17705 			first_mp = mp;
17706 			mp = mp->b_cont;
17707 			mctl_present = B_TRUE;
17708 		}
17709 	} else {
17710 		first_mp = mp;
17711 		mctl_present = B_FALSE;
17712 	}
17713 
17714 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
17715 
17716 	/* is wrong version or IP options present */
17717 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
17718 		goto version_hdrlen_check;
17719 	dst = ipha->ipha_dst;
17720 
17721 	if (connp->conn_nofailover_ill != NULL) {
17722 		attach_ill = conn_get_held_ill(connp,
17723 		    &connp->conn_nofailover_ill, &err);
17724 		if (err == ILL_LOOKUP_FAILED) {
17725 			if (need_decref)
17726 				CONN_DEC_REF(connp);
17727 			freemsg(first_mp);
17728 			return;
17729 		}
17730 	}
17731 
17732 	/* is packet multicast? */
17733 	if (CLASSD(dst))
17734 		goto multicast;
17735 
17736 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL)) {
17737 		/*
17738 		 * If the destination is a broadcast or a loopback
17739 		 * address, both SO_DONTROUTE and IP_XMIT_IF go
17740 		 * through the standard path. But in the case of local
17741 		 * destination only SO_DONTROUTE goes through the
17742 		 * standard path not IP_XMIT_IF.
17743 		 */
17744 		ire = ire_cache_lookup(dst, zoneid);
17745 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
17746 		    (ire->ire_type != IRE_LOOPBACK))) {
17747 
17748 			if ((connp->conn_dontroute) && (ire != NULL) &&
17749 				(ire->ire_type == IRE_LOCAL))
17750 				goto standard_path;
17751 
17752 			if (ire != NULL) {
17753 				ire_refrele(ire);
17754 				/* No more access to ire */
17755 				ire = NULL;
17756 			}
17757 			/*
17758 			 * bypass routing checks and go directly to
17759 			 * interface.
17760 			 */
17761 			if (connp->conn_dontroute)
17762 				goto dontroute;
17763 
17764 			/*
17765 			 * If IP_XMIT_IF socket option is set,
17766 			 * then we allow unicast and multicast
17767 			 * packets to go through the ill. It is
17768 			 * quite possible that the destination
17769 			 * is not in the ire cache table and we
17770 			 * do not want to go to ip_newroute()
17771 			 * instead we call ip_newroute_ipif.
17772 			 */
17773 			xmit_ill = conn_get_held_ill(connp,
17774 			    &connp->conn_xmit_if_ill, &err);
17775 			if (err == ILL_LOOKUP_FAILED) {
17776 				if (attach_ill != NULL)
17777 					ill_refrele(attach_ill);
17778 				if (need_decref)
17779 					CONN_DEC_REF(connp);
17780 				freemsg(first_mp);
17781 				return;
17782 			}
17783 			goto send_from_ill;
17784 		}
17785 standard_path:
17786 		/* Must be a broadcast, a loopback or a local ire */
17787 		if (ire != NULL) {
17788 			ire_refrele(ire);
17789 			/* No more access to ire */
17790 			ire = NULL;
17791 		}
17792 	}
17793 
17794 	if (attach_ill != NULL)
17795 		goto send_from_ill;
17796 
17797 	/*
17798 	 * We cache IRE_CACHEs to avoid lookups. We don't do
17799 	 * this for the tcp global queue and listen end point
17800 	 * as it does not really have a real destination to
17801 	 * talk to.  This is also true for SCTP.
17802 	 */
17803 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
17804 	    !connp->conn_fully_bound) {
17805 		ire = ire_cache_lookup(dst, zoneid);
17806 		if (ire == NULL)
17807 			goto noirefound;
17808 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
17809 		    "ip_wput_end: q %p (%S)", q, "end");
17810 
17811 		/*
17812 		 * Check if the ire has the RTF_MULTIRT flag, inherited
17813 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
17814 		 */
17815 		if (ire->ire_flags & RTF_MULTIRT) {
17816 
17817 			/*
17818 			 * Force the TTL of multirouted packets if required.
17819 			 * The TTL of such packets is bounded by the
17820 			 * ip_multirt_ttl ndd variable.
17821 			 */
17822 			if ((ip_multirt_ttl > 0) &&
17823 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
17824 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
17825 				    "(was %d), dst 0x%08x\n",
17826 				    ip_multirt_ttl, ipha->ipha_ttl,
17827 				    ntohl(ire->ire_addr)));
17828 				ipha->ipha_ttl = ip_multirt_ttl;
17829 			}
17830 			/*
17831 			 * We look at this point if there are pending
17832 			 * unresolved routes. ire_multirt_resolvable()
17833 			 * checks in O(n) that all IRE_OFFSUBNET ire
17834 			 * entries for the packet's destination and
17835 			 * flagged RTF_MULTIRT are currently resolved.
17836 			 * If some remain unresolved, we make a copy
17837 			 * of the current message. It will be used
17838 			 * to initiate additional route resolutions.
17839 			 */
17840 			multirt_need_resolve =
17841 			    ire_multirt_need_resolve(ire->ire_addr);
17842 			ip2dbg(("ip_wput[TCP]: ire %p, "
17843 			    "multirt_need_resolve %d, first_mp %p\n",
17844 			    (void *)ire, multirt_need_resolve,
17845 			    (void *)first_mp));
17846 			if (multirt_need_resolve) {
17847 				copy_mp = copymsg(first_mp);
17848 				if (copy_mp != NULL) {
17849 					MULTIRT_DEBUG_TAG(copy_mp);
17850 				}
17851 			}
17852 		}
17853 
17854 		ip_wput_ire(q, first_mp, ire, connp, caller);
17855 
17856 		/*
17857 		 * Try to resolve another multiroute if
17858 		 * ire_multirt_need_resolve() deemed it necessary.
17859 		 */
17860 		if (copy_mp != NULL) {
17861 			ip_newroute(q, copy_mp, dst, NULL, connp);
17862 		}
17863 		if (need_decref)
17864 			CONN_DEC_REF(connp);
17865 		return;
17866 	}
17867 
17868 	/*
17869 	 * Access to conn_ire_cache. (protected by conn_lock)
17870 	 *
17871 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
17872 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
17873 	 * send a packet or two with the IRE_CACHE that is going away.
17874 	 * Access to the ire requires an ire refhold on the ire prior to
17875 	 * its use since an interface unplumb thread may delete the cached
17876 	 * ire and release the refhold at any time.
17877 	 *
17878 	 * Caching an ire in the conn_ire_cache
17879 	 *
17880 	 * o Caching an ire pointer in the conn requires a strict check for
17881 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
17882 	 * ires  before cleaning up the conns. So the caching of an ire pointer
17883 	 * in the conn is done after making sure under the bucket lock that the
17884 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
17885 	 * caching an ire after the unplumb thread has cleaned up the conn.
17886 	 * If the conn does not send a packet subsequently the unplumb thread
17887 	 * will be hanging waiting for the ire count to drop to zero.
17888 	 *
17889 	 * o We also need to atomically test for a null conn_ire_cache and
17890 	 * set the conn_ire_cache under the the protection of the conn_lock
17891 	 * to avoid races among concurrent threads trying to simultaneously
17892 	 * cache an ire in the conn_ire_cache.
17893 	 */
17894 	mutex_enter(&connp->conn_lock);
17895 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
17896 
17897 	if (ire != NULL && ire->ire_addr == dst &&
17898 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
17899 
17900 		IRE_REFHOLD(ire);
17901 		mutex_exit(&connp->conn_lock);
17902 
17903 	} else {
17904 		boolean_t cached = B_FALSE;
17905 		connp->conn_ire_cache = NULL;
17906 		mutex_exit(&connp->conn_lock);
17907 		/* Release the old ire */
17908 		if (ire != NULL && sctp_ire == NULL)
17909 			IRE_REFRELE_NOTR(ire);
17910 
17911 		ire = (ire_t *)ire_cache_lookup(dst, zoneid);
17912 		if (ire == NULL)
17913 			goto noirefound;
17914 		IRE_REFHOLD_NOTR(ire);
17915 
17916 		mutex_enter(&connp->conn_lock);
17917 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
17918 		    connp->conn_ire_cache == NULL) {
17919 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
17920 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
17921 				connp->conn_ire_cache = ire;
17922 				cached = B_TRUE;
17923 			}
17924 			rw_exit(&ire->ire_bucket->irb_lock);
17925 		}
17926 		mutex_exit(&connp->conn_lock);
17927 
17928 		/*
17929 		 * We can continue to use the ire but since it was
17930 		 * not cached, we should drop the extra reference.
17931 		 */
17932 		if (!cached)
17933 			IRE_REFRELE_NOTR(ire);
17934 	}
17935 
17936 
17937 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
17938 	    "ip_wput_end: q %p (%S)", q, "end");
17939 
17940 	/*
17941 	 * Check if the ire has the RTF_MULTIRT flag, inherited
17942 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
17943 	 */
17944 	if (ire->ire_flags & RTF_MULTIRT) {
17945 
17946 		/*
17947 		 * Force the TTL of multirouted packets if required.
17948 		 * The TTL of such packets is bounded by the
17949 		 * ip_multirt_ttl ndd variable.
17950 		 */
17951 		if ((ip_multirt_ttl > 0) &&
17952 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
17953 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
17954 			    "(was %d), dst 0x%08x\n",
17955 			    ip_multirt_ttl, ipha->ipha_ttl,
17956 			    ntohl(ire->ire_addr)));
17957 			ipha->ipha_ttl = ip_multirt_ttl;
17958 		}
17959 
17960 		/*
17961 		 * At this point, we check to see if there are any pending
17962 		 * unresolved routes. ire_multirt_resolvable()
17963 		 * checks in O(n) that all IRE_OFFSUBNET ire
17964 		 * entries for the packet's destination and
17965 		 * flagged RTF_MULTIRT are currently resolved.
17966 		 * If some remain unresolved, we make a copy
17967 		 * of the current message. It will be used
17968 		 * to initiate additional route resolutions.
17969 		 */
17970 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr);
17971 		ip2dbg(("ip_wput[not TCP]: ire %p, "
17972 		    "multirt_need_resolve %d, first_mp %p\n",
17973 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
17974 		if (multirt_need_resolve) {
17975 			copy_mp = copymsg(first_mp);
17976 			if (copy_mp != NULL) {
17977 				MULTIRT_DEBUG_TAG(copy_mp);
17978 			}
17979 		}
17980 	}
17981 
17982 	ip_wput_ire(q, first_mp, ire, connp, caller);
17983 
17984 	/*
17985 	 * Try to resolve another multiroute if
17986 	 * ire_multirt_resolvable() deemed it necessary
17987 	 */
17988 	if (copy_mp != NULL) {
17989 		ip_newroute(q, copy_mp, dst, NULL, connp);
17990 	}
17991 	if (need_decref)
17992 		CONN_DEC_REF(connp);
17993 	return;
17994 
17995 doputq:
17996 	ASSERT(!need_decref);
17997 	(void) putq(q, mp);
17998 	return;
17999 
18000 qnext:
18001 	/*
18002 	 * Upper Level Protocols pass down complete IP datagrams
18003 	 * as M_DATA messages.	Everything else is a sideshow.
18004 	 *
18005 	 * 1) We could be re-entering ip_wput because of ip_neworute
18006 	 *    in which case we could have a IPSEC_OUT message. We
18007 	 *    need to pass through ip_wput like other datagrams and
18008 	 *    hence cannot branch to ip_wput_nondata.
18009 	 *
18010 	 * 2) ARP, AH, ESP, and other clients who are on the module
18011 	 *    instance of IP stream, give us something to deal with.
18012 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
18013 	 *
18014 	 * 3) ICMP replies also could come here.
18015 	 */
18016 	if (DB_TYPE(mp) != M_DATA) {
18017 	    notdata:
18018 		if (DB_TYPE(mp) == M_CTL) {
18019 			/*
18020 			 * M_CTL messages are used by ARP, AH and ESP to
18021 			 * communicate with IP. We deal with IPSEC_IN and
18022 			 * IPSEC_OUT here. ip_wput_nondata handles other
18023 			 * cases.
18024 			 */
18025 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
18026 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
18027 				first_mp = mp->b_cont;
18028 				first_mp->b_flag &= ~MSGHASREF;
18029 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
18030 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
18031 				CONN_DEC_REF(connp);
18032 				connp = NULL;
18033 			}
18034 			if (ii->ipsec_info_type == IPSEC_IN) {
18035 				/*
18036 				 * Either this message goes back to
18037 				 * IPSEC for further processing or to
18038 				 * ULP after policy checks.
18039 				 */
18040 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
18041 				return;
18042 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
18043 				io = (ipsec_out_t *)ii;
18044 				if (io->ipsec_out_proc_begin) {
18045 					/*
18046 					 * IPSEC processing has already started.
18047 					 * Complete it.
18048 					 * IPQoS notes: We don't care what is
18049 					 * in ipsec_out_ill_index since this
18050 					 * won't be processed for IPQoS policies
18051 					 * in ipsec_out_process.
18052 					 */
18053 					ipsec_out_process(q, mp, NULL,
18054 					    io->ipsec_out_ill_index);
18055 					return;
18056 				} else {
18057 					connp = (q->q_next != NULL) ?
18058 					    NULL : Q_TO_CONN(q);
18059 					first_mp = mp;
18060 					mp = mp->b_cont;
18061 					mctl_present = B_TRUE;
18062 				}
18063 				zoneid = io->ipsec_out_zoneid;
18064 				ASSERT(zoneid != ALL_ZONES);
18065 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
18066 				/*
18067 				 * It's an IPsec control message requesting
18068 				 * an SADB update to be sent to the IPsec
18069 				 * hardware acceleration capable ills.
18070 				 */
18071 				ipsec_ctl_t *ipsec_ctl =
18072 				    (ipsec_ctl_t *)mp->b_rptr;
18073 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
18074 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
18075 				mblk_t *cmp = mp->b_cont;
18076 
18077 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
18078 				ASSERT(cmp != NULL);
18079 
18080 				freeb(mp);
18081 				ill_ipsec_capab_send_all(satype, cmp, sa);
18082 				return;
18083 			} else {
18084 				/*
18085 				 * This must be ARP.
18086 				 */
18087 				ip_wput_nondata(NULL, q, mp, NULL);
18088 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18089 				    "ip_wput_end: q %p (%S)", q, "nondata");
18090 				return;
18091 			}
18092 		} else {
18093 			/*
18094 			 * This must be non-(ARP/AH/ESP) messages.
18095 			 */
18096 			ASSERT(!need_decref);
18097 			ip_wput_nondata(NULL, q, mp, NULL);
18098 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18099 			    "ip_wput_end: q %p (%S)", q, "nondata");
18100 			return;
18101 		}
18102 	} else {
18103 		first_mp = mp;
18104 		mctl_present = B_FALSE;
18105 	}
18106 
18107 	ASSERT(first_mp != NULL);
18108 	/*
18109 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
18110 	 * to make sure that this packet goes out on the same interface it
18111 	 * came in. We handle that here.
18112 	 */
18113 	if (mctl_present) {
18114 		uint_t ifindex;
18115 
18116 		io = (ipsec_out_t *)first_mp->b_rptr;
18117 		if (io->ipsec_out_attach_if ||
18118 		    io->ipsec_out_xmit_if) {
18119 			ill_t	*ill;
18120 
18121 			ASSERT(io->ipsec_out_ill_index != 0);
18122 			ifindex = io->ipsec_out_ill_index;
18123 			ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
18124 			    NULL, NULL, NULL, NULL);
18125 			/*
18126 			 * ipsec_out_xmit_if bit is used to tell
18127 			 * ip_wput to use the ill to send outgoing data
18128 			 * as we have no conn when data comes from ICMP
18129 			 * error msg routines. Currently this feature is
18130 			 * only used by ip_mrtun_forward routine.
18131 			 */
18132 			if (io->ipsec_out_xmit_if) {
18133 				xmit_ill = ill;
18134 				if (xmit_ill == NULL) {
18135 					ip1dbg(("ip_wput: bad ifindex for"
18136 					    "xmit_ill %d\n", ifindex));
18137 					freemsg(first_mp);
18138 					BUMP_MIB(&ip_mib, ipOutDiscards);
18139 					ASSERT(!need_decref);
18140 					return;
18141 				}
18142 				/* Free up the ipsec_out_t mblk */
18143 				ASSERT(first_mp->b_cont == mp);
18144 				first_mp->b_cont = NULL;
18145 				freeb(first_mp);
18146 				/* Just send the IP header+ICMP+data */
18147 				first_mp = mp;
18148 				ipha = (ipha_t *)mp->b_rptr;
18149 				dst = ipha->ipha_dst;
18150 				goto send_from_ill;
18151 
18152 			} else {
18153 				attach_ill = ill;
18154 			}
18155 
18156 			if (attach_ill == NULL) {
18157 				ASSERT(xmit_ill == NULL);
18158 				ip1dbg(("ip_wput : bad ifindex for "
18159 				    "(BIND TO IPIF_NOFAILOVER) %d\n", ifindex));
18160 				freemsg(first_mp);
18161 				BUMP_MIB(&ip_mib, ipOutDiscards);
18162 				ASSERT(!need_decref);
18163 				return;
18164 			}
18165 		}
18166 	}
18167 
18168 	ASSERT(xmit_ill == NULL);
18169 
18170 	/* We have a complete IP datagram heading outbound. */
18171 	ipha = (ipha_t *)mp->b_rptr;
18172 
18173 #ifndef SPEED_BEFORE_SAFETY
18174 	/*
18175 	 * Make sure we have a full-word aligned message and that at least
18176 	 * a simple IP header is accessible in the first message.  If not,
18177 	 * try a pullup.
18178 	 */
18179 	if (!OK_32PTR(rptr) ||
18180 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
18181 	    hdrtoosmall:
18182 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
18183 			BUMP_MIB(&ip_mib, ipOutDiscards);
18184 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18185 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
18186 			if (first_mp == NULL)
18187 				first_mp = mp;
18188 			goto drop_pkt;
18189 		}
18190 		ipha = (ipha_t *)mp->b_rptr;
18191 		if (first_mp == NULL) {
18192 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
18193 			/*
18194 			 * If we got here because of "goto hdrtoosmall"
18195 			 * We need to attach a IPSEC_OUT.
18196 			 */
18197 			if (connp->conn_out_enforce_policy) {
18198 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
18199 				    NULL, ipha->ipha_protocol)) == NULL)) {
18200 					if (need_decref)
18201 						CONN_DEC_REF(connp);
18202 					return;
18203 				} else {
18204 					ASSERT(mp->b_datap->db_type == M_CTL);
18205 					first_mp = mp;
18206 					mp = mp->b_cont;
18207 					mctl_present = B_TRUE;
18208 				}
18209 			} else {
18210 				first_mp = mp;
18211 				mctl_present = B_FALSE;
18212 			}
18213 		}
18214 	}
18215 #endif
18216 
18217 	/* Most of the code below is written for speed, not readability */
18218 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
18219 
18220 	/*
18221 	 * If ip_newroute() fails, we're going to need a full
18222 	 * header for the icmp wraparound.
18223 	 */
18224 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
18225 		uint_t	v_hlen;
18226 	    version_hdrlen_check:
18227 		ASSERT(first_mp != NULL);
18228 		v_hlen = V_HLEN;
18229 		/*
18230 		 * siphon off IPv6 packets coming down from transport
18231 		 * layer modules here.
18232 		 * Note: high-order bit carries NUD reachability confirmation
18233 		 */
18234 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
18235 			/*
18236 			 * XXX implement a IPv4 and IPv6 packet counter per
18237 			 * conn and switch when ratio exceeds e.g. 10:1
18238 			 */
18239 #ifdef notyet
18240 			if (q->q_next == NULL) /* Avoid ill queue */
18241 				ip_setqinfo(RD(q), B_TRUE, B_TRUE);
18242 #endif
18243 			BUMP_MIB(&ip_mib, ipOutIPv6);
18244 			ASSERT(xmit_ill == NULL);
18245 			if (attach_ill != NULL)
18246 				ill_refrele(attach_ill);
18247 			if (need_decref)
18248 				mp->b_flag |= MSGHASREF;
18249 			(void) ip_output_v6(connp, first_mp, q, caller);
18250 			return;
18251 		}
18252 
18253 		if ((v_hlen >> 4) != IP_VERSION) {
18254 			BUMP_MIB(&ip_mib, ipOutDiscards);
18255 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18256 			    "ip_wput_end: q %p (%S)", q, "badvers");
18257 			goto drop_pkt;
18258 		}
18259 		/*
18260 		 * Is the header length at least 20 bytes?
18261 		 *
18262 		 * Are there enough bytes accessible in the header?  If
18263 		 * not, try a pullup.
18264 		 */
18265 		v_hlen &= 0xF;
18266 		v_hlen <<= 2;
18267 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
18268 			BUMP_MIB(&ip_mib, ipOutDiscards);
18269 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18270 			    "ip_wput_end: q %p (%S)", q, "badlen");
18271 			goto drop_pkt;
18272 		}
18273 		if (v_hlen > (mp->b_wptr - rptr)) {
18274 			if (!pullupmsg(mp, v_hlen)) {
18275 				BUMP_MIB(&ip_mib, ipOutDiscards);
18276 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18277 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
18278 				goto drop_pkt;
18279 			}
18280 			ipha = (ipha_t *)mp->b_rptr;
18281 		}
18282 		/*
18283 		 * Move first entry from any source route into ipha_dst and
18284 		 * verify the options
18285 		 */
18286 		if (ip_wput_options(q, first_mp, ipha, mctl_present, zoneid)) {
18287 			ASSERT(xmit_ill == NULL);
18288 			if (attach_ill != NULL)
18289 				ill_refrele(attach_ill);
18290 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18291 			    "ip_wput_end: q %p (%S)", q, "badopts");
18292 			if (need_decref)
18293 				CONN_DEC_REF(connp);
18294 			return;
18295 		}
18296 	}
18297 	dst = ipha->ipha_dst;
18298 
18299 	/*
18300 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
18301 	 * we have to run the packet through ip_newroute which will take
18302 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
18303 	 * a resolver, or assigning a default gateway, etc.
18304 	 */
18305 	if (CLASSD(dst)) {
18306 		ipif_t	*ipif;
18307 		uint32_t setsrc = 0;
18308 
18309 	    multicast:
18310 		ASSERT(first_mp != NULL);
18311 		ASSERT(xmit_ill == NULL);
18312 		ip2dbg(("ip_wput: CLASSD\n"));
18313 		if (connp == NULL) {
18314 			/*
18315 			 * Use the first good ipif on the ill.
18316 			 * XXX Should this ever happen? (Appears
18317 			 * to show up with just ppp and no ethernet due
18318 			 * to in.rdisc.)
18319 			 * However, ire_send should be able to
18320 			 * call ip_wput_ire directly.
18321 			 *
18322 			 * XXX Also, this can happen for ICMP and other packets
18323 			 * with multicast source addresses.  Perhaps we should
18324 			 * fix things so that we drop the packet in question,
18325 			 * but for now, just run with it.
18326 			 */
18327 			ill_t *ill = (ill_t *)q->q_ptr;
18328 
18329 			/*
18330 			 * Don't honor attach_if for this case. If ill
18331 			 * is part of the group, ipif could belong to
18332 			 * any ill and we cannot maintain attach_ill
18333 			 * and ipif_ill same anymore and the assert
18334 			 * below would fail.
18335 			 */
18336 			if (mctl_present) {
18337 				io->ipsec_out_ill_index = 0;
18338 				io->ipsec_out_attach_if = B_FALSE;
18339 				ASSERT(attach_ill != NULL);
18340 				ill_refrele(attach_ill);
18341 				attach_ill = NULL;
18342 			}
18343 
18344 			ASSERT(attach_ill == NULL);
18345 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
18346 			if (ipif == NULL) {
18347 				if (need_decref)
18348 					CONN_DEC_REF(connp);
18349 				freemsg(first_mp);
18350 				return;
18351 			}
18352 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
18353 			    ntohl(dst), ill->ill_name));
18354 		} else {
18355 			/*
18356 			 * If both IP_MULTICAST_IF and IP_XMIT_IF are set,
18357 			 * IP_XMIT_IF is honoured.
18358 			 * Block comment above this function explains the
18359 			 * locking mechanism used here
18360 			 */
18361 			xmit_ill = conn_get_held_ill(connp,
18362 			    &connp->conn_xmit_if_ill, &err);
18363 			if (err == ILL_LOOKUP_FAILED) {
18364 				ip1dbg(("ip_wput: No ill for IP_XMIT_IF\n"));
18365 				goto drop_pkt;
18366 			}
18367 			if (xmit_ill == NULL) {
18368 				ipif = conn_get_held_ipif(connp,
18369 				    &connp->conn_multicast_ipif, &err);
18370 				if (err == IPIF_LOOKUP_FAILED) {
18371 					ip1dbg(("ip_wput: No ipif for "
18372 					    "multicast\n"));
18373 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18374 					goto drop_pkt;
18375 				}
18376 			}
18377 			if (xmit_ill != NULL) {
18378 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
18379 				if (ipif == NULL) {
18380 					ip1dbg(("ip_wput: No ipif for "
18381 					    "IP_XMIT_IF\n"));
18382 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18383 					goto drop_pkt;
18384 				}
18385 			} else if (ipif == NULL || ipif->ipif_isv6) {
18386 				/*
18387 				 * We must do this ipif determination here
18388 				 * else we could pass through ip_newroute
18389 				 * and come back here without the conn context.
18390 				 *
18391 				 * Note: we do late binding i.e. we bind to
18392 				 * the interface when the first packet is sent.
18393 				 * For performance reasons we do not rebind on
18394 				 * each packet but keep the binding until the
18395 				 * next IP_MULTICAST_IF option.
18396 				 *
18397 				 * conn_multicast_{ipif,ill} are shared between
18398 				 * IPv4 and IPv6 and AF_INET6 sockets can
18399 				 * send both IPv4 and IPv6 packets. Hence
18400 				 * we have to check that "isv6" matches above.
18401 				 */
18402 				if (ipif != NULL)
18403 					ipif_refrele(ipif);
18404 				ipif = ipif_lookup_group(dst, zoneid);
18405 				if (ipif == NULL) {
18406 					ip1dbg(("ip_wput: No ipif for "
18407 					    "multicast\n"));
18408 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18409 					goto drop_pkt;
18410 				}
18411 				err = conn_set_held_ipif(connp,
18412 				    &connp->conn_multicast_ipif, ipif);
18413 				if (err == IPIF_LOOKUP_FAILED) {
18414 					ipif_refrele(ipif);
18415 					ip1dbg(("ip_wput: No ipif for "
18416 					    "multicast\n"));
18417 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18418 					goto drop_pkt;
18419 				}
18420 			}
18421 		}
18422 		ASSERT(!ipif->ipif_isv6);
18423 		/*
18424 		 * As we may lose the conn by the time we reach ip_wput_ire,
18425 		 * we copy conn_multicast_loop and conn_dontroute on to an
18426 		 * ipsec_out. In case if this datagram goes out secure,
18427 		 * we need the ill_index also. Copy that also into the
18428 		 * ipsec_out.
18429 		 */
18430 		if (mctl_present) {
18431 			io = (ipsec_out_t *)first_mp->b_rptr;
18432 			ASSERT(first_mp->b_datap->db_type == M_CTL);
18433 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
18434 		} else {
18435 			ASSERT(mp == first_mp);
18436 			if ((first_mp = allocb(sizeof (ipsec_info_t),
18437 			    BPRI_HI)) == NULL) {
18438 				ipif_refrele(ipif);
18439 				first_mp = mp;
18440 				goto drop_pkt;
18441 			}
18442 			first_mp->b_datap->db_type = M_CTL;
18443 			first_mp->b_wptr += sizeof (ipsec_info_t);
18444 			/* ipsec_out_secure is B_FALSE now */
18445 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
18446 			io = (ipsec_out_t *)first_mp->b_rptr;
18447 			io->ipsec_out_type = IPSEC_OUT;
18448 			io->ipsec_out_len = sizeof (ipsec_out_t);
18449 			io->ipsec_out_use_global_policy = B_TRUE;
18450 			first_mp->b_cont = mp;
18451 			mctl_present = B_TRUE;
18452 		}
18453 		if (attach_ill != NULL) {
18454 			ASSERT(attach_ill == ipif->ipif_ill);
18455 			match_flags = MATCH_IRE_ILL;
18456 
18457 			/*
18458 			 * Check if we need an ire that will not be
18459 			 * looked up by anybody else i.e. HIDDEN.
18460 			 */
18461 			if (ill_is_probeonly(attach_ill)) {
18462 				match_flags |= MATCH_IRE_MARK_HIDDEN;
18463 			}
18464 			io->ipsec_out_ill_index =
18465 			    attach_ill->ill_phyint->phyint_ifindex;
18466 			io->ipsec_out_attach_if = B_TRUE;
18467 		} else {
18468 			match_flags = MATCH_IRE_ILL_GROUP;
18469 			io->ipsec_out_ill_index =
18470 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
18471 		}
18472 		if (connp != NULL) {
18473 			io->ipsec_out_multicast_loop =
18474 			    connp->conn_multicast_loop;
18475 			io->ipsec_out_dontroute = connp->conn_dontroute;
18476 			io->ipsec_out_zoneid = connp->conn_zoneid;
18477 		}
18478 		/*
18479 		 * If the application uses IP_MULTICAST_IF with
18480 		 * different logical addresses of the same ILL, we
18481 		 * need to make sure that the soruce address of
18482 		 * the packet matches the logical IP address used
18483 		 * in the option. We do it by initializing ipha_src
18484 		 * here. This should keep IPSEC also happy as
18485 		 * when we return from IPSEC processing, we don't
18486 		 * have to worry about getting the right address on
18487 		 * the packet. Thus it is sufficient to look for
18488 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
18489 		 * MATCH_IRE_IPIF.
18490 		 *
18491 		 * NOTE : We need to do it for non-secure case also as
18492 		 * this might go out secure if there is a global policy
18493 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
18494 		 * address, the source should be initialized already and
18495 		 * hence we won't be initializing here.
18496 		 *
18497 		 * As we do not have the ire yet, it is possible that
18498 		 * we set the source address here and then later discover
18499 		 * that the ire implies the source address to be assigned
18500 		 * through the RTF_SETSRC flag.
18501 		 * In that case, the setsrc variable will remind us
18502 		 * that overwritting the source address by the one
18503 		 * of the RTF_SETSRC-flagged ire is allowed.
18504 		 */
18505 		if (ipha->ipha_src == INADDR_ANY &&
18506 		    (connp == NULL || !connp->conn_unspec_src)) {
18507 			ipha->ipha_src = ipif->ipif_src_addr;
18508 			setsrc = RTF_SETSRC;
18509 		}
18510 		/*
18511 		 * Find an IRE which matches the destination and the outgoing
18512 		 * queue (i.e. the outgoing interface.)
18513 		 * For loopback use a unicast IP address for
18514 		 * the ire lookup.
18515 		 */
18516 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
18517 		    PHYI_LOOPBACK) {
18518 			dst = ipif->ipif_lcl_addr;
18519 		}
18520 		/*
18521 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
18522 		 * We don't need to lookup ire in ctable as the packet
18523 		 * needs to be sent to the destination through the specified
18524 		 * ill irrespective of ires in the cache table.
18525 		 */
18526 		ire = NULL;
18527 		if (xmit_ill == NULL) {
18528 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
18529 			    zoneid, match_flags);
18530 		}
18531 
18532 		/*
18533 		 * refrele attach_ill as its not needed anymore.
18534 		 */
18535 		if (attach_ill != NULL) {
18536 			ill_refrele(attach_ill);
18537 			attach_ill = NULL;
18538 		}
18539 
18540 		if (ire == NULL) {
18541 			/*
18542 			 * Multicast loopback and multicast forwarding is
18543 			 * done in ip_wput_ire.
18544 			 *
18545 			 * Mark this packet to make it be delivered to
18546 			 * ip_wput_ire after the new ire has been
18547 			 * created.
18548 			 *
18549 			 * The call to ip_newroute_ipif takes into account
18550 			 * the setsrc reminder. In any case, we take care
18551 			 * of the RTF_MULTIRT flag.
18552 			 */
18553 			mp->b_prev = mp->b_next = NULL;
18554 			if (xmit_ill == NULL ||
18555 			    xmit_ill->ill_ipif_up_count > 0) {
18556 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
18557 				    setsrc | RTF_MULTIRT);
18558 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18559 				    "ip_wput_end: q %p (%S)", q, "noire");
18560 			} else {
18561 				freemsg(first_mp);
18562 			}
18563 			ipif_refrele(ipif);
18564 			if (xmit_ill != NULL)
18565 				ill_refrele(xmit_ill);
18566 			if (need_decref)
18567 				CONN_DEC_REF(connp);
18568 			return;
18569 		}
18570 
18571 		ipif_refrele(ipif);
18572 		ipif = NULL;
18573 		ASSERT(xmit_ill == NULL);
18574 
18575 		/*
18576 		 * Honor the RTF_SETSRC flag for multicast packets,
18577 		 * if allowed by the setsrc reminder.
18578 		 */
18579 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
18580 			ipha->ipha_src = ire->ire_src_addr;
18581 		}
18582 
18583 		/*
18584 		 * Unconditionally force the TTL to 1 for
18585 		 * multirouted multicast packets:
18586 		 * multirouted multicast should not cross
18587 		 * multicast routers.
18588 		 */
18589 		if (ire->ire_flags & RTF_MULTIRT) {
18590 			if (ipha->ipha_ttl > 1) {
18591 				ip2dbg(("ip_wput: forcing multicast "
18592 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
18593 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
18594 				ipha->ipha_ttl = 1;
18595 			}
18596 		}
18597 	} else {
18598 		ire = ire_cache_lookup(dst, zoneid);
18599 		if ((ire != NULL) && (ire->ire_type &
18600 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
18601 			ignore_dontroute = B_TRUE;
18602 		}
18603 		if (ire != NULL) {
18604 			ire_refrele(ire);
18605 			ire = NULL;
18606 		}
18607 		/*
18608 		 * Guard against coming in from arp in which case conn is NULL.
18609 		 * Also guard against non M_DATA with dontroute set but
18610 		 * destined to local, loopback or broadcast addresses.
18611 		 */
18612 		if (connp != NULL && connp->conn_dontroute &&
18613 		    !ignore_dontroute) {
18614 dontroute:
18615 			/*
18616 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
18617 			 * routing protocols from seeing false direct
18618 			 * connectivity.
18619 			 */
18620 			ipha->ipha_ttl = 1;
18621 			/*
18622 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
18623 			 * along with SO_DONTROUTE, higher precedence is
18624 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
18625 			 */
18626 			if (connp->conn_xmit_if_ill == NULL) {
18627 				/* If suitable ipif not found, drop packet */
18628 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid);
18629 				if (dst_ipif == NULL) {
18630 					ip1dbg(("ip_wput: no route for "
18631 					    "dst using SO_DONTROUTE\n"));
18632 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
18633 					mp->b_prev = mp->b_next = NULL;
18634 					if (first_mp == NULL)
18635 						first_mp = mp;
18636 					goto drop_pkt;
18637 				} else {
18638 					/*
18639 					 * If suitable ipif has been found, set
18640 					 * xmit_ill to the corresponding
18641 					 * ipif_ill because we'll be following
18642 					 * the IP_XMIT_IF logic.
18643 					 */
18644 					ASSERT(xmit_ill == NULL);
18645 					xmit_ill = dst_ipif->ipif_ill;
18646 					mutex_enter(&xmit_ill->ill_lock);
18647 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
18648 						mutex_exit(&xmit_ill->ill_lock);
18649 						xmit_ill = NULL;
18650 						ipif_refrele(dst_ipif);
18651 						ip1dbg(("ip_wput: no route for"
18652 						    " dst using"
18653 						    " SO_DONTROUTE\n"));
18654 						BUMP_MIB(&ip_mib,
18655 						    ipOutNoRoutes);
18656 						mp->b_prev = mp->b_next = NULL;
18657 						if (first_mp == NULL)
18658 							first_mp = mp;
18659 						goto drop_pkt;
18660 					}
18661 					ill_refhold_locked(xmit_ill);
18662 					mutex_exit(&xmit_ill->ill_lock);
18663 					ipif_refrele(dst_ipif);
18664 				}
18665 			}
18666 
18667 		}
18668 		/*
18669 		 * If we are bound to IPIF_NOFAILOVER address, look for
18670 		 * an IRE_CACHE matching the ill.
18671 		 */
18672 send_from_ill:
18673 		if (attach_ill != NULL) {
18674 			ipif_t	*attach_ipif;
18675 
18676 			match_flags = MATCH_IRE_ILL;
18677 
18678 			/*
18679 			 * Check if we need an ire that will not be
18680 			 * looked up by anybody else i.e. HIDDEN.
18681 			 */
18682 			if (ill_is_probeonly(attach_ill)) {
18683 				match_flags |= MATCH_IRE_MARK_HIDDEN;
18684 			}
18685 
18686 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
18687 			if (attach_ipif == NULL) {
18688 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
18689 				goto drop_pkt;
18690 			}
18691 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
18692 			    zoneid, match_flags);
18693 			ipif_refrele(attach_ipif);
18694 		} else if (xmit_ill != NULL || (connp != NULL &&
18695 			    connp->conn_xmit_if_ill != NULL)) {
18696 			/*
18697 			 * Mark this packet as originated locally
18698 			 */
18699 			mp->b_prev = mp->b_next = NULL;
18700 			/*
18701 			 * xmit_ill could be NULL if SO_DONTROUTE
18702 			 * is also set.
18703 			 */
18704 			if (xmit_ill == NULL) {
18705 				xmit_ill = conn_get_held_ill(connp,
18706 				    &connp->conn_xmit_if_ill, &err);
18707 				if (err == ILL_LOOKUP_FAILED) {
18708 					if (need_decref)
18709 						CONN_DEC_REF(connp);
18710 					freemsg(first_mp);
18711 					return;
18712 				}
18713 				if (xmit_ill == NULL) {
18714 					if (connp->conn_dontroute)
18715 						goto dontroute;
18716 					goto send_from_ill;
18717 				}
18718 			}
18719 			/*
18720 			 * could be SO_DONTROUTE case also.
18721 			 * check at least one interface is UP as
18722 			 * spcified by this ILL, and then call
18723 			 * ip_newroute_ipif()
18724 			 */
18725 			if (xmit_ill->ill_ipif_up_count > 0) {
18726 				ipif_t *ipif;
18727 
18728 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
18729 				if (ipif != NULL) {
18730 					ip_newroute_ipif(q, first_mp, ipif,
18731 					    dst, connp, 0);
18732 					ipif_refrele(ipif);
18733 					ip1dbg(("ip_wput: ip_unicast_if\n"));
18734 				}
18735 			} else {
18736 				freemsg(first_mp);
18737 			}
18738 			ill_refrele(xmit_ill);
18739 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18740 			    "ip_wput_end: q %p (%S)", q, "unicast_if");
18741 			if (need_decref)
18742 				CONN_DEC_REF(connp);
18743 			return;
18744 		} else {
18745 			ire = ire_cache_lookup(dst, zoneid);
18746 		}
18747 		if (!ire) {
18748 			/*
18749 			 * Make sure we don't load spread if this
18750 			 * is IPIF_NOFAILOVER case.
18751 			 */
18752 			if (attach_ill != NULL) {
18753 				if (mctl_present) {
18754 					io = (ipsec_out_t *)first_mp->b_rptr;
18755 					ASSERT(first_mp->b_datap->db_type ==
18756 					    M_CTL);
18757 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
18758 				} else {
18759 					ASSERT(mp == first_mp);
18760 					first_mp = allocb(
18761 					    sizeof (ipsec_info_t), BPRI_HI);
18762 					if (first_mp == NULL) {
18763 						first_mp = mp;
18764 						goto drop_pkt;
18765 					}
18766 					first_mp->b_datap->db_type = M_CTL;
18767 					first_mp->b_wptr +=
18768 					    sizeof (ipsec_info_t);
18769 					/* ipsec_out_secure is B_FALSE now */
18770 					bzero(first_mp->b_rptr,
18771 					    sizeof (ipsec_info_t));
18772 					io = (ipsec_out_t *)first_mp->b_rptr;
18773 					io->ipsec_out_type = IPSEC_OUT;
18774 					io->ipsec_out_len =
18775 					    sizeof (ipsec_out_t);
18776 					io->ipsec_out_use_global_policy =
18777 					    B_TRUE;
18778 					first_mp->b_cont = mp;
18779 					mctl_present = B_TRUE;
18780 				}
18781 				io->ipsec_out_ill_index = attach_ill->
18782 				    ill_phyint->phyint_ifindex;
18783 				io->ipsec_out_attach_if = B_TRUE;
18784 			}
18785 noirefound:
18786 			/*
18787 			 * Mark this packet as having originated on
18788 			 * this machine.  This will be noted in
18789 			 * ire_add_then_send, which needs to know
18790 			 * whether to run it back through ip_wput or
18791 			 * ip_rput following successful resolution.
18792 			 */
18793 			mp->b_prev = NULL;
18794 			mp->b_next = NULL;
18795 			ip_newroute(q, first_mp, dst, NULL, connp);
18796 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18797 			    "ip_wput_end: q %p (%S)", q, "newroute");
18798 			if (attach_ill != NULL)
18799 				ill_refrele(attach_ill);
18800 			if (xmit_ill != NULL)
18801 				ill_refrele(xmit_ill);
18802 			if (need_decref)
18803 				CONN_DEC_REF(connp);
18804 			return;
18805 		}
18806 	}
18807 
18808 	/* We now know where we are going with it. */
18809 
18810 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18811 	    "ip_wput_end: q %p (%S)", q, "end");
18812 
18813 	/*
18814 	 * Check if the ire has the RTF_MULTIRT flag, inherited
18815 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
18816 	 */
18817 	if (ire->ire_flags & RTF_MULTIRT) {
18818 		/*
18819 		 * Force the TTL of multirouted packets if required.
18820 		 * The TTL of such packets is bounded by the
18821 		 * ip_multirt_ttl ndd variable.
18822 		 */
18823 		if ((ip_multirt_ttl > 0) &&
18824 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
18825 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
18826 			    "(was %d), dst 0x%08x\n",
18827 			    ip_multirt_ttl, ipha->ipha_ttl,
18828 			    ntohl(ire->ire_addr)));
18829 			ipha->ipha_ttl = ip_multirt_ttl;
18830 		}
18831 		/*
18832 		 * At this point, we check to see if there are any pending
18833 		 * unresolved routes. ire_multirt_resolvable()
18834 		 * checks in O(n) that all IRE_OFFSUBNET ire
18835 		 * entries for the packet's destination and
18836 		 * flagged RTF_MULTIRT are currently resolved.
18837 		 * If some remain unresolved, we make a copy
18838 		 * of the current message. It will be used
18839 		 * to initiate additional route resolutions.
18840 		 */
18841 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr);
18842 		ip2dbg(("ip_wput[noirefound]: ire %p, "
18843 		    "multirt_need_resolve %d, first_mp %p\n",
18844 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
18845 		if (multirt_need_resolve) {
18846 			copy_mp = copymsg(first_mp);
18847 			if (copy_mp != NULL) {
18848 				MULTIRT_DEBUG_TAG(copy_mp);
18849 			}
18850 		}
18851 	}
18852 
18853 	ip_wput_ire(q, first_mp, ire, connp, caller);
18854 	/*
18855 	 * Try to resolve another multiroute if
18856 	 * ire_multirt_resolvable() deemed it necessary.
18857 	 * At this point, we need to distinguish
18858 	 * multicasts from other packets. For multicasts,
18859 	 * we call ip_newroute_ipif() and request that both
18860 	 * multirouting and setsrc flags are checked.
18861 	 */
18862 	if (copy_mp != NULL) {
18863 		if (CLASSD(dst)) {
18864 			ipif_t *ipif = ipif_lookup_group(dst, zoneid);
18865 			if (ipif) {
18866 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
18867 				    RTF_SETSRC | RTF_MULTIRT);
18868 				ipif_refrele(ipif);
18869 			} else {
18870 				MULTIRT_DEBUG_UNTAG(copy_mp);
18871 				freemsg(copy_mp);
18872 				copy_mp = NULL;
18873 			}
18874 		} else {
18875 			ip_newroute(q, copy_mp, dst, NULL, connp);
18876 		}
18877 	}
18878 	if (attach_ill != NULL)
18879 		ill_refrele(attach_ill);
18880 	if (xmit_ill != NULL)
18881 		ill_refrele(xmit_ill);
18882 	if (need_decref)
18883 		CONN_DEC_REF(connp);
18884 	return;
18885 
18886 drop_pkt:
18887 	ip1dbg(("ip_wput: dropped packet\n"));
18888 	if (ire != NULL)
18889 		ire_refrele(ire);
18890 	if (need_decref)
18891 		CONN_DEC_REF(connp);
18892 	freemsg(first_mp);
18893 	if (attach_ill != NULL)
18894 		ill_refrele(attach_ill);
18895 	if (xmit_ill != NULL)
18896 		ill_refrele(xmit_ill);
18897 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18898 	    "ip_wput_end: q %p (%S)", q, "droppkt");
18899 }
18900 
18901 void
18902 ip_wput(queue_t *q, mblk_t *mp)
18903 {
18904 	ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
18905 }
18906 
18907 /*
18908  *
18909  * The following rules must be observed when accessing any ipif or ill
18910  * that has been cached in the conn. Typically conn_nofailover_ill,
18911  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
18912  *
18913  * Access: The ipif or ill pointed to from the conn can be accessed under
18914  * the protection of the conn_lock or after it has been refheld under the
18915  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
18916  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
18917  * The reason for this is that a concurrent unplumb could actually be
18918  * cleaning up these cached pointers by walking the conns and might have
18919  * finished cleaning up the conn in question. The macros check that an
18920  * unplumb has not yet started on the ipif or ill.
18921  *
18922  * Caching: An ipif or ill pointer may be cached in the conn only after
18923  * making sure that an unplumb has not started. So the caching is done
18924  * while holding both the conn_lock and the ill_lock and after using the
18925  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
18926  * flag before starting the cleanup of conns.
18927  *
18928  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
18929  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
18930  * or a reference to the ipif or a reference to an ire that references the
18931  * ipif. An ipif does not change its ill except for failover/failback. Since
18932  * failover/failback happens only after bringing down the ipif and making sure
18933  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
18934  * the above holds.
18935  */
18936 static ipif_t *
18937 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
18938 {
18939 	ipif_t	*ipif;
18940 	ill_t	*ill;
18941 
18942 	*err = 0;
18943 	rw_enter(&ill_g_lock, RW_READER);
18944 	mutex_enter(&connp->conn_lock);
18945 	ipif = *ipifp;
18946 	if (ipif != NULL) {
18947 		ill = ipif->ipif_ill;
18948 		mutex_enter(&ill->ill_lock);
18949 		if (IPIF_CAN_LOOKUP(ipif)) {
18950 			ipif_refhold_locked(ipif);
18951 			mutex_exit(&ill->ill_lock);
18952 			mutex_exit(&connp->conn_lock);
18953 			rw_exit(&ill_g_lock);
18954 			return (ipif);
18955 		} else {
18956 			*err = IPIF_LOOKUP_FAILED;
18957 		}
18958 		mutex_exit(&ill->ill_lock);
18959 	}
18960 	mutex_exit(&connp->conn_lock);
18961 	rw_exit(&ill_g_lock);
18962 	return (NULL);
18963 }
18964 
18965 ill_t *
18966 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
18967 {
18968 	ill_t	*ill;
18969 
18970 	*err = 0;
18971 	mutex_enter(&connp->conn_lock);
18972 	ill = *illp;
18973 	if (ill != NULL) {
18974 		mutex_enter(&ill->ill_lock);
18975 		if (ILL_CAN_LOOKUP(ill)) {
18976 			ill_refhold_locked(ill);
18977 			mutex_exit(&ill->ill_lock);
18978 			mutex_exit(&connp->conn_lock);
18979 			return (ill);
18980 		} else {
18981 			*err = ILL_LOOKUP_FAILED;
18982 		}
18983 		mutex_exit(&ill->ill_lock);
18984 	}
18985 	mutex_exit(&connp->conn_lock);
18986 	return (NULL);
18987 }
18988 
18989 static int
18990 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
18991 {
18992 	ill_t	*ill;
18993 
18994 	ill = ipif->ipif_ill;
18995 	mutex_enter(&connp->conn_lock);
18996 	mutex_enter(&ill->ill_lock);
18997 	if (IPIF_CAN_LOOKUP(ipif)) {
18998 		*ipifp = ipif;
18999 		mutex_exit(&ill->ill_lock);
19000 		mutex_exit(&connp->conn_lock);
19001 		return (0);
19002 	}
19003 	mutex_exit(&ill->ill_lock);
19004 	mutex_exit(&connp->conn_lock);
19005 	return (IPIF_LOOKUP_FAILED);
19006 }
19007 
19008 /*
19009  * This is called if the outbound datagram needs fragmentation.
19010  *
19011  * NOTE : This function does not ire_refrele the ire argument passed in.
19012  */
19013 static void
19014 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire)
19015 {
19016 	ipha_t		*ipha;
19017 	mblk_t		*mp;
19018 	uint32_t	v_hlen_tos_len;
19019 	uint32_t	max_frag;
19020 	uint32_t	frag_flag;
19021 	boolean_t	dont_use;
19022 
19023 	if (ipsec_mp->b_datap->db_type == M_CTL) {
19024 		mp = ipsec_mp->b_cont;
19025 	} else {
19026 		mp = ipsec_mp;
19027 	}
19028 
19029 	ipha = (ipha_t *)mp->b_rptr;
19030 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19031 
19032 #ifdef	_BIG_ENDIAN
19033 #define	V_HLEN	(v_hlen_tos_len >> 24)
19034 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
19035 #else
19036 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19037 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
19038 #endif
19039 
19040 #ifndef SPEED_BEFORE_SAFETY
19041 	/*
19042 	 * Check that ipha_length is consistent with
19043 	 * the mblk length
19044 	 */
19045 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
19046 		ip0dbg(("Packet length mismatch: %d, %ld\n",
19047 		    LENGTH, msgdsize(mp)));
19048 		freemsg(ipsec_mp);
19049 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
19050 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
19051 		    "packet length mismatch");
19052 		return;
19053 	}
19054 #endif
19055 	/*
19056 	 * Don't use frag_flag if pre-built packet or source
19057 	 * routed or if multicast (since multicast packets do not solicit
19058 	 * ICMP "packet too big" messages). Get the values of
19059 	 * max_frag and frag_flag atomically by acquiring the
19060 	 * ire_lock.
19061 	 */
19062 	mutex_enter(&ire->ire_lock);
19063 	max_frag = ire->ire_max_frag;
19064 	frag_flag = ire->ire_frag_flag;
19065 	mutex_exit(&ire->ire_lock);
19066 
19067 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
19068 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
19069 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
19070 
19071 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
19072 	    (dont_use ? 0 : frag_flag));
19073 }
19074 
19075 /*
19076  * Used for deciding the MSS size for the upper layer. Thus
19077  * we need to check the outbound policy values in the conn.
19078  */
19079 int
19080 conn_ipsec_length(conn_t *connp)
19081 {
19082 	ipsec_latch_t *ipl;
19083 
19084 	ipl = connp->conn_latch;
19085 	if (ipl == NULL)
19086 		return (0);
19087 
19088 	if (ipl->ipl_out_policy == NULL)
19089 		return (0);
19090 
19091 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
19092 }
19093 
19094 /*
19095  * Returns an estimate of the IPSEC headers size. This is used if
19096  * we don't want to call into IPSEC to get the exact size.
19097  */
19098 int
19099 ipsec_out_extra_length(mblk_t *ipsec_mp)
19100 {
19101 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
19102 	ipsec_action_t *a;
19103 
19104 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
19105 	if (!io->ipsec_out_secure)
19106 		return (0);
19107 
19108 	a = io->ipsec_out_act;
19109 
19110 	if (a == NULL) {
19111 		ASSERT(io->ipsec_out_policy != NULL);
19112 		a = io->ipsec_out_policy->ipsp_act;
19113 	}
19114 	ASSERT(a != NULL);
19115 
19116 	return (a->ipa_ovhd);
19117 }
19118 
19119 /*
19120  * Returns an estimate of the IPSEC headers size. This is used if
19121  * we don't want to call into IPSEC to get the exact size.
19122  */
19123 int
19124 ipsec_in_extra_length(mblk_t *ipsec_mp)
19125 {
19126 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
19127 	ipsec_action_t *a;
19128 
19129 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
19130 
19131 	a = ii->ipsec_in_action;
19132 	return (a == NULL ? 0 : a->ipa_ovhd);
19133 }
19134 
19135 /*
19136  * If there are any source route options, return the true final
19137  * destination. Otherwise, return the destination.
19138  */
19139 ipaddr_t
19140 ip_get_dst(ipha_t *ipha)
19141 {
19142 	ipoptp_t	opts;
19143 	uchar_t		*opt;
19144 	uint8_t		optval;
19145 	uint8_t		optlen;
19146 	ipaddr_t	dst;
19147 	uint32_t off;
19148 
19149 	dst = ipha->ipha_dst;
19150 
19151 	if (IS_SIMPLE_IPH(ipha))
19152 		return (dst);
19153 
19154 	for (optval = ipoptp_first(&opts, ipha);
19155 	    optval != IPOPT_EOL;
19156 	    optval = ipoptp_next(&opts)) {
19157 		opt = opts.ipoptp_cur;
19158 		optlen = opts.ipoptp_len;
19159 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19160 		switch (optval) {
19161 		case IPOPT_SSRR:
19162 		case IPOPT_LSRR:
19163 			off = opt[IPOPT_OFFSET];
19164 			/*
19165 			 * If one of the conditions is true, it means
19166 			 * end of options and dst already has the right
19167 			 * value.
19168 			 */
19169 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
19170 				off = optlen - IP_ADDR_LEN;
19171 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
19172 			}
19173 			return (dst);
19174 		default:
19175 			break;
19176 		}
19177 	}
19178 
19179 	return (dst);
19180 }
19181 
19182 mblk_t *
19183 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
19184     conn_t *connp, boolean_t unspec_src)
19185 {
19186 	ipsec_out_t	*io;
19187 	mblk_t		*first_mp;
19188 	boolean_t policy_present;
19189 
19190 	first_mp = mp;
19191 	if (mp->b_datap->db_type == M_CTL) {
19192 		io = (ipsec_out_t *)first_mp->b_rptr;
19193 		/*
19194 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
19195 		 *
19196 		 * 1) There is per-socket policy (including cached global
19197 		 *    policy).
19198 		 * 2) There is no per-socket policy, but it is
19199 		 *    a multicast packet that needs to go out
19200 		 *    on a specific interface. This is the case
19201 		 *    where (ip_wput and ip_wput_multicast) attaches
19202 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
19203 		 *
19204 		 * In case (2) we check with global policy to
19205 		 * see if there is a match and set the ill_index
19206 		 * appropriately so that we can lookup the ire
19207 		 * properly in ip_wput_ipsec_out.
19208 		 */
19209 
19210 		/*
19211 		 * ipsec_out_use_global_policy is set to B_FALSE
19212 		 * in ipsec_in_to_out(). Refer to that function for
19213 		 * details.
19214 		 */
19215 		if ((io->ipsec_out_latch == NULL) &&
19216 		    (io->ipsec_out_use_global_policy)) {
19217 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
19218 			    ire, connp, unspec_src));
19219 		}
19220 		if (!io->ipsec_out_secure) {
19221 			/*
19222 			 * If this is not a secure packet, drop
19223 			 * the IPSEC_OUT mp and treat it as a clear
19224 			 * packet. This happens when we are sending
19225 			 * a ICMP reply back to a clear packet. See
19226 			 * ipsec_in_to_out() for details.
19227 			 */
19228 			mp = first_mp->b_cont;
19229 			freeb(first_mp);
19230 		}
19231 		return (mp);
19232 	}
19233 	/*
19234 	 * See whether we need to attach a global policy here. We
19235 	 * don't depend on the conn (as it could be null) for deciding
19236 	 * what policy this datagram should go through because it
19237 	 * should have happened in ip_wput if there was some
19238 	 * policy. This normally happens for connections which are not
19239 	 * fully bound preventing us from caching policies in
19240 	 * ip_bind. Packets coming from the TCP listener/global queue
19241 	 * - which are non-hard_bound - could also be affected by
19242 	 * applying policy here.
19243 	 *
19244 	 * If this packet is coming from tcp global queue or listener,
19245 	 * we will be applying policy here.  This may not be *right*
19246 	 * if these packets are coming from the detached connection as
19247 	 * it could have gone in clear before. This happens only if a
19248 	 * TCP connection started when there is no policy and somebody
19249 	 * added policy before it became detached. Thus packets of the
19250 	 * detached connection could go out secure and the other end
19251 	 * would drop it because it will be expecting in clear. The
19252 	 * converse is not true i.e if somebody starts a TCP
19253 	 * connection and deletes the policy, all the packets will
19254 	 * still go out with the policy that existed before deleting
19255 	 * because ip_unbind sends up policy information which is used
19256 	 * by TCP on subsequent ip_wputs. The right solution is to fix
19257 	 * TCP to attach a dummy IPSEC_OUT and set
19258 	 * ipsec_out_use_global_policy to B_FALSE. As this might
19259 	 * affect performance for normal cases, we are not doing it.
19260 	 * Thus, set policy before starting any TCP connections.
19261 	 *
19262 	 * NOTE - We might apply policy even for a hard bound connection
19263 	 * - for which we cached policy in ip_bind - if somebody added
19264 	 * global policy after we inherited the policy in ip_bind.
19265 	 * This means that the packets that were going out in clear
19266 	 * previously would start going secure and hence get dropped
19267 	 * on the other side. To fix this, TCP attaches a dummy
19268 	 * ipsec_out and make sure that we don't apply global policy.
19269 	 */
19270 	if (ipha != NULL)
19271 		policy_present = ipsec_outbound_v4_policy_present;
19272 	else
19273 		policy_present = ipsec_outbound_v6_policy_present;
19274 	if (!policy_present)
19275 		return (mp);
19276 
19277 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src));
19278 }
19279 
19280 ire_t *
19281 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
19282 {
19283 	ipaddr_t addr;
19284 	ire_t *save_ire;
19285 	irb_t *irb;
19286 	ill_group_t *illgrp;
19287 	int	err;
19288 
19289 	save_ire = ire;
19290 	addr = ire->ire_addr;
19291 
19292 	ASSERT(ire->ire_type == IRE_BROADCAST);
19293 
19294 	illgrp = connp->conn_outgoing_ill->ill_group;
19295 	if (illgrp == NULL) {
19296 		*conn_outgoing_ill = conn_get_held_ill(connp,
19297 		    &connp->conn_outgoing_ill, &err);
19298 		if (err == ILL_LOOKUP_FAILED) {
19299 			ire_refrele(save_ire);
19300 			return (NULL);
19301 		}
19302 		return (save_ire);
19303 	}
19304 	/*
19305 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
19306 	 * If it is part of the group, we need to send on the ire
19307 	 * that has been cleared of IRE_MARK_NORECV and that belongs
19308 	 * to this group. This is okay as IP_BOUND_IF really means
19309 	 * any ill in the group. We depend on the fact that the
19310 	 * first ire in the group is always cleared of IRE_MARK_NORECV
19311 	 * if such an ire exists. This is possible only if you have
19312 	 * at least one ill in the group that has not failed.
19313 	 *
19314 	 * First get to the ire that matches the address and group.
19315 	 *
19316 	 * We don't look for an ire with a matching zoneid because a given zone
19317 	 * won't always have broadcast ires on all ills in the group.
19318 	 */
19319 	irb = ire->ire_bucket;
19320 	rw_enter(&irb->irb_lock, RW_READER);
19321 	if (ire->ire_marks & IRE_MARK_NORECV) {
19322 		/*
19323 		 * If the current zone only has an ire broadcast for this
19324 		 * address marked NORECV, the ire we want is ahead in the
19325 		 * bucket, so we look it up deliberately ignoring the zoneid.
19326 		 */
19327 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
19328 			if (ire->ire_addr != addr)
19329 				continue;
19330 			/* skip over deleted ires */
19331 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
19332 				continue;
19333 		}
19334 	}
19335 	while (ire != NULL) {
19336 		/*
19337 		 * If a new interface is coming up, we could end up
19338 		 * seeing the loopback ire and the non-loopback ire
19339 		 * may not have been added yet. So check for ire_stq
19340 		 */
19341 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
19342 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
19343 			break;
19344 		}
19345 		ire = ire->ire_next;
19346 	}
19347 	if (ire != NULL && ire->ire_addr == addr &&
19348 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
19349 		IRE_REFHOLD(ire);
19350 		rw_exit(&irb->irb_lock);
19351 		ire_refrele(save_ire);
19352 		*conn_outgoing_ill = ire_to_ill(ire);
19353 		/*
19354 		 * Refhold the ill to make the conn_outgoing_ill
19355 		 * independent of the ire. ip_wput_ire goes in a loop
19356 		 * and may refrele the ire. Since we have an ire at this
19357 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
19358 		 */
19359 		ill_refhold(*conn_outgoing_ill);
19360 		return (ire);
19361 	}
19362 	rw_exit(&irb->irb_lock);
19363 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
19364 	/*
19365 	 * If we can't find a suitable ire, return the original ire.
19366 	 */
19367 	return (save_ire);
19368 }
19369 
19370 /*
19371  * This function does the ire_refrele of the ire passed in as the
19372  * argument. As this function looks up more ires i.e broadcast ires,
19373  * it needs to REFRELE them. Currently, for simplicity we don't
19374  * differentiate the one passed in and looked up here. We always
19375  * REFRELE.
19376  * IPQoS Notes:
19377  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
19378  * IPSec packets are done in ipsec_out_process.
19379  *
19380  */
19381 void
19382 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller)
19383 {
19384 	ipha_t		*ipha;
19385 #define	rptr	((uchar_t *)ipha)
19386 	mblk_t		*mp1;
19387 	queue_t		*stq;
19388 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
19389 	uint32_t	v_hlen_tos_len;
19390 	uint32_t	ttl_protocol;
19391 	ipaddr_t	src;
19392 	ipaddr_t	dst;
19393 	uint32_t	cksum;
19394 	ipaddr_t	orig_src;
19395 	ire_t		*ire1;
19396 	mblk_t		*next_mp;
19397 	uint_t		hlen;
19398 	uint16_t	*up;
19399 	uint32_t	max_frag = ire->ire_max_frag;
19400 	ill_t		*ill = ire_to_ill(ire);
19401 	int		clusterwide;
19402 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
19403 	int		ipsec_len;
19404 	mblk_t		*first_mp;
19405 	ipsec_out_t	*io;
19406 	boolean_t	conn_dontroute;		/* conn value for multicast */
19407 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
19408 	boolean_t	multicast_forward;	/* Should we forward ? */
19409 	boolean_t	unspec_src;
19410 	ill_t		*conn_outgoing_ill = NULL;
19411 	ill_t		*ire_ill;
19412 	ill_t		*ire1_ill;
19413 	uint32_t 	ill_index = 0;
19414 	boolean_t	multirt_send = B_FALSE;
19415 	int		err;
19416 	zoneid_t	zoneid;
19417 	boolean_t	iphdrhwcksum = B_FALSE;
19418 
19419 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
19420 	    "ip_wput_ire_start: q %p", q);
19421 
19422 	multicast_forward = B_FALSE;
19423 	unspec_src = (connp != NULL && connp->conn_unspec_src);
19424 
19425 	if (ire->ire_flags & RTF_MULTIRT) {
19426 		/*
19427 		 * Multirouting case. The bucket where ire is stored
19428 		 * probably holds other RTF_MULTIRT flagged ire
19429 		 * to the destination. In this call to ip_wput_ire,
19430 		 * we attempt to send the packet through all
19431 		 * those ires. Thus, we first ensure that ire is the
19432 		 * first RTF_MULTIRT ire in the bucket,
19433 		 * before walking the ire list.
19434 		 */
19435 		ire_t *first_ire;
19436 		irb_t *irb = ire->ire_bucket;
19437 		ASSERT(irb != NULL);
19438 
19439 		/* Make sure we do not omit any multiroute ire. */
19440 		IRB_REFHOLD(irb);
19441 		for (first_ire = irb->irb_ire;
19442 		    first_ire != NULL;
19443 		    first_ire = first_ire->ire_next) {
19444 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
19445 			    (first_ire->ire_addr == ire->ire_addr) &&
19446 			    !(first_ire->ire_marks &
19447 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
19448 				break;
19449 		}
19450 
19451 		if ((first_ire != NULL) && (first_ire != ire)) {
19452 			IRE_REFHOLD(first_ire);
19453 			ire_refrele(ire);
19454 			ire = first_ire;
19455 			ill = ire_to_ill(ire);
19456 		}
19457 		IRB_REFRELE(irb);
19458 	}
19459 
19460 	/*
19461 	 * conn_outgoing_ill is used only in the broadcast loop.
19462 	 * for performance we don't grab the mutexs in the fastpath
19463 	 */
19464 	if ((connp != NULL) &&
19465 	    (connp->conn_xmit_if_ill == NULL) &&
19466 	    (ire->ire_type == IRE_BROADCAST) &&
19467 	    ((connp->conn_nofailover_ill != NULL) ||
19468 	    (connp->conn_outgoing_ill != NULL))) {
19469 		/*
19470 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
19471 		 * option. So, see if this endpoint is bound to a
19472 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
19473 		 * that if the interface is failed, we will still send
19474 		 * the packet on the same ill which is what we want.
19475 		 */
19476 		conn_outgoing_ill = conn_get_held_ill(connp,
19477 		    &connp->conn_nofailover_ill, &err);
19478 		if (err == ILL_LOOKUP_FAILED) {
19479 			ire_refrele(ire);
19480 			freemsg(mp);
19481 			return;
19482 		}
19483 		if (conn_outgoing_ill == NULL) {
19484 			/*
19485 			 * Choose a good ill in the group to send the
19486 			 * packets on.
19487 			 */
19488 			ire = conn_set_outgoing_ill(connp, ire,
19489 			    &conn_outgoing_ill);
19490 			if (ire == NULL) {
19491 				freemsg(mp);
19492 				return;
19493 			}
19494 		}
19495 	}
19496 
19497 	if (mp->b_datap->db_type != M_CTL) {
19498 		ipha = (ipha_t *)mp->b_rptr;
19499 		zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
19500 	} else {
19501 		io = (ipsec_out_t *)mp->b_rptr;
19502 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
19503 		zoneid = io->ipsec_out_zoneid;
19504 		ASSERT(zoneid != ALL_ZONES);
19505 		ipha = (ipha_t *)mp->b_cont->b_rptr;
19506 		dst = ipha->ipha_dst;
19507 		/*
19508 		 * For the multicast case, ipsec_out carries conn_dontroute and
19509 		 * conn_multicast_loop as conn may not be available here. We
19510 		 * need this for multicast loopback and forwarding which is done
19511 		 * later in the code.
19512 		 */
19513 		if (CLASSD(dst)) {
19514 			conn_dontroute = io->ipsec_out_dontroute;
19515 			conn_multicast_loop = io->ipsec_out_multicast_loop;
19516 			/*
19517 			 * If conn_dontroute is not set or conn_multicast_loop
19518 			 * is set, we need to do forwarding/loopback. For
19519 			 * datagrams from ip_wput_multicast, conn_dontroute is
19520 			 * set to B_TRUE and conn_multicast_loop is set to
19521 			 * B_FALSE so that we neither do forwarding nor
19522 			 * loopback.
19523 			 */
19524 			if (!conn_dontroute || conn_multicast_loop)
19525 				multicast_forward = B_TRUE;
19526 		}
19527 	}
19528 
19529 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid) {
19530 		/*
19531 		 * When a zone sends a packet to another zone, we try to deliver
19532 		 * the packet under the same conditions as if the destination
19533 		 * was a real node on the network. To do so, we look for a
19534 		 * matching route in the forwarding table.
19535 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
19536 		 * ip_newroute() does.
19537 		 */
19538 		ire_t *src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
19539 		    NULL, NULL, zoneid, 0, (MATCH_IRE_RECURSIVE |
19540 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE));
19541 		if (src_ire != NULL &&
19542 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))) {
19543 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
19544 				ipha->ipha_src = src_ire->ire_src_addr;
19545 			ire_refrele(src_ire);
19546 		} else {
19547 			ire_refrele(ire);
19548 			if (conn_outgoing_ill != NULL)
19549 				ill_refrele(conn_outgoing_ill);
19550 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
19551 			if (src_ire != NULL) {
19552 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
19553 					ire_refrele(src_ire);
19554 					freemsg(mp);
19555 					return;
19556 				}
19557 				ire_refrele(src_ire);
19558 			}
19559 			if (ip_hdr_complete(ipha, zoneid)) {
19560 				/* Failed */
19561 				freemsg(mp);
19562 				return;
19563 			}
19564 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE);
19565 			return;
19566 		}
19567 	}
19568 
19569 	if (mp->b_datap->db_type == M_CTL ||
19570 	    ipsec_outbound_v4_policy_present) {
19571 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
19572 		    unspec_src);
19573 		if (mp == NULL) {
19574 			ire_refrele(ire);
19575 			if (conn_outgoing_ill != NULL)
19576 				ill_refrele(conn_outgoing_ill);
19577 			return;
19578 		}
19579 	}
19580 
19581 	first_mp = mp;
19582 	ipsec_len = 0;
19583 
19584 	if (first_mp->b_datap->db_type == M_CTL) {
19585 		io = (ipsec_out_t *)first_mp->b_rptr;
19586 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
19587 		mp = first_mp->b_cont;
19588 		ipsec_len = ipsec_out_extra_length(first_mp);
19589 		ASSERT(ipsec_len >= 0);
19590 		zoneid = io->ipsec_out_zoneid;
19591 		ASSERT(zoneid != ALL_ZONES);
19592 
19593 		/*
19594 		 * Drop M_CTL here if IPsec processing is not needed.
19595 		 * (Non-IPsec use of M_CTL extracted any information it
19596 		 * needed above).
19597 		 */
19598 		if (ipsec_len == 0) {
19599 			freeb(first_mp);
19600 			first_mp = mp;
19601 		}
19602 	}
19603 
19604 	/*
19605 	 * Fast path for ip_wput_ire
19606 	 */
19607 
19608 	ipha = (ipha_t *)mp->b_rptr;
19609 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19610 	dst = ipha->ipha_dst;
19611 
19612 	/*
19613 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
19614 	 * if the socket is a SOCK_RAW type. The transport checksum should
19615 	 * be provided in the pre-built packet, so we don't need to compute it.
19616 	 * Also, other application set flags, like DF, should not be altered.
19617 	 * Other transport MUST pass down zero.
19618 	 */
19619 	ip_hdr_included = ipha->ipha_ident;
19620 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
19621 
19622 	if (CLASSD(dst)) {
19623 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
19624 		    ntohl(dst),
19625 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
19626 		    ntohl(ire->ire_addr)));
19627 	}
19628 
19629 /* Macros to extract header fields from data already in registers */
19630 #ifdef	_BIG_ENDIAN
19631 #define	V_HLEN	(v_hlen_tos_len >> 24)
19632 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
19633 #define	PROTO	(ttl_protocol & 0xFF)
19634 #else
19635 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19636 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
19637 #define	PROTO	(ttl_protocol >> 8)
19638 #endif
19639 
19640 
19641 	orig_src = src = ipha->ipha_src;
19642 	/* (The loop back to "another" is explained down below.) */
19643 another:;
19644 	/*
19645 	 * Assign an ident value for this packet.  We assign idents on
19646 	 * a per destination basis out of the IRE.  There could be
19647 	 * other threads targeting the same destination, so we have to
19648 	 * arrange for a atomic increment.  Note that we use a 32-bit
19649 	 * atomic add because it has better performance than its
19650 	 * 16-bit sibling.
19651 	 *
19652 	 * If running in cluster mode and if the source address
19653 	 * belongs to a replicated service then vector through
19654 	 * cl_inet_ipident vector to allocate ip identifier
19655 	 * NOTE: This is a contract private interface with the
19656 	 * clustering group.
19657 	 */
19658 	clusterwide = 0;
19659 	if (cl_inet_ipident) {
19660 		ASSERT(cl_inet_isclusterwide);
19661 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
19662 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
19663 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
19664 			    AF_INET, (uint8_t *)(uintptr_t)src,
19665 			    (uint8_t *)(uintptr_t)dst);
19666 			clusterwide = 1;
19667 		}
19668 	}
19669 	if (!clusterwide) {
19670 		ipha->ipha_ident =
19671 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
19672 	}
19673 
19674 #ifndef _BIG_ENDIAN
19675 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
19676 #endif
19677 
19678 	/*
19679 	 * Set source address unless sent on an ill or conn_unspec_src is set.
19680 	 * This is needed to obey conn_unspec_src when packets go through
19681 	 * ip_newroute + arp.
19682 	 * Assumes ip_newroute{,_multi} sets the source address as well.
19683 	 */
19684 	if (src == INADDR_ANY && !unspec_src) {
19685 		/*
19686 		 * Assign the appropriate source address from the IRE if none
19687 		 * was specified.
19688 		 */
19689 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
19690 
19691 		/*
19692 		 * With IP multipathing, broadcast packets are sent on the ire
19693 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
19694 		 * the group. However, this ire might not be in the same zone so
19695 		 * we can't always use its source address. We look for a
19696 		 * broadcast ire in the same group and in the right zone.
19697 		 */
19698 		if (ire->ire_type == IRE_BROADCAST &&
19699 		    ire->ire_zoneid != zoneid) {
19700 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
19701 			    IRE_BROADCAST, ire->ire_ipif, zoneid,
19702 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
19703 			if (src_ire != NULL) {
19704 				src = src_ire->ire_src_addr;
19705 				ire_refrele(src_ire);
19706 			} else {
19707 				ire_refrele(ire);
19708 				if (conn_outgoing_ill != NULL)
19709 					ill_refrele(conn_outgoing_ill);
19710 				freemsg(first_mp);
19711 				BUMP_MIB(&ip_mib, ipOutDiscards);
19712 				return;
19713 			}
19714 		} else {
19715 			src = ire->ire_src_addr;
19716 		}
19717 
19718 		if (connp == NULL) {
19719 			ip1dbg(("ip_wput_ire: no connp and no src "
19720 			    "address for dst 0x%x, using src 0x%x\n",
19721 			    ntohl(dst),
19722 			    ntohl(src)));
19723 		}
19724 		ipha->ipha_src = src;
19725 	}
19726 	stq = ire->ire_stq;
19727 
19728 	/*
19729 	 * We only allow ire chains for broadcasts since there will
19730 	 * be multiple IRE_CACHE entries for the same multicast
19731 	 * address (one per ipif).
19732 	 */
19733 	next_mp = NULL;
19734 
19735 	/* broadcast packet */
19736 	if (ire->ire_type == IRE_BROADCAST)
19737 		goto broadcast;
19738 
19739 	/* loopback ? */
19740 	if (stq == NULL)
19741 		goto nullstq;
19742 
19743 	/* The ill_index for outbound ILL */
19744 	ill_index = Q_TO_INDEX(stq);
19745 
19746 	BUMP_MIB(&ip_mib, ipOutRequests);
19747 	ttl_protocol = ((uint16_t *)ipha)[4];
19748 
19749 	/* pseudo checksum (do it in parts for IP header checksum) */
19750 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
19751 
19752 #define	FRAGMENT_NEEDED(mtu, size)	\
19753 	(((mtu) < (unsigned int)(size)) ? B_TRUE : B_FALSE)
19754 
19755 #define	IS_FASTPATH(ire, bp) 					\
19756 	((ire)->ire_fp_mp != NULL &&				\
19757 	(MBLKHEAD((bp)) >= (MBLKL((ire)->ire_fp_mp))))		\
19758 
19759 #define	IPH_UDPH_CHECKSUMP(ipha, hlen) \
19760 	((uint16_t *)(((uchar_t *)ipha)+(hlen + UDP_CHECKSUM_OFFSET)))
19761 #define	IPH_TCPH_CHECKSUMP(ipha, hlen) \
19762 	    ((uint16_t *)(((uchar_t *)ipha)+(hlen+TCP_CHECKSUM_OFFSET)))
19763 
19764 #define	IP_CKSUM_XMIT(ill, ire, mp, up, proto, hlen, max_frag,		\
19765 	    ipsec_len) { 						\
19766 	uint32_t	sum;						\
19767 	uint32_t	xmit_capab = HCKSUM_INET_FULL_V4 |		\
19768 			    HCKSUM_INET_PARTIAL | HCKSUM_IPHDRCKSUM;	\
19769 	boolean_t	cksum_offload = B_FALSE;			\
19770 									\
19771 	/*								\
19772 	 * The ire fp mp can change due to the arrival of a		\
19773 	 * DL_NOTE_FASTPATH_FLUSH in the case of IRE_BROADCAST		\
19774 	 * and IRE_MIPRTUN. Hence the ire_fp_mp has to be accessed	\
19775 	 * only under the ire_lock in such cases.			\
19776 	 */								\
19777 	LOCK_IRE_FP_MP(ire);						\
19778 	if ((ill) && (ill->ill_capabilities & ILL_CAPAB_HCKSUM) &&	\
19779 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &		\
19780 	    xmit_capab) && (!FRAGMENT_NEEDED(max_frag, 			\
19781 	    (LENGTH + ipsec_len))) && (!(ire->ire_flags & 		\
19782 	    RTF_MULTIRT)) && (ipsec_len == 0) && 			\
19783 	    IS_FASTPATH((ire), (mp)) &&	(dohwcksum)) { 			\
19784 		/*							\
19785 		 * Underlying interface supports hardware checksumming.	\
19786 		 * So postpone the checksum to the interface driver	\
19787 		 */							\
19788 									\
19789 		if ((hlen) == IP_SIMPLE_HDR_LENGTH) {			       \
19790 			if (ill->ill_hcksum_capab->ill_hcksum_txflags &        \
19791 			    HCKSUM_IPHDRCKSUM) {			       \
19792 				mp->b_datap->db_struioun.cksum.flags |=	       \
19793 				    HCK_IPV4_HDRCKSUM;			       \
19794 				/* seed the cksum field to 0 */		       \
19795 				ipha->ipha_hdr_checksum = 0;		       \
19796 				iphdrhwcksum = B_TRUE;			       \
19797 			}						       \
19798 			/*						       \
19799 			 * If underlying h/w supports full h/w checksumming    \
19800 			 * and no IP options are present, then offload	       \
19801 			 * full checksumming to the hardware.		       \
19802 			 *						       \
19803 			 * If h/w can do partial checksumming then offload     \
19804 			 * unless the startpoint offset, including mac-header, \
19805 			 * is too big for the interface to some of our	       \
19806 			 * hardware (CE and ERI) which have 6 bit fields.      \
19807 			 * Sigh.					       \
19808 			 * Unhappily we don't have the mac-header size here    \
19809 			 * so punt for any options.			       \
19810 			 */						       \
19811 			if (ill->ill_hcksum_capab->ill_hcksum_txflags &        \
19812 			    HCKSUM_INET_FULL_V4) {			       \
19813 				UNLOCK_IRE_FP_MP(ire);			       \
19814 				/* Seed the checksum field to 0 */	       \
19815 				*up = 0;				       \
19816 				mp->b_datap->db_struioun.cksum.flags |=	       \
19817 				    HCK_FULLCKSUM;			       \
19818 				cksum_offload = B_TRUE;			       \
19819 			} else if (ill->ill_hcksum_capab->ill_hcksum_txflags & \
19820 			    HCKSUM_INET_PARTIAL) {			       \
19821 				UNLOCK_IRE_FP_MP(ire);			       \
19822 				sum = *up + cksum + proto;		       \
19823 				sum = (sum & 0xFFFF) + (sum >> 16);	       \
19824 				*up = (sum & 0xFFFF) + (sum >> 16);	       \
19825 				/*					       \
19826 				 * All offsets are relative to the beginning   \
19827 				 * of the IP header.			       \
19828 				 */					       \
19829 				mp->b_datap->db_cksumstart = hlen;	       \
19830 				mp->b_datap->db_cksumstuff = 		       \
19831 				    (PROTO == IPPROTO_UDP) ?		       \
19832 				    (hlen) + UDP_CHECKSUM_OFFSET :	       \
19833 				    (hlen) + TCP_CHECKSUM_OFFSET;	       \
19834 				mp->b_datap->db_cksumend = ipha->ipha_length;  \
19835 				mp->b_datap->db_struioun.cksum.flags |=	       \
19836 				    HCK_PARTIALCKSUM;			       \
19837 				cksum_offload = B_TRUE;			       \
19838 			}						       \
19839 		}							\
19840 	} 								\
19841 	if (!cksum_offload) {						\
19842 		UNLOCK_IRE_FP_MP(ire);					\
19843 		IP_STAT(ip_out_sw_cksum);				\
19844 		(sum) = IP_CSUM((mp), (hlen), cksum + proto);		\
19845 		*(up) = (uint16_t)((sum) ? (sum) : ~(sum));		\
19846 	}								\
19847 }
19848 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
19849 		queue_t *dev_q = stq->q_next;
19850 
19851 		/* flow controlled */
19852 		if ((dev_q->q_next || dev_q->q_first) &&
19853 		    !canput(dev_q))
19854 			goto blocked;
19855 		if ((PROTO == IPPROTO_UDP) &&
19856 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
19857 			hlen = (V_HLEN & 0xF) << 2;
19858 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
19859 			if (*up) {
19860 				IP_CKSUM_XMIT(ill, ire, mp, up,
19861 				    IP_UDP_CSUM_COMP, hlen, max_frag,
19862 				    ipsec_len);
19863 			}
19864 		}
19865 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
19866 		hlen = (V_HLEN & 0xF) << 2;
19867 		if (PROTO == IPPROTO_TCP) {
19868 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
19869 			/*
19870 			 * The packet header is processed once and for all, even
19871 			 * in the multirouting case. We disable hardware
19872 			 * checksum if the packet is multirouted, as it will be
19873 			 * replicated via several interfaces, and not all of
19874 			 * them may have this capability.
19875 			 */
19876 			IP_CKSUM_XMIT(ill, ire, mp, up,
19877 			    IP_TCP_CSUM_COMP, hlen, max_frag, ipsec_len);
19878 		} else {
19879 			sctp_hdr_t	*sctph;
19880 
19881 			ASSERT(PROTO == IPPROTO_SCTP);
19882 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
19883 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
19884 			/*
19885 			 * Zero out the checksum field to ensure proper
19886 			 * checksum calculation.
19887 			 */
19888 			sctph->sh_chksum = 0;
19889 #ifdef	DEBUG
19890 			if (!skip_sctp_cksum)
19891 #endif
19892 				sctph->sh_chksum = sctp_cksum(mp, hlen);
19893 		}
19894 	}
19895 
19896 	/*
19897 	 * If this is a multicast packet and originated from ip_wput
19898 	 * we need to do loopback and forwarding checks. If it comes
19899 	 * from ip_wput_multicast, we SHOULD not do this.
19900 	 */
19901 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
19902 
19903 	/* checksum */
19904 	cksum += ttl_protocol;
19905 
19906 	/* fragment the packet */
19907 	if (FRAGMENT_NEEDED(max_frag, (LENGTH + ipsec_len)))
19908 		goto fragmentit;
19909 	/*
19910 	 * Don't use frag_flag if packet is pre-built or source
19911 	 * routed or if multicast (since multicast packets do
19912 	 * not solicit ICMP "packet too big" messages).
19913 	 */
19914 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
19915 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
19916 	    !ip_source_route_included(ipha)) &&
19917 	    !CLASSD(ipha->ipha_dst))
19918 		ipha->ipha_fragment_offset_and_flags |=
19919 		    htons(ire->ire_frag_flag);
19920 
19921 	if (!iphdrhwcksum) {
19922 		/* checksum */
19923 		cksum += ipha->ipha_ident;
19924 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
19925 		cksum += ipha->ipha_fragment_offset_and_flags;
19926 
19927 		/* IP options present */
19928 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
19929 		if (hlen)
19930 			goto checksumoptions;
19931 
19932 		/* calculate hdr checksum */
19933 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
19934 		cksum = ~(cksum + (cksum >> 16));
19935 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
19936 	}
19937 	if (ipsec_len != 0) {
19938 		/*
19939 		 * We will do the rest of the processing after
19940 		 * we come back from IPSEC in ip_wput_ipsec_out().
19941 		 */
19942 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
19943 
19944 		io = (ipsec_out_t *)first_mp->b_rptr;
19945 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
19946 				ill_phyint->phyint_ifindex;
19947 
19948 		ipsec_out_process(q, first_mp, ire, ill_index);
19949 		ire_refrele(ire);
19950 		if (conn_outgoing_ill != NULL)
19951 			ill_refrele(conn_outgoing_ill);
19952 		return;
19953 	}
19954 
19955 	/*
19956 	 * In most cases, the emission loop below is entered only
19957 	 * once. Only in the case where the ire holds the
19958 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
19959 	 * flagged ires in the bucket, and send the packet
19960 	 * through all crossed RTF_MULTIRT routes.
19961 	 */
19962 	if (ire->ire_flags & RTF_MULTIRT) {
19963 		multirt_send = B_TRUE;
19964 	}
19965 	do {
19966 		if (multirt_send) {
19967 			irb_t *irb;
19968 			/*
19969 			 * We are in a multiple send case, need to get
19970 			 * the next ire and make a duplicate of the packet.
19971 			 * ire1 holds here the next ire to process in the
19972 			 * bucket. If multirouting is expected,
19973 			 * any non-RTF_MULTIRT ire that has the
19974 			 * right destination address is ignored.
19975 			 */
19976 			irb = ire->ire_bucket;
19977 			ASSERT(irb != NULL);
19978 
19979 			IRB_REFHOLD(irb);
19980 			for (ire1 = ire->ire_next;
19981 			    ire1 != NULL;
19982 			    ire1 = ire1->ire_next) {
19983 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
19984 					continue;
19985 				if (ire1->ire_addr != ire->ire_addr)
19986 					continue;
19987 				if (ire1->ire_marks &
19988 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
19989 					continue;
19990 
19991 				/* Got one */
19992 				IRE_REFHOLD(ire1);
19993 				break;
19994 			}
19995 			IRB_REFRELE(irb);
19996 
19997 			if (ire1 != NULL) {
19998 				next_mp = copyb(mp);
19999 				if ((next_mp == NULL) ||
20000 				    ((mp->b_cont != NULL) &&
20001 				    ((next_mp->b_cont =
20002 				    dupmsg(mp->b_cont)) == NULL))) {
20003 					freemsg(next_mp);
20004 					next_mp = NULL;
20005 					ire_refrele(ire1);
20006 					ire1 = NULL;
20007 				}
20008 			}
20009 
20010 			/* Last multiroute ire; don't loop anymore. */
20011 			if (ire1 == NULL) {
20012 				multirt_send = B_FALSE;
20013 			}
20014 		}
20015 		mp = ip_wput_attach_llhdr(mp, ire, IPP_LOCAL_OUT, ill_index);
20016 		if (mp == NULL) {
20017 			BUMP_MIB(&ip_mib, ipOutDiscards);
20018 			ip2dbg(("ip_wput_ire: fastpath wput pkt dropped "\
20019 			    "during IPPF processing\n"));
20020 			ire_refrele(ire);
20021 			if (next_mp != NULL) {
20022 				freemsg(next_mp);
20023 				ire_refrele(ire1);
20024 			}
20025 			if (conn_outgoing_ill != NULL)
20026 				ill_refrele(conn_outgoing_ill);
20027 			return;
20028 		}
20029 		UPDATE_OB_PKT_COUNT(ire);
20030 		ire->ire_last_used_time = lbolt;
20031 
20032 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20033 		    "ip_wput_ire_end: q %p (%S)",
20034 		    q, "last copy out");
20035 		putnext(stq, mp);
20036 		IRE_REFRELE(ire);
20037 
20038 		if (multirt_send) {
20039 			ASSERT(ire1);
20040 			/*
20041 			 * Proceed with the next RTF_MULTIRT ire,
20042 			 * Also set up the send-to queue accordingly.
20043 			 */
20044 			ire = ire1;
20045 			ire1 = NULL;
20046 			stq = ire->ire_stq;
20047 			mp = next_mp;
20048 			next_mp = NULL;
20049 			ipha = (ipha_t *)mp->b_rptr;
20050 			ill_index = Q_TO_INDEX(stq);
20051 		}
20052 	} while (multirt_send);
20053 	if (conn_outgoing_ill != NULL)
20054 		ill_refrele(conn_outgoing_ill);
20055 	return;
20056 
20057 	/*
20058 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
20059 	 */
20060 broadcast:
20061 	{
20062 		/*
20063 		 * Avoid broadcast storms by setting the ttl to 1
20064 		 * for broadcasts. This parameter can be set
20065 		 * via ndd, so make sure that for the SO_DONTROUTE
20066 		 * case that ipha_ttl is always set to 1.
20067 		 * In the event that we are replying to incoming
20068 		 * ICMP packets, conn could be NULL.
20069 		 */
20070 		if ((connp != NULL) && connp->conn_dontroute)
20071 			ipha->ipha_ttl = 1;
20072 		else
20073 			ipha->ipha_ttl = ip_broadcast_ttl;
20074 
20075 		/*
20076 		 * Note that we are not doing a IRB_REFHOLD here.
20077 		 * Actually we don't care if the list changes i.e
20078 		 * if somebody deletes an IRE from the list while
20079 		 * we drop the lock, the next time we come around
20080 		 * ire_next will be NULL and hence we won't send
20081 		 * out multiple copies which is fine.
20082 		 */
20083 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20084 		ire1 = ire->ire_next;
20085 		if (conn_outgoing_ill != NULL) {
20086 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
20087 				ASSERT(ire1 == ire->ire_next);
20088 				if (ire1 != NULL && ire1->ire_addr == dst) {
20089 					ire_refrele(ire);
20090 					ire = ire1;
20091 					IRE_REFHOLD(ire);
20092 					ire1 = ire->ire_next;
20093 					continue;
20094 				}
20095 				rw_exit(&ire->ire_bucket->irb_lock);
20096 				/* Did not find a matching ill */
20097 				ip1dbg(("ip_wput_ire: broadcast with no "
20098 				    "matching IP_BOUND_IF ill %s\n",
20099 				    conn_outgoing_ill->ill_name));
20100 				freemsg(first_mp);
20101 				if (ire != NULL)
20102 					ire_refrele(ire);
20103 				ill_refrele(conn_outgoing_ill);
20104 				return;
20105 			}
20106 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
20107 			/*
20108 			 * If the next IRE has the same address and is not one
20109 			 * of the two copies that we need to send, try to see
20110 			 * whether this copy should be sent at all. This
20111 			 * assumes that we insert loopbacks first and then
20112 			 * non-loopbacks. This is acheived by inserting the
20113 			 * loopback always before non-loopback.
20114 			 * This is used to send a single copy of a broadcast
20115 			 * packet out all physical interfaces that have an
20116 			 * matching IRE_BROADCAST while also looping
20117 			 * back one copy (to ip_wput_local) for each
20118 			 * matching physical interface. However, we avoid
20119 			 * sending packets out different logical that match by
20120 			 * having ipif_up/ipif_down supress duplicate
20121 			 * IRE_BROADCASTS.
20122 			 *
20123 			 * This feature is currently used to get broadcasts
20124 			 * sent to multiple interfaces, when the broadcast
20125 			 * address being used applies to multiple interfaces.
20126 			 * For example, a whole net broadcast will be
20127 			 * replicated on every connected subnet of
20128 			 * the target net.
20129 			 *
20130 			 * Each zone has its own set of IRE_BROADCASTs, so that
20131 			 * we're able to distribute inbound packets to multiple
20132 			 * zones who share a broadcast address. We avoid looping
20133 			 * back outbound packets in different zones but on the
20134 			 * same ill, as the application would see duplicates.
20135 			 *
20136 			 * If the interfaces are part of the same group,
20137 			 * we would want to send only one copy out for
20138 			 * whole group.
20139 			 *
20140 			 * This logic assumes that ire_add_v4() groups the
20141 			 * IRE_BROADCAST entries so that those with the same
20142 			 * ire_addr and ill_group are kept together.
20143 			 */
20144 			ire_ill = ire->ire_ipif->ipif_ill;
20145 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
20146 				if (ire_ill->ill_group != NULL &&
20147 				    (ire->ire_marks & IRE_MARK_NORECV)) {
20148 					/*
20149 					 * If the current zone only has an ire
20150 					 * broadcast for this address marked
20151 					 * NORECV, the ire we want is ahead in
20152 					 * the bucket, so we look it up
20153 					 * deliberately ignoring the zoneid.
20154 					 */
20155 					for (ire1 = ire->ire_bucket->irb_ire;
20156 					    ire1 != NULL;
20157 					    ire1 = ire1->ire_next) {
20158 						ire1_ill =
20159 						    ire1->ire_ipif->ipif_ill;
20160 						if (ire1->ire_addr != dst)
20161 							continue;
20162 						/* skip over the current ire */
20163 						if (ire1 == ire)
20164 							continue;
20165 						/* skip over deleted ires */
20166 						if (ire1->ire_marks &
20167 						    IRE_MARK_CONDEMNED)
20168 							continue;
20169 						/*
20170 						 * non-loopback ire in our
20171 						 * group: use it for the next
20172 						 * pass in the loop
20173 						 */
20174 						if (ire1->ire_stq != NULL &&
20175 						    ire1_ill->ill_group ==
20176 						    ire_ill->ill_group)
20177 							break;
20178 					}
20179 				}
20180 			} else {
20181 				while (ire1 != NULL && ire1->ire_addr == dst) {
20182 					ire1_ill = ire1->ire_ipif->ipif_ill;
20183 					/*
20184 					 * We can have two broadcast ires on the
20185 					 * same ill in different zones; here
20186 					 * we'll send a copy of the packet on
20187 					 * each ill and the fanout code will
20188 					 * call conn_wantpacket() to check that
20189 					 * the zone has the broadcast address
20190 					 * configured on the ill. If the two
20191 					 * ires are in the same group we only
20192 					 * send one copy up.
20193 					 */
20194 					if (ire1_ill != ire_ill &&
20195 					    (ire1_ill->ill_group == NULL ||
20196 					    ire_ill->ill_group == NULL ||
20197 					    ire1_ill->ill_group !=
20198 					    ire_ill->ill_group)) {
20199 						break;
20200 					}
20201 					ire1 = ire1->ire_next;
20202 				}
20203 			}
20204 		}
20205 		ASSERT(multirt_send == B_FALSE);
20206 		if (ire1 != NULL && ire1->ire_addr == dst) {
20207 			if ((ire->ire_flags & RTF_MULTIRT) &&
20208 			    (ire1->ire_flags & RTF_MULTIRT)) {
20209 				/*
20210 				 * We are in the multirouting case.
20211 				 * The message must be sent at least
20212 				 * on both ires. These ires have been
20213 				 * inserted AFTER the standard ones
20214 				 * in ip_rt_add(). There are thus no
20215 				 * other ire entries for the destination
20216 				 * address in the rest of the bucket
20217 				 * that do not have the RTF_MULTIRT
20218 				 * flag. We don't process a copy
20219 				 * of the message here. This will be
20220 				 * done in the final sending loop.
20221 				 */
20222 				multirt_send = B_TRUE;
20223 			} else {
20224 				next_mp = ip_copymsg(first_mp);
20225 				if (next_mp != NULL)
20226 					IRE_REFHOLD(ire1);
20227 			}
20228 		}
20229 		rw_exit(&ire->ire_bucket->irb_lock);
20230 	}
20231 
20232 	if (stq) {
20233 		/*
20234 		 * A non-NULL send-to queue means this packet is going
20235 		 * out of this machine.
20236 		 */
20237 
20238 		BUMP_MIB(&ip_mib, ipOutRequests);
20239 		ttl_protocol = ((uint16_t *)ipha)[4];
20240 		/*
20241 		 * We accumulate the pseudo header checksum in cksum.
20242 		 * This is pretty hairy code, so watch close.  One
20243 		 * thing to keep in mind is that UDP and TCP have
20244 		 * stored their respective datagram lengths in their
20245 		 * checksum fields.  This lines things up real nice.
20246 		 */
20247 		cksum = (dst >> 16) + (dst & 0xFFFF) +
20248 		    (src >> 16) + (src & 0xFFFF);
20249 		/*
20250 		 * We assume the udp checksum field contains the
20251 		 * length, so to compute the pseudo header checksum,
20252 		 * all we need is the protocol number and src/dst.
20253 		 */
20254 		/* Provide the checksums for UDP and TCP. */
20255 		if ((PROTO == IPPROTO_TCP) &&
20256 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
20257 			/* hlen gets the number of uchar_ts in the IP header */
20258 			hlen = (V_HLEN & 0xF) << 2;
20259 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
20260 			IP_STAT(ip_out_sw_cksum);
20261 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
20262 		} else if (PROTO == IPPROTO_SCTP &&
20263 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
20264 			sctp_hdr_t	*sctph;
20265 
20266 			hlen = (V_HLEN & 0xF) << 2;
20267 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
20268 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
20269 			sctph->sh_chksum = 0;
20270 #ifdef	DEBUG
20271 			if (!skip_sctp_cksum)
20272 #endif
20273 				sctph->sh_chksum = sctp_cksum(mp, hlen);
20274 		} else {
20275 			queue_t *dev_q = stq->q_next;
20276 
20277 			if ((dev_q->q_next || dev_q->q_first) &&
20278 			    !canput(dev_q)) {
20279 			    blocked:
20280 				ipha->ipha_ident = ip_hdr_included;
20281 				/*
20282 				 * If we don't have a conn to apply
20283 				 * backpressure, free the message.
20284 				 * In the ire_send path, we don't know
20285 				 * the position to requeue the packet. Rather
20286 				 * than reorder packets, we just drop this
20287 				 * packet.
20288 				 */
20289 				if (ip_output_queue && connp != NULL &&
20290 				    caller != IRE_SEND) {
20291 					if (caller == IP_WSRV) {
20292 						connp->conn_did_putbq = 1;
20293 						(void) putbq(connp->conn_wq,
20294 						    first_mp);
20295 						conn_drain_insert(connp);
20296 						/*
20297 						 * This is the service thread,
20298 						 * and the queue is already
20299 						 * noenabled. The check for
20300 						 * canput and the putbq is not
20301 						 * atomic. So we need to check
20302 						 * again.
20303 						 */
20304 						if (canput(stq->q_next))
20305 							connp->conn_did_putbq
20306 							    = 0;
20307 						IP_STAT(ip_conn_flputbq);
20308 					} else {
20309 						/*
20310 						 * We are not the service proc.
20311 						 * ip_wsrv will be scheduled or
20312 						 * is already running.
20313 						 */
20314 						(void) putq(connp->conn_wq,
20315 						    first_mp);
20316 					}
20317 				} else {
20318 					BUMP_MIB(&ip_mib, ipOutDiscards);
20319 					freemsg(first_mp);
20320 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20321 					    "ip_wput_ire_end: q %p (%S)",
20322 					    q, "discard");
20323 				}
20324 				ire_refrele(ire);
20325 				if (next_mp) {
20326 					ire_refrele(ire1);
20327 					freemsg(next_mp);
20328 				}
20329 				if (conn_outgoing_ill != NULL)
20330 					ill_refrele(conn_outgoing_ill);
20331 				return;
20332 			}
20333 			if ((PROTO == IPPROTO_UDP) &&
20334 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
20335 				/*
20336 				 * hlen gets the number of uchar_ts in the
20337 				 * IP header
20338 				 */
20339 				hlen = (V_HLEN & 0xF) << 2;
20340 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
20341 				if (*up) {
20342 					uint_t	sum;
20343 
20344 					/*
20345 					 * NOTE: watch out for compiler high
20346 					 * bits
20347 					 */
20348 					IP_STAT(ip_out_sw_cksum);
20349 					sum = IP_CSUM(mp, hlen,
20350 					    cksum + IP_UDP_CSUM_COMP);
20351 					*up = (uint16_t)(sum ? sum : ~sum);
20352 				}
20353 			}
20354 		}
20355 		/*
20356 		 * Need to do this even when fragmenting. The local
20357 		 * loopback can be done without computing checksums
20358 		 * but forwarding out other interface must be done
20359 		 * after the IP checksum (and ULP checksums) have been
20360 		 * computed.
20361 		 *
20362 		 * NOTE : multicast_forward is set only if this packet
20363 		 * originated from ip_wput. For packets originating from
20364 		 * ip_wput_multicast, it is not set.
20365 		 */
20366 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
20367 		    multi_loopback:
20368 			ip2dbg(("ip_wput: multicast, loop %d\n",
20369 			    conn_multicast_loop));
20370 
20371 			/*  Forget header checksum offload */
20372 			mp->b_datap->db_struioun.cksum.flags &=
20373 			    ~HCK_IPV4_HDRCKSUM;
20374 			iphdrhwcksum = B_FALSE;
20375 
20376 			/*
20377 			 * Local loopback of multicasts?  Check the
20378 			 * ill.
20379 			 *
20380 			 * Note that the loopback function will not come
20381 			 * in through ip_rput - it will only do the
20382 			 * client fanout thus we need to do an mforward
20383 			 * as well.  The is different from the BSD
20384 			 * logic.
20385 			 */
20386 			if (ill != NULL) {
20387 				ilm_t	*ilm;
20388 
20389 				ILM_WALKER_HOLD(ill);
20390 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
20391 				    ALL_ZONES);
20392 				ILM_WALKER_RELE(ill);
20393 				if (ilm != NULL) {
20394 					/*
20395 					 * Pass along the virtual output q.
20396 					 * ip_wput_local() will distribute the
20397 					 * packet to all the matching zones,
20398 					 * except the sending zone when
20399 					 * IP_MULTICAST_LOOP is false.
20400 					 */
20401 					ip_multicast_loopback(q, ill, first_mp,
20402 					    conn_multicast_loop ? 0 :
20403 					    IP_FF_NO_MCAST_LOOP, zoneid);
20404 				}
20405 			}
20406 			if (ipha->ipha_ttl == 0) {
20407 				/*
20408 				 * 0 => only to this host i.e. we are
20409 				 * done. We are also done if this was the
20410 				 * loopback interface since it is sufficient
20411 				 * to loopback one copy of a multicast packet.
20412 				 */
20413 				freemsg(first_mp);
20414 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20415 				    "ip_wput_ire_end: q %p (%S)",
20416 				    q, "loopback");
20417 				ire_refrele(ire);
20418 				if (conn_outgoing_ill != NULL)
20419 					ill_refrele(conn_outgoing_ill);
20420 				return;
20421 			}
20422 			/*
20423 			 * ILLF_MULTICAST is checked in ip_newroute
20424 			 * i.e. we don't need to check it here since
20425 			 * all IRE_CACHEs come from ip_newroute.
20426 			 * For multicast traffic, SO_DONTROUTE is interpreted
20427 			 * to mean only send the packet out the interface
20428 			 * (optionally specified with IP_MULTICAST_IF)
20429 			 * and do not forward it out additional interfaces.
20430 			 * RSVP and the rsvp daemon is an example of a
20431 			 * protocol and user level process that
20432 			 * handles it's own routing. Hence, it uses the
20433 			 * SO_DONTROUTE option to accomplish this.
20434 			 */
20435 
20436 			if (ip_g_mrouter && !conn_dontroute && ill != NULL) {
20437 				/* Unconditionally redo the checksum */
20438 				ipha->ipha_hdr_checksum = 0;
20439 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
20440 
20441 				/*
20442 				 * If this needs to go out secure, we need
20443 				 * to wait till we finish the IPSEC
20444 				 * processing.
20445 				 */
20446 				if (ipsec_len == 0 &&
20447 				    ip_mforward(ill, ipha, mp)) {
20448 					freemsg(first_mp);
20449 					ip1dbg(("ip_wput: mforward failed\n"));
20450 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20451 					    "ip_wput_ire_end: q %p (%S)",
20452 					    q, "mforward failed");
20453 					ire_refrele(ire);
20454 					if (conn_outgoing_ill != NULL)
20455 						ill_refrele(conn_outgoing_ill);
20456 					return;
20457 				}
20458 			}
20459 		}
20460 		max_frag = ire->ire_max_frag;
20461 		cksum += ttl_protocol;
20462 		if (!FRAGMENT_NEEDED(max_frag, (LENGTH + ipsec_len))) {
20463 			/* No fragmentation required for this one. */
20464 			/* Complete the IP header checksum. */
20465 			cksum += ipha->ipha_ident;
20466 			/*
20467 			 * Don't use frag_flag if packet is pre-built or source
20468 			 * routed or if multicast (since multicast packets do
20469 			 * not solicit ICMP "packet too big" messages).
20470 			 */
20471 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
20472 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
20473 			    !ip_source_route_included(ipha)) &&
20474 			    !CLASSD(ipha->ipha_dst))
20475 				ipha->ipha_fragment_offset_and_flags |=
20476 				    htons(ire->ire_frag_flag);
20477 
20478 			cksum += (v_hlen_tos_len >> 16)+
20479 			    (v_hlen_tos_len & 0xFFFF);
20480 			cksum += ipha->ipha_fragment_offset_and_flags;
20481 			hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
20482 			if (hlen) {
20483 			    checksumoptions:
20484 				/*
20485 				 * Account for the IP Options in the IP
20486 				 * header checksum.
20487 				 */
20488 				up = (uint16_t *)(rptr+IP_SIMPLE_HDR_LENGTH);
20489 				do {
20490 					cksum += up[0];
20491 					cksum += up[1];
20492 					up += 2;
20493 				} while (--hlen);
20494 			}
20495 			cksum = ((cksum & 0xFFFF) + (cksum >> 16));
20496 			cksum = ~(cksum + (cksum >> 16));
20497 			ipha->ipha_hdr_checksum = (uint16_t)cksum;
20498 			if (ipsec_len != 0) {
20499 				ipsec_out_process(q, first_mp, ire, ill_index);
20500 				if (!next_mp) {
20501 					ire_refrele(ire);
20502 					if (conn_outgoing_ill != NULL)
20503 						ill_refrele(conn_outgoing_ill);
20504 					return;
20505 				}
20506 				goto next;
20507 			}
20508 
20509 			/*
20510 			 * multirt_send has already been handled
20511 			 * for broadcast, but not yet for multicast
20512 			 * or IP options.
20513 			 */
20514 			if (next_mp == NULL) {
20515 				if (ire->ire_flags & RTF_MULTIRT) {
20516 					multirt_send = B_TRUE;
20517 				}
20518 			}
20519 
20520 			/*
20521 			 * In most cases, the emission loop below is
20522 			 * entered only once. Only in the case where
20523 			 * the ire holds the RTF_MULTIRT flag, do we loop
20524 			 * to process all RTF_MULTIRT ires in the bucket,
20525 			 * and send the packet through all crossed
20526 			 * RTF_MULTIRT routes.
20527 			 */
20528 			do {
20529 				if (multirt_send) {
20530 					irb_t *irb;
20531 
20532 					irb = ire->ire_bucket;
20533 					ASSERT(irb != NULL);
20534 					/*
20535 					 * We are in a multiple send case,
20536 					 * need to get the next IRE and make
20537 					 * a duplicate of the packet.
20538 					 */
20539 					IRB_REFHOLD(irb);
20540 					for (ire1 = ire->ire_next;
20541 					    ire1 != NULL;
20542 					    ire1 = ire1->ire_next) {
20543 						if (!(ire1->ire_flags &
20544 						    RTF_MULTIRT))
20545 							continue;
20546 						if (ire1->ire_addr !=
20547 						    ire->ire_addr)
20548 							continue;
20549 						if (ire1->ire_marks &
20550 						    (IRE_MARK_CONDEMNED|
20551 							IRE_MARK_HIDDEN))
20552 							continue;
20553 
20554 						/* Got one */
20555 						IRE_REFHOLD(ire1);
20556 						break;
20557 					}
20558 					IRB_REFRELE(irb);
20559 
20560 					if (ire1 != NULL) {
20561 						next_mp = copyb(mp);
20562 						if ((next_mp == NULL) ||
20563 						    ((mp->b_cont != NULL) &&
20564 						    ((next_mp->b_cont =
20565 						    dupmsg(mp->b_cont))
20566 						    == NULL))) {
20567 							freemsg(next_mp);
20568 							next_mp = NULL;
20569 							ire_refrele(ire1);
20570 							ire1 = NULL;
20571 						}
20572 					}
20573 
20574 					/*
20575 					 * Last multiroute ire; don't loop
20576 					 * anymore. The emission is over
20577 					 * and next_mp is NULL.
20578 					 */
20579 					if (ire1 == NULL) {
20580 						multirt_send = B_FALSE;
20581 					}
20582 				}
20583 
20584 			noprepend:
20585 				ASSERT(ipsec_len == 0);
20586 				mp1 = ip_wput_attach_llhdr(mp, ire,
20587 				    IPP_LOCAL_OUT, ill_index);
20588 				if (mp1 == NULL) {
20589 					BUMP_MIB(&ip_mib, ipOutDiscards);
20590 					if (next_mp) {
20591 						freemsg(next_mp);
20592 						ire_refrele(ire1);
20593 					}
20594 					ire_refrele(ire);
20595 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20596 					    "ip_wput_ire_end: q %p (%S)",
20597 					    q, "discard MDATA");
20598 					if (conn_outgoing_ill != NULL)
20599 						ill_refrele(conn_outgoing_ill);
20600 					return;
20601 				}
20602 				UPDATE_OB_PKT_COUNT(ire);
20603 				ire->ire_last_used_time = lbolt;
20604 
20605 				if (multirt_send) {
20606 					/*
20607 					 * We are in a multiple send case,
20608 					 * need to re-enter the sending loop
20609 					 * using the next ire.
20610 					 */
20611 					putnext(stq, mp1);
20612 					ire_refrele(ire);
20613 					ire = ire1;
20614 					stq = ire->ire_stq;
20615 					mp = next_mp;
20616 					next_mp = NULL;
20617 					ipha = (ipha_t *)mp->b_rptr;
20618 					ill_index = Q_TO_INDEX(stq);
20619 				}
20620 			} while (multirt_send);
20621 
20622 			if (!next_mp) {
20623 				/*
20624 				 * Last copy going out (the ultra-common
20625 				 * case).  Note that we intentionally replicate
20626 				 * the putnext rather than calling it before
20627 				 * the next_mp check in hopes of a little
20628 				 * tail-call action out of the compiler.
20629 				 */
20630 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20631 				    "ip_wput_ire_end: q %p (%S)",
20632 				    q, "last copy out(1)");
20633 				putnext(stq, mp1);
20634 				ire_refrele(ire);
20635 				if (conn_outgoing_ill != NULL)
20636 					ill_refrele(conn_outgoing_ill);
20637 				return;
20638 			}
20639 			/* More copies going out below. */
20640 			putnext(stq, mp1);
20641 		} else {
20642 			int offset;
20643 		    fragmentit:
20644 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
20645 			/*
20646 			 * If this would generate a icmp_frag_needed message,
20647 			 * we need to handle it before we do the IPSEC
20648 			 * processing. Otherwise, we need to strip the IPSEC
20649 			 * headers before we send up the message to the ULPs
20650 			 * which becomes messy and difficult.
20651 			 */
20652 			if (ipsec_len != 0) {
20653 				if ((max_frag < (unsigned int)(LENGTH +
20654 				    ipsec_len)) && (offset & IPH_DF)) {
20655 
20656 					BUMP_MIB(&ip_mib, ipFragFails);
20657 					ipha->ipha_hdr_checksum = 0;
20658 					ipha->ipha_hdr_checksum =
20659 					    (uint16_t)ip_csum_hdr(ipha);
20660 					icmp_frag_needed(ire->ire_stq, first_mp,
20661 					    max_frag);
20662 					if (!next_mp) {
20663 						ire_refrele(ire);
20664 						if (conn_outgoing_ill != NULL) {
20665 							ill_refrele(
20666 							    conn_outgoing_ill);
20667 						}
20668 						return;
20669 					}
20670 				} else {
20671 					/*
20672 					 * This won't cause a icmp_frag_needed
20673 					 * message. to be gnerated. Send it on
20674 					 * the wire. Note that this could still
20675 					 * cause fragmentation and all we
20676 					 * do is the generation of the message
20677 					 * to the ULP if needed before IPSEC.
20678 					 */
20679 					if (!next_mp) {
20680 						ipsec_out_process(q, first_mp,
20681 						    ire, ill_index);
20682 						TRACE_2(TR_FAC_IP,
20683 						    TR_IP_WPUT_IRE_END,
20684 						    "ip_wput_ire_end: q %p "
20685 						    "(%S)", q,
20686 						    "last ipsec_out_process");
20687 						ire_refrele(ire);
20688 						if (conn_outgoing_ill != NULL) {
20689 							ill_refrele(
20690 							    conn_outgoing_ill);
20691 						}
20692 						return;
20693 					}
20694 					ipsec_out_process(q, first_mp,
20695 					    ire, ill_index);
20696 				}
20697 			} else {
20698 				/* Initiate IPPF processing */
20699 				if (IPP_ENABLED(IPP_LOCAL_OUT)) {
20700 					ip_process(IPP_LOCAL_OUT, &mp,
20701 					    ill_index);
20702 					if (mp == NULL) {
20703 						BUMP_MIB(&ip_mib,
20704 						    ipOutDiscards);
20705 						if (next_mp != NULL) {
20706 							freemsg(next_mp);
20707 							ire_refrele(ire1);
20708 						}
20709 						ire_refrele(ire);
20710 						TRACE_2(TR_FAC_IP,
20711 						    TR_IP_WPUT_IRE_END,
20712 						    "ip_wput_ire: q %p (%S)",
20713 						    q, "discard MDATA");
20714 						if (conn_outgoing_ill != NULL) {
20715 							ill_refrele(
20716 							    conn_outgoing_ill);
20717 						}
20718 						return;
20719 					}
20720 				}
20721 				if (!next_mp) {
20722 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20723 					    "ip_wput_ire_end: q %p (%S)",
20724 					    q, "last fragmentation");
20725 					ip_wput_ire_fragmentit(mp, ire);
20726 					ire_refrele(ire);
20727 					if (conn_outgoing_ill != NULL)
20728 						ill_refrele(conn_outgoing_ill);
20729 					return;
20730 				}
20731 				ip_wput_ire_fragmentit(mp, ire);
20732 			}
20733 		}
20734 	} else {
20735 	    nullstq:
20736 		/* A NULL stq means the destination address is local. */
20737 		UPDATE_OB_PKT_COUNT(ire);
20738 		ire->ire_last_used_time = lbolt;
20739 		ASSERT(ire->ire_ipif != NULL);
20740 		if (!next_mp) {
20741 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20742 			    "ip_wput_ire_end: q %p (%S)",
20743 			    q, "local address");
20744 			ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha,
20745 			    first_mp, ire, 0, ire->ire_zoneid);
20746 			ire_refrele(ire);
20747 			if (conn_outgoing_ill != NULL)
20748 				ill_refrele(conn_outgoing_ill);
20749 			return;
20750 		}
20751 		ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha, first_mp,
20752 		    ire, 0, ire->ire_zoneid);
20753 	}
20754 next:
20755 	/*
20756 	 * More copies going out to additional interfaces.
20757 	 * ire1 has already been held. We don't need the
20758 	 * "ire" anymore.
20759 	 */
20760 	ire_refrele(ire);
20761 	ire = ire1;
20762 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
20763 	mp = next_mp;
20764 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
20765 	ill = ire_to_ill(ire);
20766 	first_mp = mp;
20767 	if (ipsec_len != 0) {
20768 		ASSERT(first_mp->b_datap->db_type == M_CTL);
20769 		mp = mp->b_cont;
20770 	}
20771 	dst = ire->ire_addr;
20772 	ipha = (ipha_t *)mp->b_rptr;
20773 	/*
20774 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
20775 	 * Restore ipha_ident "no checksum" flag.
20776 	 */
20777 	src = orig_src;
20778 	ipha->ipha_ident = ip_hdr_included;
20779 	goto another;
20780 
20781 #undef	rptr
20782 #undef	Q_TO_INDEX
20783 }
20784 
20785 /*
20786  * Routine to allocate a message that is used to notify the ULP about MDT.
20787  * The caller may provide a pointer to the link-layer MDT capabilities,
20788  * or NULL if MDT is to be disabled on the stream.
20789  */
20790 mblk_t *
20791 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
20792 {
20793 	mblk_t *mp;
20794 	ip_mdt_info_t *mdti;
20795 	ill_mdt_capab_t *idst;
20796 
20797 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
20798 		DB_TYPE(mp) = M_CTL;
20799 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
20800 		mdti = (ip_mdt_info_t *)mp->b_rptr;
20801 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
20802 		idst = &(mdti->mdt_capab);
20803 
20804 		/*
20805 		 * If the caller provides us with the capability, copy
20806 		 * it over into our notification message; otherwise
20807 		 * we zero out the capability portion.
20808 		 */
20809 		if (isrc != NULL)
20810 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
20811 		else
20812 			bzero((caddr_t)idst, sizeof (*idst));
20813 	}
20814 	return (mp);
20815 }
20816 
20817 /*
20818  * Routine which determines whether MDT can be enabled on the destination
20819  * IRE and IPC combination, and if so, allocates and returns the MDT
20820  * notification mblk that may be used by ULP.  We also check if we need to
20821  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
20822  * MDT usage in the past have been lifted.  This gets called during IP
20823  * and ULP binding.
20824  */
20825 mblk_t *
20826 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
20827     ill_mdt_capab_t *mdt_cap)
20828 {
20829 	mblk_t *mp;
20830 	boolean_t rc = B_FALSE;
20831 
20832 	ASSERT(dst_ire != NULL);
20833 	ASSERT(connp != NULL);
20834 	ASSERT(mdt_cap != NULL);
20835 
20836 	/*
20837 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
20838 	 * Multidata, which is handled in tcp_multisend().  This
20839 	 * is the reason why we do all these checks here, to ensure
20840 	 * that we don't enable Multidata for the cases which we
20841 	 * can't handle at the moment.
20842 	 */
20843 	do {
20844 		/* Only do TCP at the moment */
20845 		if (connp->conn_ulp != IPPROTO_TCP)
20846 			break;
20847 
20848 		/*
20849 		 * IPSEC outbound policy present?  Note that we get here
20850 		 * after calling ipsec_conn_cache_policy() where the global
20851 		 * policy checking is performed.  conn_latch will be
20852 		 * non-NULL as long as there's a policy defined,
20853 		 * i.e. conn_out_enforce_policy may be NULL in such case
20854 		 * when the connection is non-secure, and hence we check
20855 		 * further if the latch refers to an outbound policy.
20856 		 */
20857 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
20858 			break;
20859 
20860 		/* CGTP (multiroute) is enabled? */
20861 		if (dst_ire->ire_flags & RTF_MULTIRT)
20862 			break;
20863 
20864 		/* Outbound IPQoS enabled? */
20865 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
20866 			/*
20867 			 * In this case, we disable MDT for this and all
20868 			 * future connections going over the interface.
20869 			 */
20870 			mdt_cap->ill_mdt_on = 0;
20871 			break;
20872 		}
20873 
20874 		/* socket option(s) present? */
20875 		if (!CONN_IS_MD_FASTPATH(connp))
20876 			break;
20877 
20878 		rc = B_TRUE;
20879 	/* CONSTCOND */
20880 	} while (0);
20881 
20882 	/* Remember the result */
20883 	connp->conn_mdt_ok = rc;
20884 
20885 	if (!rc)
20886 		return (NULL);
20887 	else if (!mdt_cap->ill_mdt_on) {
20888 		/*
20889 		 * If MDT has been previously turned off in the past, and we
20890 		 * currently can do MDT (due to IPQoS policy removal, etc.)
20891 		 * then enable it for this interface.
20892 		 */
20893 		mdt_cap->ill_mdt_on = 1;
20894 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
20895 		    "interface %s\n", ill_name));
20896 	}
20897 
20898 	/* Allocate the MDT info mblk */
20899 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
20900 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
20901 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
20902 		return (NULL);
20903 	}
20904 	return (mp);
20905 }
20906 
20907 /*
20908  * Create destination address attribute, and fill it with the physical
20909  * destination address and SAP taken from the template DL_UNITDATA_REQ
20910  * message block.
20911  */
20912 boolean_t
20913 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
20914 {
20915 	dl_unitdata_req_t *dlurp;
20916 	pattr_t *pa;
20917 	pattrinfo_t pa_info;
20918 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
20919 	uint_t das_len, das_off;
20920 
20921 	ASSERT(dlmp != NULL);
20922 
20923 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
20924 	das_len = dlurp->dl_dest_addr_length;
20925 	das_off = dlurp->dl_dest_addr_offset;
20926 
20927 	pa_info.type = PATTR_DSTADDRSAP;
20928 	pa_info.len = sizeof (**das) + das_len - 1;
20929 
20930 	/* create and associate the attribute */
20931 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
20932 	if (pa != NULL) {
20933 		ASSERT(*das != NULL);
20934 		(*das)->addr_is_group = 0;
20935 		(*das)->addr_len = (uint8_t)das_len;
20936 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
20937 	}
20938 
20939 	return (pa != NULL);
20940 }
20941 
20942 /*
20943  * Create hardware checksum attribute and fill it with the values passed.
20944  */
20945 boolean_t
20946 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
20947     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
20948 {
20949 	pattr_t *pa;
20950 	pattrinfo_t pa_info;
20951 
20952 	ASSERT(mmd != NULL);
20953 
20954 	pa_info.type = PATTR_HCKSUM;
20955 	pa_info.len = sizeof (pattr_hcksum_t);
20956 
20957 	/* create and associate the attribute */
20958 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
20959 	if (pa != NULL) {
20960 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
20961 
20962 		hck->hcksum_start_offset = start_offset;
20963 		hck->hcksum_stuff_offset = stuff_offset;
20964 		hck->hcksum_end_offset = end_offset;
20965 		hck->hcksum_flags = flags;
20966 	}
20967 	return (pa != NULL);
20968 }
20969 
20970 /*
20971  * Create zerocopy attribute and fill it with the specified flags
20972  */
20973 boolean_t
20974 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
20975 {
20976 	pattr_t *pa;
20977 	pattrinfo_t pa_info;
20978 
20979 	ASSERT(mmd != NULL);
20980 	pa_info.type = PATTR_ZCOPY;
20981 	pa_info.len = sizeof (pattr_zcopy_t);
20982 
20983 	/* create and associate the attribute */
20984 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
20985 	if (pa != NULL) {
20986 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
20987 
20988 		zcopy->zcopy_flags = flags;
20989 	}
20990 	return (pa != NULL);
20991 }
20992 
20993 /*
20994  * Outbound IP fragmentation routine.
20995  *
20996  * NOTE : This routine does not ire_refrele the ire that is passed in
20997  * as the argument.
20998  */
20999 static void
21000 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
21001     uint32_t frag_flag)
21002 {
21003 	int	i1;
21004 	mblk_t	*ll_hdr_mp;
21005 	int 	ll_hdr_len;
21006 	int	hdr_len;
21007 	mblk_t	*hdr_mp;
21008 	ipha_t	*ipha;
21009 	int	ip_data_end;
21010 	int	len;
21011 	mblk_t	*mp = mp_orig;
21012 	int	offset;
21013 	queue_t	*q;
21014 	uint32_t	v_hlen_tos_len;
21015 	mblk_t	*first_mp;
21016 	boolean_t mctl_present;
21017 	mblk_t	*xmit_mp;
21018 	mblk_t	*carve_mp;
21019 	ire_t   *ire1 = NULL;
21020 	ire_t   *save_ire = NULL;
21021 	mblk_t  *next_mp = NULL;
21022 	boolean_t last_frag = B_FALSE;
21023 	boolean_t multirt_send = B_FALSE;
21024 	ire_t *first_ire = NULL;
21025 	irb_t *irb = NULL;
21026 
21027 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
21028 	    "ip_wput_frag_start:");
21029 
21030 	if (mp->b_datap->db_type == M_CTL) {
21031 		first_mp = mp;
21032 		mp_orig = mp = mp->b_cont;
21033 		mctl_present = B_TRUE;
21034 	} else {
21035 		first_mp = mp;
21036 		mctl_present = B_FALSE;
21037 	}
21038 
21039 	ipha = (ipha_t *)mp->b_rptr;
21040 
21041 	/*
21042 	 * If the Don't Fragment flag is on, generate an ICMP destination
21043 	 * unreachable, fragmentation needed.
21044 	 */
21045 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
21046 	if (offset & IPH_DF) {
21047 		BUMP_MIB(&ip_mib, ipFragFails);
21048 		/*
21049 		 * Need to compute hdr checksum if called from ip_wput_ire.
21050 		 * Note that ip_rput_forward verifies the checksum before
21051 		 * calling this routine so in that case this is a noop.
21052 		 */
21053 		ipha->ipha_hdr_checksum = 0;
21054 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21055 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag);
21056 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21057 		    "ip_wput_frag_end:(%S)",
21058 		    "don't fragment");
21059 		return;
21060 	}
21061 	if (mctl_present)
21062 		freeb(first_mp);
21063 	/*
21064 	 * Establish the starting offset.  May not be zero if we are fragging
21065 	 * a fragment that is being forwarded.
21066 	 */
21067 	offset = offset & IPH_OFFSET;
21068 
21069 	/* TODO why is this test needed? */
21070 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21071 	if (((max_frag - LENGTH) & ~7) < 8) {
21072 		/* TODO: notify ulp somehow */
21073 		BUMP_MIB(&ip_mib, ipFragFails);
21074 		freemsg(mp);
21075 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21076 		    "ip_wput_frag_end:(%S)",
21077 		    "len < 8");
21078 		return;
21079 	}
21080 
21081 	hdr_len = (V_HLEN & 0xF) << 2;
21082 	ipha->ipha_hdr_checksum = 0;
21083 
21084 	/* Get a copy of the header for the trailing frags */
21085 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset);
21086 	if (!hdr_mp) {
21087 		BUMP_MIB(&ip_mib, ipOutDiscards);
21088 		freemsg(mp);
21089 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21090 		    "ip_wput_frag_end:(%S)",
21091 		    "couldn't copy hdr");
21092 		return;
21093 	}
21094 
21095 	/* Store the starting offset, with the MoreFrags flag. */
21096 	i1 = offset | IPH_MF | frag_flag;
21097 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
21098 
21099 	/* Establish the ending byte offset, based on the starting offset. */
21100 	offset <<= 3;
21101 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
21102 
21103 	/*
21104 	 * Establish the number of bytes maximum per frag, after putting
21105 	 * in the header.
21106 	 */
21107 	len = (max_frag - hdr_len) & ~7;
21108 
21109 	/* Store the length of the first fragment in the IP header. */
21110 	i1 = len + hdr_len;
21111 	ASSERT(i1 <= IP_MAXPACKET);
21112 	ipha->ipha_length = htons((uint16_t)i1);
21113 
21114 	/*
21115 	 * Compute the IP header checksum for the first frag.  We have to
21116 	 * watch out that we stop at the end of the header.
21117 	 */
21118 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21119 
21120 	/*
21121 	 * Now carve off the first frag.  Note that this will include the
21122 	 * original IP header.
21123 	 */
21124 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
21125 		BUMP_MIB(&ip_mib, ipOutDiscards);
21126 		freeb(hdr_mp);
21127 		freemsg(mp_orig);
21128 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21129 		    "ip_wput_frag_end:(%S)",
21130 		    "couldn't carve first");
21131 		return;
21132 	}
21133 
21134 	/*
21135 	 * Multirouting case. Each fragment is replicated
21136 	 * via all non-condemned RTF_MULTIRT routes
21137 	 * currently resolved.
21138 	 * We ensure that first_ire is the first RTF_MULTIRT
21139 	 * ire in the bucket.
21140 	 */
21141 	if (ire->ire_flags & RTF_MULTIRT) {
21142 		irb = ire->ire_bucket;
21143 		ASSERT(irb != NULL);
21144 
21145 		multirt_send = B_TRUE;
21146 
21147 		/* Make sure we do not omit any multiroute ire. */
21148 		IRB_REFHOLD(irb);
21149 		for (first_ire = irb->irb_ire;
21150 		    first_ire != NULL;
21151 		    first_ire = first_ire->ire_next) {
21152 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
21153 			    (first_ire->ire_addr == ire->ire_addr) &&
21154 			    !(first_ire->ire_marks &
21155 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
21156 				break;
21157 		}
21158 
21159 		if (first_ire != NULL) {
21160 			if (first_ire != ire) {
21161 				IRE_REFHOLD(first_ire);
21162 				/*
21163 				 * Do not release the ire passed in
21164 				 * as the argument.
21165 				 */
21166 				ire = first_ire;
21167 			} else {
21168 				first_ire = NULL;
21169 			}
21170 		}
21171 		IRB_REFRELE(irb);
21172 
21173 		/*
21174 		 * Save the first ire; we will need to restore it
21175 		 * for the trailing frags.
21176 		 * We REFHOLD save_ire, as each iterated ire will be
21177 		 * REFRELEd.
21178 		 */
21179 		save_ire = ire;
21180 		IRE_REFHOLD(save_ire);
21181 	}
21182 
21183 	/*
21184 	 * First fragment emission loop.
21185 	 * In most cases, the emission loop below is entered only
21186 	 * once. Only in the case where the ire holds the RTF_MULTIRT
21187 	 * flag, do we loop to process all RTF_MULTIRT ires in the
21188 	 * bucket, and send the fragment through all crossed
21189 	 * RTF_MULTIRT routes.
21190 	 */
21191 	do {
21192 		if (ire->ire_flags & RTF_MULTIRT) {
21193 			/*
21194 			 * We are in a multiple send case, need to get
21195 			 * the next ire and make a copy of the packet.
21196 			 * ire1 holds here the next ire to process in the
21197 			 * bucket. If multirouting is expected,
21198 			 * any non-RTF_MULTIRT ire that has the
21199 			 * right destination address is ignored.
21200 			 *
21201 			 * We have to take into account the MTU of
21202 			 * each walked ire. max_frag is set by the
21203 			 * the caller and generally refers to
21204 			 * the primary ire entry. Here we ensure that
21205 			 * no route with a lower MTU will be used, as
21206 			 * fragments are carved once for all ires,
21207 			 * then replicated.
21208 			 */
21209 			ASSERT(irb != NULL);
21210 			IRB_REFHOLD(irb);
21211 			for (ire1 = ire->ire_next;
21212 			    ire1 != NULL;
21213 			    ire1 = ire1->ire_next) {
21214 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
21215 					continue;
21216 				if (ire1->ire_addr != ire->ire_addr)
21217 					continue;
21218 				if (ire1->ire_marks &
21219 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
21220 					continue;
21221 				/*
21222 				 * Ensure we do not exceed the MTU
21223 				 * of the next route.
21224 				 */
21225 				if (ire1->ire_max_frag < max_frag) {
21226 					ip_multirt_bad_mtu(ire1, max_frag);
21227 					continue;
21228 				}
21229 
21230 				/* Got one. */
21231 				IRE_REFHOLD(ire1);
21232 				break;
21233 			}
21234 			IRB_REFRELE(irb);
21235 
21236 			if (ire1 != NULL) {
21237 				next_mp = copyb(mp);
21238 				if ((next_mp == NULL) ||
21239 				    ((mp->b_cont != NULL) &&
21240 				    ((next_mp->b_cont =
21241 				    dupmsg(mp->b_cont)) == NULL))) {
21242 					freemsg(next_mp);
21243 					next_mp = NULL;
21244 					ire_refrele(ire1);
21245 					ire1 = NULL;
21246 				}
21247 			}
21248 
21249 			/* Last multiroute ire; don't loop anymore. */
21250 			if (ire1 == NULL) {
21251 				multirt_send = B_FALSE;
21252 			}
21253 		}
21254 
21255 		ll_hdr_len = 0;
21256 		LOCK_IRE_FP_MP(ire);
21257 		ll_hdr_mp = ire->ire_fp_mp;
21258 		if (ll_hdr_mp != NULL) {
21259 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
21260 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
21261 		} else {
21262 			ll_hdr_mp = ire->ire_dlureq_mp;
21263 		}
21264 
21265 		/* If there is a transmit header, get a copy for this frag. */
21266 		/*
21267 		 * TODO: should check db_ref before calling ip_carve_mp since
21268 		 * it might give us a dup.
21269 		 */
21270 		if (!ll_hdr_mp) {
21271 			/* No xmit header. */
21272 			xmit_mp = mp;
21273 		} else if (mp->b_datap->db_ref == 1 &&
21274 		    ll_hdr_len != 0 &&
21275 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
21276 			/* M_DATA fastpath */
21277 			mp->b_rptr -= ll_hdr_len;
21278 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
21279 			xmit_mp = mp;
21280 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
21281 			UNLOCK_IRE_FP_MP(ire);
21282 			BUMP_MIB(&ip_mib, ipOutDiscards);
21283 			freeb(hdr_mp);
21284 			freemsg(mp);
21285 			freemsg(mp_orig);
21286 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21287 			    "ip_wput_frag_end:(%S)",
21288 			    "discard");
21289 
21290 			if (multirt_send) {
21291 				ASSERT(ire1);
21292 				ASSERT(next_mp);
21293 
21294 				freemsg(next_mp);
21295 				ire_refrele(ire1);
21296 			}
21297 			if (save_ire != NULL)
21298 				IRE_REFRELE(save_ire);
21299 
21300 			if (first_ire != NULL)
21301 				ire_refrele(first_ire);
21302 			return;
21303 		} else {
21304 			xmit_mp->b_cont = mp;
21305 			/* Get priority marking, if any. */
21306 			if (DB_TYPE(xmit_mp) == M_DATA)
21307 				xmit_mp->b_band = mp->b_band;
21308 		}
21309 		UNLOCK_IRE_FP_MP(ire);
21310 		q = ire->ire_stq;
21311 		BUMP_MIB(&ip_mib, ipFragCreates);
21312 		putnext(q, xmit_mp);
21313 		if (pkt_type != OB_PKT) {
21314 			/*
21315 			 * Update the packet count of trailing
21316 			 * RTF_MULTIRT ires.
21317 			 */
21318 			UPDATE_OB_PKT_COUNT(ire);
21319 		}
21320 
21321 		if (multirt_send) {
21322 			/*
21323 			 * We are in a multiple send case; look for
21324 			 * the next ire and re-enter the loop.
21325 			 */
21326 			ASSERT(ire1);
21327 			ASSERT(next_mp);
21328 			/* REFRELE the current ire before looping */
21329 			ire_refrele(ire);
21330 			ire = ire1;
21331 			ire1 = NULL;
21332 			mp = next_mp;
21333 			next_mp = NULL;
21334 		}
21335 	} while (multirt_send);
21336 
21337 	ASSERT(ire1 == NULL);
21338 
21339 	/* Restore the original ire; we need it for the trailing frags */
21340 	if (save_ire != NULL) {
21341 		/* REFRELE the last iterated ire */
21342 		ire_refrele(ire);
21343 		/* save_ire has been REFHOLDed */
21344 		ire = save_ire;
21345 		save_ire = NULL;
21346 		q = ire->ire_stq;
21347 	}
21348 
21349 	if (pkt_type == OB_PKT) {
21350 		UPDATE_OB_PKT_COUNT(ire);
21351 	} else {
21352 		UPDATE_IB_PKT_COUNT(ire);
21353 	}
21354 
21355 	/* Advance the offset to the second frag starting point. */
21356 	offset += len;
21357 	/*
21358 	 * Update hdr_len from the copied header - there might be less options
21359 	 * in the later fragments.
21360 	 */
21361 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
21362 	/* Loop until done. */
21363 	for (;;) {
21364 		uint16_t	offset_and_flags;
21365 		uint16_t	ip_len;
21366 
21367 		if (ip_data_end - offset > len) {
21368 			/*
21369 			 * Carve off the appropriate amount from the original
21370 			 * datagram.
21371 			 */
21372 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
21373 				mp = NULL;
21374 				break;
21375 			}
21376 			/*
21377 			 * More frags after this one.  Get another copy
21378 			 * of the header.
21379 			 */
21380 			if (carve_mp->b_datap->db_ref == 1 &&
21381 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
21382 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
21383 				/* Inline IP header */
21384 				carve_mp->b_rptr -= hdr_mp->b_wptr -
21385 				    hdr_mp->b_rptr;
21386 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
21387 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
21388 				mp = carve_mp;
21389 			} else {
21390 				if (!(mp = copyb(hdr_mp))) {
21391 					freemsg(carve_mp);
21392 					break;
21393 				}
21394 				/* Get priority marking, if any. */
21395 				mp->b_band = carve_mp->b_band;
21396 				mp->b_cont = carve_mp;
21397 			}
21398 			ipha = (ipha_t *)mp->b_rptr;
21399 			offset_and_flags = IPH_MF;
21400 		} else {
21401 			/*
21402 			 * Last frag.  Consume the header. Set len to
21403 			 * the length of this last piece.
21404 			 */
21405 			len = ip_data_end - offset;
21406 
21407 			/*
21408 			 * Carve off the appropriate amount from the original
21409 			 * datagram.
21410 			 */
21411 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
21412 				mp = NULL;
21413 				break;
21414 			}
21415 			if (carve_mp->b_datap->db_ref == 1 &&
21416 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
21417 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
21418 				/* Inline IP header */
21419 				carve_mp->b_rptr -= hdr_mp->b_wptr -
21420 				    hdr_mp->b_rptr;
21421 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
21422 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
21423 				mp = carve_mp;
21424 				freeb(hdr_mp);
21425 				hdr_mp = mp;
21426 			} else {
21427 				mp = hdr_mp;
21428 				/* Get priority marking, if any. */
21429 				mp->b_band = carve_mp->b_band;
21430 				mp->b_cont = carve_mp;
21431 			}
21432 			ipha = (ipha_t *)mp->b_rptr;
21433 			/* A frag of a frag might have IPH_MF non-zero */
21434 			offset_and_flags =
21435 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
21436 			    IPH_MF;
21437 		}
21438 		offset_and_flags |= (uint16_t)(offset >> 3);
21439 		offset_and_flags |= (uint16_t)frag_flag;
21440 		/* Store the offset and flags in the IP header. */
21441 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
21442 
21443 		/* Store the length in the IP header. */
21444 		ip_len = (uint16_t)(len + hdr_len);
21445 		ipha->ipha_length = htons(ip_len);
21446 
21447 		/*
21448 		 * Set the IP header checksum.	Note that mp is just
21449 		 * the header, so this is easy to pass to ip_csum.
21450 		 */
21451 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21452 
21453 		/* Attach a transmit header, if any, and ship it. */
21454 		if (pkt_type == OB_PKT) {
21455 			UPDATE_OB_PKT_COUNT(ire);
21456 		} else {
21457 			UPDATE_IB_PKT_COUNT(ire);
21458 		}
21459 
21460 		if (ire->ire_flags & RTF_MULTIRT) {
21461 			irb = ire->ire_bucket;
21462 			ASSERT(irb != NULL);
21463 
21464 			multirt_send = B_TRUE;
21465 
21466 			/*
21467 			 * Save the original ire; we will need to restore it
21468 			 * for the tailing frags.
21469 			 */
21470 			save_ire = ire;
21471 			IRE_REFHOLD(save_ire);
21472 		}
21473 		/*
21474 		 * Emission loop for this fragment, similar
21475 		 * to what is done for the first fragment.
21476 		 */
21477 		do {
21478 			if (multirt_send) {
21479 				/*
21480 				 * We are in a multiple send case, need to get
21481 				 * the next ire and make a copy of the packet.
21482 				 */
21483 				ASSERT(irb != NULL);
21484 				IRB_REFHOLD(irb);
21485 				for (ire1 = ire->ire_next;
21486 				    ire1 != NULL;
21487 				    ire1 = ire1->ire_next) {
21488 					if (!(ire1->ire_flags & RTF_MULTIRT))
21489 						continue;
21490 					if (ire1->ire_addr != ire->ire_addr)
21491 						continue;
21492 					if (ire1->ire_marks &
21493 					    (IRE_MARK_CONDEMNED|
21494 						IRE_MARK_HIDDEN))
21495 						continue;
21496 					/*
21497 					 * Ensure we do not exceed the MTU
21498 					 * of the next route.
21499 					 */
21500 					if (ire1->ire_max_frag < max_frag) {
21501 						ip_multirt_bad_mtu(ire1,
21502 						    max_frag);
21503 						continue;
21504 					}
21505 
21506 					/* Got one. */
21507 					IRE_REFHOLD(ire1);
21508 					break;
21509 				}
21510 				IRB_REFRELE(irb);
21511 
21512 				if (ire1 != NULL) {
21513 					next_mp = copyb(mp);
21514 					if ((next_mp == NULL) ||
21515 					    ((mp->b_cont != NULL) &&
21516 					    ((next_mp->b_cont =
21517 					    dupmsg(mp->b_cont)) == NULL))) {
21518 						freemsg(next_mp);
21519 						next_mp = NULL;
21520 						ire_refrele(ire1);
21521 						ire1 = NULL;
21522 					}
21523 				}
21524 
21525 				/* Last multiroute ire; don't loop anymore. */
21526 				if (ire1 == NULL) {
21527 					multirt_send = B_FALSE;
21528 				}
21529 			}
21530 
21531 			/* Update transmit header */
21532 			ll_hdr_len = 0;
21533 			LOCK_IRE_FP_MP(ire);
21534 			ll_hdr_mp = ire->ire_fp_mp;
21535 			if (ll_hdr_mp != NULL) {
21536 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
21537 				ll_hdr_len = MBLKL(ll_hdr_mp);
21538 			} else {
21539 				ll_hdr_mp = ire->ire_dlureq_mp;
21540 			}
21541 
21542 			if (!ll_hdr_mp) {
21543 				xmit_mp = mp;
21544 			} else if (mp->b_datap->db_ref == 1 &&
21545 			    ll_hdr_len != 0 &&
21546 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
21547 				/* M_DATA fastpath */
21548 				mp->b_rptr -= ll_hdr_len;
21549 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
21550 				    ll_hdr_len);
21551 				xmit_mp = mp;
21552 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
21553 				xmit_mp->b_cont = mp;
21554 				/* Get priority marking, if any. */
21555 				if (DB_TYPE(xmit_mp) == M_DATA)
21556 					xmit_mp->b_band = mp->b_band;
21557 			} else {
21558 				/*
21559 				 * Exit both the replication and
21560 				 * fragmentation loops.
21561 				 */
21562 				UNLOCK_IRE_FP_MP(ire);
21563 				goto drop_pkt;
21564 			}
21565 			UNLOCK_IRE_FP_MP(ire);
21566 			BUMP_MIB(&ip_mib, ipFragCreates);
21567 			putnext(q, xmit_mp);
21568 
21569 			if (pkt_type != OB_PKT) {
21570 				/*
21571 				 * Update the packet count of trailing
21572 				 * RTF_MULTIRT ires.
21573 				 */
21574 				UPDATE_OB_PKT_COUNT(ire);
21575 			}
21576 
21577 			/* All done if we just consumed the hdr_mp. */
21578 			if (mp == hdr_mp) {
21579 				last_frag = B_TRUE;
21580 			}
21581 
21582 			if (multirt_send) {
21583 				/*
21584 				 * We are in a multiple send case; look for
21585 				 * the next ire and re-enter the loop.
21586 				 */
21587 				ASSERT(ire1);
21588 				ASSERT(next_mp);
21589 				/* REFRELE the current ire before looping */
21590 				ire_refrele(ire);
21591 				ire = ire1;
21592 				ire1 = NULL;
21593 				q = ire->ire_stq;
21594 				mp = next_mp;
21595 				next_mp = NULL;
21596 			}
21597 		} while (multirt_send);
21598 		/*
21599 		 * Restore the original ire; we need it for the
21600 		 * trailing frags
21601 		 */
21602 		if (save_ire != NULL) {
21603 			ASSERT(ire1 == NULL);
21604 			/* REFRELE the last iterated ire */
21605 			ire_refrele(ire);
21606 			/* save_ire has been REFHOLDed */
21607 			ire = save_ire;
21608 			q = ire->ire_stq;
21609 			save_ire = NULL;
21610 		}
21611 
21612 		if (last_frag) {
21613 			BUMP_MIB(&ip_mib, ipFragOKs);
21614 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21615 			    "ip_wput_frag_end:(%S)",
21616 			    "consumed hdr_mp");
21617 
21618 			if (first_ire != NULL)
21619 				ire_refrele(first_ire);
21620 			return;
21621 		}
21622 		/* Otherwise, advance and loop. */
21623 		offset += len;
21624 	}
21625 
21626 drop_pkt:
21627 	/* Clean up following allocation failure. */
21628 	BUMP_MIB(&ip_mib, ipOutDiscards);
21629 	freemsg(mp);
21630 	if (mp != hdr_mp)
21631 		freeb(hdr_mp);
21632 	if (mp != mp_orig)
21633 		freemsg(mp_orig);
21634 
21635 	if (save_ire != NULL)
21636 		IRE_REFRELE(save_ire);
21637 	if (first_ire != NULL)
21638 		ire_refrele(first_ire);
21639 
21640 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
21641 	    "ip_wput_frag_end:(%S)",
21642 	    "end--alloc failure");
21643 }
21644 
21645 /*
21646  * Copy the header plus those options which have the copy bit set
21647  */
21648 static mblk_t *
21649 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset)
21650 {
21651 	mblk_t	*mp;
21652 	uchar_t	*up;
21653 
21654 	/*
21655 	 * Quick check if we need to look for options without the copy bit
21656 	 * set
21657 	 */
21658 	mp = allocb(ip_wroff_extra + hdr_len, BPRI_HI);
21659 	if (!mp)
21660 		return (mp);
21661 	mp->b_rptr += ip_wroff_extra;
21662 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
21663 		bcopy(rptr, mp->b_rptr, hdr_len);
21664 		mp->b_wptr += hdr_len + ip_wroff_extra;
21665 		return (mp);
21666 	}
21667 	up  = mp->b_rptr;
21668 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
21669 	up += IP_SIMPLE_HDR_LENGTH;
21670 	rptr += IP_SIMPLE_HDR_LENGTH;
21671 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
21672 	while (hdr_len > 0) {
21673 		uint32_t optval;
21674 		uint32_t optlen;
21675 
21676 		optval = *rptr;
21677 		if (optval == IPOPT_EOL)
21678 			break;
21679 		if (optval == IPOPT_NOP)
21680 			optlen = 1;
21681 		else
21682 			optlen = rptr[1];
21683 		if (optval & IPOPT_COPY) {
21684 			bcopy(rptr, up, optlen);
21685 			up += optlen;
21686 		}
21687 		rptr += optlen;
21688 		hdr_len -= optlen;
21689 	}
21690 	/*
21691 	 * Make sure that we drop an even number of words by filling
21692 	 * with EOL to the next word boundary.
21693 	 */
21694 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
21695 	    hdr_len & 0x3; hdr_len++)
21696 		*up++ = IPOPT_EOL;
21697 	mp->b_wptr = up;
21698 	/* Update header length */
21699 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
21700 	return (mp);
21701 }
21702 
21703 /*
21704  * Delivery to local recipients including fanout to multiple recipients.
21705  * Does not do checksumming of UDP/TCP.
21706  * Note: q should be the read side queue for either the ill or conn.
21707  * Note: rq should be the read side q for the lower (ill) stream.
21708  * We don't send packets to IPPF processing, thus the last argument
21709  * to all the fanout calls are B_FALSE.
21710  */
21711 void
21712 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
21713     int fanout_flags, zoneid_t zoneid)
21714 {
21715 	uint32_t	protocol;
21716 	mblk_t		*first_mp;
21717 	boolean_t	mctl_present;
21718 	int		ire_type;
21719 #define	rptr	((uchar_t *)ipha)
21720 
21721 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
21722 	    "ip_wput_local_start: q %p", q);
21723 
21724 	if (ire != NULL) {
21725 		ire_type = ire->ire_type;
21726 	} else {
21727 		/*
21728 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
21729 		 * packet is not multicast, we can't tell the ire type.
21730 		 */
21731 		ASSERT(CLASSD(ipha->ipha_dst));
21732 		ire_type = IRE_BROADCAST;
21733 	}
21734 
21735 	first_mp = mp;
21736 	if (first_mp->b_datap->db_type == M_CTL) {
21737 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
21738 		if (!io->ipsec_out_secure) {
21739 			/*
21740 			 * This ipsec_out_t was allocated in ip_wput
21741 			 * for multicast packets to store the ill_index.
21742 			 * As this is being delivered locally, we don't
21743 			 * need this anymore.
21744 			 */
21745 			mp = first_mp->b_cont;
21746 			freeb(first_mp);
21747 			first_mp = mp;
21748 			mctl_present = B_FALSE;
21749 		} else {
21750 			mctl_present = B_TRUE;
21751 			mp = first_mp->b_cont;
21752 			ASSERT(mp != NULL);
21753 			ipsec_out_to_in(first_mp);
21754 		}
21755 	} else {
21756 		mctl_present = B_FALSE;
21757 	}
21758 
21759 	loopback_packets++;
21760 
21761 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
21762 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
21763 	if (!IS_SIMPLE_IPH(ipha)) {
21764 		ip_wput_local_options(ipha);
21765 	}
21766 
21767 	protocol = ipha->ipha_protocol;
21768 	switch (protocol) {
21769 	case IPPROTO_ICMP: {
21770 		ire_t		*ire_zone;
21771 		ilm_t		*ilm;
21772 		mblk_t		*mp1;
21773 		zoneid_t	last_zoneid;
21774 
21775 		if (CLASSD(ipha->ipha_dst) &&
21776 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
21777 			ASSERT(ire_type == IRE_BROADCAST);
21778 			/*
21779 			 * In the multicast case, applications may have joined
21780 			 * the group from different zones, so we need to deliver
21781 			 * the packet to each of them. Loop through the
21782 			 * multicast memberships structures (ilm) on the receive
21783 			 * ill and send a copy of the packet up each matching
21784 			 * one. However, we don't do this for multicasts sent on
21785 			 * the loopback interface (PHYI_LOOPBACK flag set) as
21786 			 * they must stay in the sender's zone.
21787 			 *
21788 			 * ilm_add_v6() ensures that ilms in the same zone are
21789 			 * contiguous in the ill_ilm list. We use this property
21790 			 * to avoid sending duplicates needed when two
21791 			 * applications in the same zone join the same group on
21792 			 * different logical interfaces: we ignore the ilm if
21793 			 * its zoneid is the same as the last matching one.
21794 			 * In addition, the sending of the packet for
21795 			 * ire_zoneid is delayed until all of the other ilms
21796 			 * have been exhausted.
21797 			 */
21798 			last_zoneid = -1;
21799 			ILM_WALKER_HOLD(ill);
21800 			for (ilm = ill->ill_ilm; ilm != NULL;
21801 			    ilm = ilm->ilm_next) {
21802 				if ((ilm->ilm_flags & ILM_DELETED) ||
21803 				    ipha->ipha_dst != ilm->ilm_addr ||
21804 				    ilm->ilm_zoneid == last_zoneid ||
21805 				    ilm->ilm_zoneid == zoneid ||
21806 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
21807 					continue;
21808 				mp1 = ip_copymsg(first_mp);
21809 				if (mp1 == NULL)
21810 					continue;
21811 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
21812 				    mctl_present, B_FALSE, ill,
21813 				    ilm->ilm_zoneid);
21814 				last_zoneid = ilm->ilm_zoneid;
21815 			}
21816 			ILM_WALKER_RELE(ill);
21817 			/*
21818 			 * Loopback case: the sending endpoint has
21819 			 * IP_MULTICAST_LOOP disabled, therefore we don't
21820 			 * dispatch the multicast packet to the sending zone.
21821 			 */
21822 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
21823 				freemsg(first_mp);
21824 				return;
21825 			}
21826 		} else if (ire_type == IRE_BROADCAST) {
21827 			/*
21828 			 * In the broadcast case, there may be many zones
21829 			 * which need a copy of the packet delivered to them.
21830 			 * There is one IRE_BROADCAST per broadcast address
21831 			 * and per zone; we walk those using a helper function.
21832 			 * In addition, the sending of the packet for zoneid is
21833 			 * delayed until all of the other ires have been
21834 			 * processed.
21835 			 */
21836 			IRB_REFHOLD(ire->ire_bucket);
21837 			ire_zone = NULL;
21838 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
21839 			    ire)) != NULL) {
21840 				mp1 = ip_copymsg(first_mp);
21841 				if (mp1 == NULL)
21842 					continue;
21843 
21844 				UPDATE_IB_PKT_COUNT(ire_zone);
21845 				ire_zone->ire_last_used_time = lbolt;
21846 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
21847 				    mctl_present, B_FALSE, ill,
21848 				    ire_zone->ire_zoneid);
21849 			}
21850 			IRB_REFRELE(ire->ire_bucket);
21851 		}
21852 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
21853 		    0, mctl_present, B_FALSE, ill, zoneid);
21854 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
21855 		    "ip_wput_local_end: q %p (%S)",
21856 		    q, "icmp");
21857 		return;
21858 	}
21859 	case IPPROTO_IGMP:
21860 		if (igmp_input(q, mp, ill)) {
21861 			/* Bad packet - discarded by igmp_input */
21862 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
21863 			    "ip_wput_local_end: q %p (%S)",
21864 			    q, "igmp_input--bad packet");
21865 			if (mctl_present)
21866 				freeb(first_mp);
21867 			return;
21868 		}
21869 		/*
21870 		 * igmp_input() may have pulled up the message so ipha needs to
21871 		 * be reinitialized.
21872 		 */
21873 		ipha = (ipha_t *)mp->b_rptr;
21874 		/* deliver to local raw users */
21875 		break;
21876 	case IPPROTO_ENCAP:
21877 		/*
21878 		 * This case is covered by either ip_fanout_proto, or by
21879 		 * the above security processing for self-tunneled packets.
21880 		 */
21881 		break;
21882 	case IPPROTO_UDP: {
21883 		uint16_t	*up;
21884 		uint32_t	ports;
21885 
21886 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
21887 		    UDP_PORTS_OFFSET);
21888 		/* Force a 'valid' checksum. */
21889 		up[3] = 0;
21890 
21891 		ports = *(uint32_t *)up;
21892 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
21893 		    (ire_type == IRE_BROADCAST),
21894 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
21895 		    IP_FF_SEND_SLLA | IP_FF_IP6INFO, mctl_present, B_FALSE,
21896 		    ill, zoneid);
21897 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
21898 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
21899 		return;
21900 	}
21901 	case IPPROTO_TCP: {
21902 
21903 		/*
21904 		 * For TCP, discard broadcast packets.
21905 		 */
21906 		if ((ushort_t)ire_type == IRE_BROADCAST) {
21907 			freemsg(first_mp);
21908 			BUMP_MIB(&ip_mib, ipInDiscards);
21909 			return;
21910 		}
21911 
21912 		if (mp->b_datap->db_type == M_DATA) {
21913 			/*
21914 			 * M_DATA mblk, so init mblk (chain) for no struio().
21915 			 */
21916 			mblk_t	*mp1 = mp;
21917 
21918 			do
21919 				mp1->b_datap->db_struioflag = 0;
21920 			while ((mp1 = mp1->b_cont) != NULL);
21921 		}
21922 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
21923 		    <= mp->b_wptr);
21924 		ip_fanout_tcp(q, first_mp, ill, ipha,
21925 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
21926 		    IP_FF_SYN_ADDIRE | IP_FF_IP6INFO,
21927 		    mctl_present, B_FALSE, zoneid);
21928 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
21929 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
21930 		return;
21931 	}
21932 	case IPPROTO_SCTP:
21933 	{
21934 		uint32_t	ports;
21935 
21936 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
21937 		ip_fanout_sctp(first_mp, ill, ipha, ports,
21938 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
21939 		    IP_FF_IP6INFO,
21940 		    mctl_present, B_FALSE, 0, zoneid);
21941 		return;
21942 	}
21943 
21944 	default:
21945 		break;
21946 	}
21947 	/*
21948 	 * Find a client for some other protocol.  We give
21949 	 * copies to multiple clients, if more than one is
21950 	 * bound.
21951 	 */
21952 	ip_fanout_proto(q, first_mp, ill, ipha,
21953 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
21954 	    mctl_present, B_FALSE, ill, zoneid);
21955 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
21956 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
21957 #undef	rptr
21958 }
21959 
21960 /*
21961  * Update any source route, record route, or timestamp options.
21962  * Check that we are at end of strict source route.
21963  * The options have been sanity checked by ip_wput_options().
21964  */
21965 static void
21966 ip_wput_local_options(ipha_t *ipha)
21967 {
21968 	ipoptp_t	opts;
21969 	uchar_t		*opt;
21970 	uint8_t		optval;
21971 	uint8_t		optlen;
21972 	ipaddr_t	dst;
21973 	uint32_t	ts;
21974 	ire_t		*ire;
21975 	timestruc_t	now;
21976 
21977 	ip2dbg(("ip_wput_local_options\n"));
21978 	for (optval = ipoptp_first(&opts, ipha);
21979 	    optval != IPOPT_EOL;
21980 	    optval = ipoptp_next(&opts)) {
21981 		opt = opts.ipoptp_cur;
21982 		optlen = opts.ipoptp_len;
21983 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21984 		switch (optval) {
21985 			uint32_t off;
21986 		case IPOPT_SSRR:
21987 		case IPOPT_LSRR:
21988 			off = opt[IPOPT_OFFSET];
21989 			off--;
21990 			if (optlen < IP_ADDR_LEN ||
21991 			    off > optlen - IP_ADDR_LEN) {
21992 				/* End of source route */
21993 				break;
21994 			}
21995 			/*
21996 			 * This will only happen if two consecutive entries
21997 			 * in the source route contains our address or if
21998 			 * it is a packet with a loose source route which
21999 			 * reaches us before consuming the whole source route
22000 			 */
22001 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
22002 			if (optval == IPOPT_SSRR) {
22003 				return;
22004 			}
22005 			/*
22006 			 * Hack: instead of dropping the packet truncate the
22007 			 * source route to what has been used by filling the
22008 			 * rest with IPOPT_NOP.
22009 			 */
22010 			opt[IPOPT_OLEN] = (uint8_t)off;
22011 			while (off < optlen) {
22012 				opt[off++] = IPOPT_NOP;
22013 			}
22014 			break;
22015 		case IPOPT_RR:
22016 			off = opt[IPOPT_OFFSET];
22017 			off--;
22018 			if (optlen < IP_ADDR_LEN ||
22019 			    off > optlen - IP_ADDR_LEN) {
22020 				/* No more room - ignore */
22021 				ip1dbg((
22022 				    "ip_wput_forward_options: end of RR\n"));
22023 				break;
22024 			}
22025 			dst = htonl(INADDR_LOOPBACK);
22026 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
22027 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
22028 			break;
22029 		case IPOPT_TS:
22030 			/* Insert timestamp if there is romm */
22031 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
22032 			case IPOPT_TS_TSONLY:
22033 				off = IPOPT_TS_TIMELEN;
22034 				break;
22035 			case IPOPT_TS_PRESPEC:
22036 			case IPOPT_TS_PRESPEC_RFC791:
22037 				/* Verify that the address matched */
22038 				off = opt[IPOPT_OFFSET] - 1;
22039 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
22040 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
22041 				    NULL, ALL_ZONES, MATCH_IRE_TYPE);
22042 				if (ire == NULL) {
22043 					/* Not for us */
22044 					break;
22045 				}
22046 				ire_refrele(ire);
22047 				/* FALLTHRU */
22048 			case IPOPT_TS_TSANDADDR:
22049 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
22050 				break;
22051 			default:
22052 				/*
22053 				 * ip_*put_options should have already
22054 				 * dropped this packet.
22055 				 */
22056 				cmn_err(CE_PANIC, "ip_wput_local_options: "
22057 				    "unknown IT - bug in ip_wput_options?\n");
22058 				return;	/* Keep "lint" happy */
22059 			}
22060 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
22061 				/* Increase overflow counter */
22062 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
22063 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
22064 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
22065 				    (off << 4);
22066 				break;
22067 			}
22068 			off = opt[IPOPT_OFFSET] - 1;
22069 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
22070 			case IPOPT_TS_PRESPEC:
22071 			case IPOPT_TS_PRESPEC_RFC791:
22072 			case IPOPT_TS_TSANDADDR:
22073 				dst = htonl(INADDR_LOOPBACK);
22074 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
22075 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
22076 				/* FALLTHRU */
22077 			case IPOPT_TS_TSONLY:
22078 				off = opt[IPOPT_OFFSET] - 1;
22079 				/* Compute # of milliseconds since midnight */
22080 				gethrestime(&now);
22081 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
22082 				    now.tv_nsec / (NANOSEC / MILLISEC);
22083 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
22084 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
22085 				break;
22086 			}
22087 			break;
22088 		}
22089 	}
22090 }
22091 
22092 /*
22093  * Send out a multicast packet on interface ipif.
22094  * The sender does not have an conn.
22095  * Caller verifies that this isn't a PHYI_LOOPBACK.
22096  */
22097 void
22098 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif)
22099 {
22100 	ipha_t	*ipha;
22101 	ire_t	*ire;
22102 	ipaddr_t	dst;
22103 	mblk_t		*first_mp;
22104 
22105 	/* igmp_sendpkt always allocates a ipsec_out_t */
22106 	ASSERT(mp->b_datap->db_type == M_CTL);
22107 	ASSERT(!ipif->ipif_isv6);
22108 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
22109 
22110 	first_mp = mp;
22111 	mp = first_mp->b_cont;
22112 	ASSERT(mp->b_datap->db_type == M_DATA);
22113 	ipha = (ipha_t *)mp->b_rptr;
22114 
22115 	/*
22116 	 * Find an IRE which matches the destination and the outgoing
22117 	 * queue (i.e. the outgoing interface.)
22118 	 */
22119 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
22120 		dst = ipif->ipif_pp_dst_addr;
22121 	else
22122 		dst = ipha->ipha_dst;
22123 	/*
22124 	 * The source address has already been initialized by the
22125 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
22126 	 * be sufficient rather than MATCH_IRE_IPIF.
22127 	 *
22128 	 * This function is used for sending IGMP packets. We need
22129 	 * to make sure that we send the packet out of the interface
22130 	 * (ipif->ipif_ill) where we joined the group. This is to
22131 	 * prevent from switches doing IGMP snooping to send us multicast
22132 	 * packets for a given group on the interface we have joined.
22133 	 * If we can't find an ire, igmp_sendpkt has already initialized
22134 	 * ipsec_out_attach_if so that this will not be load spread in
22135 	 * ip_newroute_ipif.
22136 	 */
22137 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MATCH_IRE_ILL);
22138 	if (!ire) {
22139 		/*
22140 		 * Mark this packet to make it be delivered to
22141 		 * ip_wput_ire after the new ire has been
22142 		 * created.
22143 		 */
22144 		mp->b_prev = NULL;
22145 		mp->b_next = NULL;
22146 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC);
22147 		return;
22148 	}
22149 
22150 	/*
22151 	 * Honor the RTF_SETSRC flag; this is the only case
22152 	 * where we force this addr whatever the current src addr is,
22153 	 * because this address is set by igmp_sendpkt(), and
22154 	 * cannot be specified by any user.
22155 	 */
22156 	if (ire->ire_flags & RTF_SETSRC) {
22157 		ipha->ipha_src = ire->ire_src_addr;
22158 	}
22159 
22160 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE);
22161 }
22162 
22163 /*
22164  * NOTE : This function does not ire_refrele the ire argument passed in.
22165  *
22166  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
22167  * failure. The ire_fp_mp can vanish any time in the case of IRE_MIPRTUN
22168  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
22169  * the ire_lock to access the ire_fp_mp in this case.
22170  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
22171  * prepending a fastpath message IPQoS processing must precede it, we also set
22172  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
22173  * (IPQoS might have set the b_band for CoS marking).
22174  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
22175  * must follow it so that IPQoS can mark the dl_priority field for CoS
22176  * marking, if needed.
22177  */
22178 static mblk_t *
22179 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
22180 {
22181 	uint_t	hlen;
22182 	ipha_t *ipha;
22183 	mblk_t *mp1;
22184 	boolean_t qos_done = B_FALSE;
22185 	uchar_t	*ll_hdr;
22186 
22187 #define	rptr	((uchar_t *)ipha)
22188 
22189 	ipha = (ipha_t *)mp->b_rptr;
22190 	hlen = 0;
22191 	LOCK_IRE_FP_MP(ire);
22192 	if ((mp1 = ire->ire_fp_mp) != NULL) {
22193 		ASSERT(DB_TYPE(mp1) == M_DATA);
22194 		/* Initiate IPPF processing */
22195 		if ((proc != 0) && IPP_ENABLED(proc)) {
22196 			UNLOCK_IRE_FP_MP(ire);
22197 			ip_process(proc, &mp, ill_index);
22198 			if (mp == NULL)
22199 				return (NULL);
22200 
22201 			ipha = (ipha_t *)mp->b_rptr;
22202 			LOCK_IRE_FP_MP(ire);
22203 			if ((mp1 = ire->ire_fp_mp) == NULL) {
22204 				qos_done = B_TRUE;
22205 				goto no_fp_mp;
22206 			}
22207 			ASSERT(DB_TYPE(mp1) == M_DATA);
22208 		}
22209 		hlen = MBLKL(mp1);
22210 		/*
22211 		 * Check if we have enough room to prepend fastpath
22212 		 * header
22213 		 */
22214 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
22215 			ll_hdr = rptr - hlen;
22216 			bcopy(mp1->b_rptr, ll_hdr, hlen);
22217 			/* XXX ipha is not aligned here */
22218 			ipha = (ipha_t *)(rptr - hlen);
22219 			/*
22220 			 * Set the b_rptr to the start of the link layer
22221 			 * header
22222 			 */
22223 			mp->b_rptr = rptr;
22224 			mp1 = mp;
22225 		} else {
22226 			mp1 = copyb(mp1);
22227 			if (mp1 == NULL)
22228 				goto unlock_err;
22229 			mp1->b_band = mp->b_band;
22230 			mp1->b_cont = mp;
22231 			/*
22232 			 * XXX disable ICK_VALID and compute checksum
22233 			 * here; can happen if ire_fp_mp changes and
22234 			 * it can't be copied now due to insufficient
22235 			 * space. (unlikely, fp mp can change, but it
22236 			 * does not increase in length)
22237 			 */
22238 		}
22239 		UNLOCK_IRE_FP_MP(ire);
22240 	} else {
22241 no_fp_mp:
22242 		mp1 = copyb(ire->ire_dlureq_mp);
22243 		if (mp1 == NULL) {
22244 unlock_err:
22245 			UNLOCK_IRE_FP_MP(ire);
22246 			freemsg(mp);
22247 			return (NULL);
22248 		}
22249 		UNLOCK_IRE_FP_MP(ire);
22250 		mp1->b_cont = mp;
22251 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc)) {
22252 			ip_process(proc, &mp1, ill_index);
22253 			if (mp1 == NULL)
22254 				return (NULL);
22255 		}
22256 	}
22257 	return (mp1);
22258 #undef rptr
22259 }
22260 
22261 /*
22262  * Finish the outbound IPsec processing for an IPv6 packet. This function
22263  * is called from ipsec_out_process() if the IPsec packet was processed
22264  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
22265  * asynchronously.
22266  */
22267 void
22268 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
22269     ire_t *ire_arg)
22270 {
22271 	in6_addr_t *v6dstp;
22272 	ire_t *ire;
22273 	mblk_t *mp;
22274 	uint_t	ill_index;
22275 	ipsec_out_t *io;
22276 	boolean_t attach_if, hwaccel;
22277 	uint32_t flags = IP6_NO_IPPOLICY;
22278 	int match_flags;
22279 	zoneid_t zoneid;
22280 	boolean_t ill_need_rele = B_FALSE;
22281 	boolean_t ire_need_rele = B_FALSE;
22282 
22283 	mp = ipsec_mp->b_cont;
22284 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
22285 	ill_index = io->ipsec_out_ill_index;
22286 	if (io->ipsec_out_reachable) {
22287 		flags |= IPV6_REACHABILITY_CONFIRMATION;
22288 	}
22289 	attach_if = io->ipsec_out_attach_if;
22290 	hwaccel = io->ipsec_out_accelerated;
22291 	zoneid = io->ipsec_out_zoneid;
22292 	ASSERT(zoneid != ALL_ZONES);
22293 	match_flags = MATCH_IRE_ILL_GROUP;
22294 	/* Multicast addresses should have non-zero ill_index. */
22295 	v6dstp = &ip6h->ip6_dst;
22296 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
22297 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
22298 	ASSERT(!attach_if || ill_index != 0);
22299 	if (ill_index != 0) {
22300 		if (ill == NULL) {
22301 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
22302 			    B_TRUE);
22303 
22304 			/* Failure case frees things for us. */
22305 			if (ill == NULL)
22306 				return;
22307 
22308 			ill_need_rele = B_TRUE;
22309 		}
22310 		/*
22311 		 * If this packet needs to go out on a particular interface
22312 		 * honor it.
22313 		 */
22314 		if (attach_if) {
22315 			match_flags = MATCH_IRE_ILL;
22316 
22317 			/*
22318 			 * Check if we need an ire that will not be
22319 			 * looked up by anybody else i.e. HIDDEN.
22320 			 */
22321 			if (ill_is_probeonly(ill)) {
22322 				match_flags |= MATCH_IRE_MARK_HIDDEN;
22323 			}
22324 		}
22325 	}
22326 	ASSERT(mp != NULL);
22327 
22328 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
22329 		boolean_t unspec_src;
22330 		ipif_t	*ipif;
22331 
22332 		/*
22333 		 * Use the ill_index to get the right ill.
22334 		 */
22335 		unspec_src = io->ipsec_out_unspec_src;
22336 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
22337 		if (ipif == NULL) {
22338 			if (ill_need_rele)
22339 				ill_refrele(ill);
22340 			freemsg(ipsec_mp);
22341 			return;
22342 		}
22343 
22344 		if (ire_arg != NULL) {
22345 			ire = ire_arg;
22346 		} else {
22347 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
22348 			    zoneid, match_flags);
22349 			ire_need_rele = B_TRUE;
22350 		}
22351 		if (ire != NULL) {
22352 			ipif_refrele(ipif);
22353 			/*
22354 			 * XXX Do the multicast forwarding now, as the IPSEC
22355 			 * processing has been done.
22356 			 */
22357 			goto send;
22358 		}
22359 
22360 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
22361 		mp->b_prev = NULL;
22362 		mp->b_next = NULL;
22363 
22364 		/*
22365 		 * If the IPsec packet was processed asynchronously,
22366 		 * drop it now.
22367 		 */
22368 		if (q == NULL) {
22369 			if (ill_need_rele)
22370 				ill_refrele(ill);
22371 			freemsg(ipsec_mp);
22372 			return;
22373 		}
22374 
22375 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
22376 		    unspec_src, zoneid);
22377 		ipif_refrele(ipif);
22378 	} else {
22379 		if (attach_if) {
22380 			ipif_t	*ipif;
22381 
22382 			ipif = ipif_get_next_ipif(NULL, ill);
22383 			if (ipif == NULL) {
22384 				if (ill_need_rele)
22385 					ill_refrele(ill);
22386 				freemsg(ipsec_mp);
22387 				return;
22388 			}
22389 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
22390 			    zoneid, match_flags);
22391 			ire_need_rele = B_TRUE;
22392 			ipif_refrele(ipif);
22393 		} else {
22394 			if (ire_arg != NULL) {
22395 				ire = ire_arg;
22396 			} else {
22397 				ire = ire_cache_lookup_v6(v6dstp, zoneid);
22398 				ire_need_rele = B_TRUE;
22399 			}
22400 		}
22401 		if (ire != NULL)
22402 			goto send;
22403 		/*
22404 		 * ire disappeared underneath.
22405 		 *
22406 		 * What we need to do here is the ip_newroute
22407 		 * logic to get the ire without doing the IPSEC
22408 		 * processing. Follow the same old path. But this
22409 		 * time, ip_wput or ire_add_then_send will call us
22410 		 * directly as all the IPSEC operations are done.
22411 		 */
22412 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
22413 		mp->b_prev = NULL;
22414 		mp->b_next = NULL;
22415 
22416 		/*
22417 		 * If the IPsec packet was processed asynchronously,
22418 		 * drop it now.
22419 		 */
22420 		if (q == NULL) {
22421 			if (ill_need_rele)
22422 				ill_refrele(ill);
22423 			freemsg(ipsec_mp);
22424 			return;
22425 		}
22426 
22427 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
22428 		    zoneid);
22429 	}
22430 	if (ill != NULL && ill_need_rele)
22431 		ill_refrele(ill);
22432 	return;
22433 send:
22434 	if (ill != NULL && ill_need_rele)
22435 		ill_refrele(ill);
22436 
22437 	/* Local delivery */
22438 	if (ire->ire_stq == NULL) {
22439 		ASSERT(q != NULL);
22440 		ip_wput_local_v6(RD(q), ire->ire_ipif->ipif_ill, ip6h, ipsec_mp,
22441 		    ire, 0);
22442 		if (ire_need_rele)
22443 			ire_refrele(ire);
22444 		return;
22445 	}
22446 	/*
22447 	 * Everything is done. Send it out on the wire.
22448 	 * We force the insertion of a fragment header using the
22449 	 * IPH_FRAG_HDR flag in two cases:
22450 	 * - after reception of an ICMPv6 "packet too big" message
22451 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
22452 	 * - for multirouted IPv6 packets, so that the receiver can
22453 	 *   discard duplicates according to their fragment identifier
22454 	 */
22455 	/* XXX fix flow control problems. */
22456 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
22457 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
22458 		if (hwaccel) {
22459 			/*
22460 			 * hardware acceleration does not handle these
22461 			 * "slow path" cases.
22462 			 */
22463 			/* IPsec KSTATS: should bump bean counter here. */
22464 			if (ire_need_rele)
22465 				ire_refrele(ire);
22466 			freemsg(ipsec_mp);
22467 			return;
22468 		}
22469 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
22470 		    (mp->b_cont ? msgdsize(mp) :
22471 		    mp->b_wptr - (uchar_t *)ip6h)) {
22472 			/* IPsec KSTATS: should bump bean counter here. */
22473 			ip0dbg(("Packet length mismatch: %d, %ld\n",
22474 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
22475 			    msgdsize(mp)));
22476 			if (ire_need_rele)
22477 				ire_refrele(ire);
22478 			freemsg(ipsec_mp);
22479 			return;
22480 		}
22481 		ASSERT(mp->b_prev == NULL);
22482 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
22483 		    ntohs(ip6h->ip6_plen) +
22484 		    IPV6_HDR_LEN, ire->ire_max_frag));
22485 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
22486 		    ire->ire_max_frag);
22487 	} else {
22488 		UPDATE_OB_PKT_COUNT(ire);
22489 		ire->ire_last_used_time = lbolt;
22490 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
22491 	}
22492 	if (ire_need_rele)
22493 		ire_refrele(ire);
22494 	freeb(ipsec_mp);
22495 }
22496 
22497 void
22498 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
22499 {
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 		freemsg(mp);
22509 		return;
22510 	}
22511 
22512 	/*
22513 	 * It's an IPsec packet that must be
22514 	 * accelerated by the Provider, and the
22515 	 * outbound ill is IPsec acceleration capable.
22516 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
22517 	 * to the ill.
22518 	 * IPsec KSTATS: should bump packet counter here.
22519 	 */
22520 
22521 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
22522 	if (hada_mp == NULL) {
22523 		/* IPsec KSTATS: should bump packet counter here. */
22524 		freemsg(mp);
22525 		return;
22526 	}
22527 
22528 	hada_mp->b_datap->db_type = M_CTL;
22529 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
22530 	hada_mp->b_cont = mp;
22531 
22532 	hada = (da_ipsec_t *)hada_mp->b_rptr;
22533 	bzero(hada, sizeof (da_ipsec_t));
22534 	hada->da_type = IPHADA_M_CTL;
22535 
22536 	putnext(q, hada_mp);
22537 }
22538 
22539 /*
22540  * Finish the outbound IPsec processing. This function is called from
22541  * ipsec_out_process() if the IPsec packet was processed
22542  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
22543  * asynchronously.
22544  */
22545 void
22546 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
22547     ire_t *ire_arg)
22548 {
22549 	uint32_t v_hlen_tos_len;
22550 	ipaddr_t	dst;
22551 	ipif_t	*ipif = NULL;
22552 	ire_t *ire;
22553 	ire_t *ire1 = NULL;
22554 	mblk_t *next_mp = NULL;
22555 	uint32_t max_frag;
22556 	boolean_t multirt_send = B_FALSE;
22557 	mblk_t *mp;
22558 	mblk_t *mp1;
22559 	uint_t	ill_index;
22560 	ipsec_out_t *io;
22561 	boolean_t attach_if;
22562 	int match_flags, offset;
22563 	irb_t *irb = NULL;
22564 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
22565 	zoneid_t zoneid;
22566 	uint32_t cksum;
22567 	uint16_t *up;
22568 	/* Hack until the UDP merge into IP happens. */
22569 	extern boolean_t udp_compute_checksum(void);
22570 #ifdef	_BIG_ENDIAN
22571 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22572 #else
22573 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22574 #endif
22575 
22576 	mp = ipsec_mp->b_cont;
22577 	ASSERT(mp != NULL);
22578 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22579 	dst = ipha->ipha_dst;
22580 
22581 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
22582 	ill_index = io->ipsec_out_ill_index;
22583 	attach_if = io->ipsec_out_attach_if;
22584 	zoneid = io->ipsec_out_zoneid;
22585 	ASSERT(zoneid != ALL_ZONES);
22586 	match_flags = MATCH_IRE_ILL_GROUP;
22587 	if (ill_index != 0) {
22588 		if (ill == NULL) {
22589 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
22590 			    ill_index, B_FALSE);
22591 
22592 			/* Failure case frees things for us. */
22593 			if (ill == NULL)
22594 				return;
22595 
22596 			ill_need_rele = B_TRUE;
22597 		}
22598 		/*
22599 		 * If this packet needs to go out on a particular interface
22600 		 * honor it.
22601 		 */
22602 		if (attach_if) {
22603 			match_flags = MATCH_IRE_ILL;
22604 
22605 			/*
22606 			 * Check if we need an ire that will not be
22607 			 * looked up by anybody else i.e. HIDDEN.
22608 			 */
22609 			if (ill_is_probeonly(ill)) {
22610 				match_flags |= MATCH_IRE_MARK_HIDDEN;
22611 			}
22612 		}
22613 	}
22614 
22615 	if (CLASSD(dst)) {
22616 		boolean_t conn_dontroute;
22617 		/*
22618 		 * Use the ill_index to get the right ipif.
22619 		 */
22620 		conn_dontroute = io->ipsec_out_dontroute;
22621 		if (ill_index == 0)
22622 			ipif = ipif_lookup_group(dst, zoneid);
22623 		else
22624 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
22625 		if (ipif == NULL) {
22626 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
22627 			    " multicast\n"));
22628 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
22629 			freemsg(ipsec_mp);
22630 			goto done;
22631 		}
22632 		/*
22633 		 * ipha_src has already been intialized with the
22634 		 * value of the ipif in ip_wput. All we need now is
22635 		 * an ire to send this downstream.
22636 		 */
22637 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, match_flags);
22638 		if (ire != NULL) {
22639 			ill_t *ill1;
22640 			/*
22641 			 * Do the multicast forwarding now, as the IPSEC
22642 			 * processing has been done.
22643 			 */
22644 			if (ip_g_mrouter && !conn_dontroute &&
22645 			    (ill1 = ire_to_ill(ire))) {
22646 				if (ip_mforward(ill1, ipha, mp)) {
22647 					freemsg(ipsec_mp);
22648 					ip1dbg(("ip_wput_ipsec_out: mforward "
22649 					    "failed\n"));
22650 					ire_refrele(ire);
22651 					goto done;
22652 				}
22653 			}
22654 			goto send;
22655 		}
22656 
22657 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
22658 		mp->b_prev = NULL;
22659 		mp->b_next = NULL;
22660 
22661 		/*
22662 		 * If the IPsec packet was processed asynchronously,
22663 		 * drop it now.
22664 		 */
22665 		if (q == NULL) {
22666 			freemsg(ipsec_mp);
22667 			goto done;
22668 		}
22669 
22670 		/*
22671 		 * We may be using a wrong ipif to create the ire.
22672 		 * But it is okay as the source address is assigned
22673 		 * for the packet already. Next outbound packet would
22674 		 * create the IRE with the right IPIF in ip_wput.
22675 		 *
22676 		 * Also handle RTF_MULTIRT routes.
22677 		 */
22678 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT);
22679 	} else {
22680 		if (attach_if) {
22681 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
22682 			    zoneid, match_flags);
22683 		} else {
22684 			if (ire_arg != NULL) {
22685 				ire = ire_arg;
22686 				ire_need_rele = B_FALSE;
22687 			} else {
22688 				ire = ire_cache_lookup(dst, zoneid);
22689 			}
22690 		}
22691 		if (ire != NULL) {
22692 			goto send;
22693 		}
22694 
22695 		/*
22696 		 * ire disappeared underneath.
22697 		 *
22698 		 * What we need to do here is the ip_newroute
22699 		 * logic to get the ire without doing the IPSEC
22700 		 * processing. Follow the same old path. But this
22701 		 * time, ip_wput or ire_add_then_put will call us
22702 		 * directly as all the IPSEC operations are done.
22703 		 */
22704 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
22705 		mp->b_prev = NULL;
22706 		mp->b_next = NULL;
22707 
22708 		/*
22709 		 * If the IPsec packet was processed asynchronously,
22710 		 * drop it now.
22711 		 */
22712 		if (q == NULL) {
22713 			freemsg(ipsec_mp);
22714 			goto done;
22715 		}
22716 
22717 		/*
22718 		 * Since we're going through ip_newroute() again, we
22719 		 * need to make sure we don't:
22720 		 *
22721 		 *	1.) Trigger the ASSERT() with the ipha_ident
22722 		 *	    overloading.
22723 		 *	2.) Redo transport-layer checksumming, since we've
22724 		 *	    already done all that to get this far.
22725 		 *
22726 		 * The easiest way not do either of the above is to set
22727 		 * the ipha_ident field to IP_HDR_INCLUDED.
22728 		 */
22729 		ipha->ipha_ident = IP_HDR_INCLUDED;
22730 		ip_newroute(q, ipsec_mp, dst, NULL,
22731 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL));
22732 	}
22733 	goto done;
22734 send:
22735 	if (ipha->ipha_protocol == IPPROTO_UDP && udp_compute_checksum()) {
22736 		/*
22737 		 * ESP NAT-Traversal packet.
22738 		 *
22739 		 * Just do software checksum for now.
22740 		 */
22741 
22742 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
22743 		IP_STAT(ip_out_sw_cksum);
22744 #define	iphs	((uint16_t *)ipha)
22745 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
22746 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
22747 		    IP_SIMPLE_HDR_LENGTH);
22748 #undef iphs
22749 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
22750 			cksum = 0xFFFF;
22751 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
22752 			if (mp1->b_wptr - mp1->b_rptr >=
22753 			    offset + sizeof (uint16_t)) {
22754 				up = (uint16_t *)(mp1->b_rptr + offset);
22755 				*up = cksum;
22756 				break;	/* out of for loop */
22757 			} else {
22758 				offset -= (mp->b_wptr - mp->b_rptr);
22759 			}
22760 	} /* Otherwise, just keep the all-zero checksum. */
22761 
22762 	if (ire->ire_stq == NULL) {
22763 		/*
22764 		 * Loopbacks go through ip_wput_local except for one case.
22765 		 * We come here if we generate a icmp_frag_needed message
22766 		 * after IPSEC processing is over. When this function calls
22767 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
22768 		 * icmp_frag_needed. The message generated comes back here
22769 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
22770 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
22771 		 * source address as it is usually set in ip_wput_ire. As
22772 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
22773 		 * and we end up here. We can't enter ip_wput_ire once the
22774 		 * IPSEC processing is over and hence we need to do it here.
22775 		 */
22776 		ASSERT(q != NULL);
22777 		UPDATE_OB_PKT_COUNT(ire);
22778 		ire->ire_last_used_time = lbolt;
22779 		if (ipha->ipha_src == 0)
22780 			ipha->ipha_src = ire->ire_src_addr;
22781 		ip_wput_local(RD(q), ire->ire_ipif->ipif_ill, ipha, ipsec_mp,
22782 		    ire, 0, zoneid);
22783 		if (ire_need_rele)
22784 			ire_refrele(ire);
22785 		goto done;
22786 	}
22787 
22788 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
22789 		/*
22790 		 * We are through with IPSEC processing.
22791 		 * Fragment this and send it on the wire.
22792 		 */
22793 		if (io->ipsec_out_accelerated) {
22794 			/*
22795 			 * The packet has been accelerated but must
22796 			 * be fragmented. This should not happen
22797 			 * since AH and ESP must not accelerate
22798 			 * packets that need fragmentation, however
22799 			 * the configuration could have changed
22800 			 * since the AH or ESP processing.
22801 			 * Drop packet.
22802 			 * IPsec KSTATS: bump bean counter here.
22803 			 */
22804 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
22805 			    "fragmented accelerated packet!\n"));
22806 			freemsg(ipsec_mp);
22807 		} else {
22808 			ip_wput_ire_fragmentit(ipsec_mp, ire);
22809 		}
22810 		if (ire_need_rele)
22811 			ire_refrele(ire);
22812 		goto done;
22813 	}
22814 
22815 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
22816 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
22817 	    (void *)ire->ire_ipif, (void *)ipif));
22818 
22819 	/*
22820 	 * Multiroute the secured packet, unless IPsec really
22821 	 * requires the packet to go out only through a particular
22822 	 * interface.
22823 	 */
22824 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
22825 		ire_t *first_ire;
22826 		irb = ire->ire_bucket;
22827 		ASSERT(irb != NULL);
22828 		/*
22829 		 * This ire has been looked up as the one that
22830 		 * goes through the given ipif;
22831 		 * make sure we do not omit any other multiroute ire
22832 		 * that may be present in the bucket before this one.
22833 		 */
22834 		IRB_REFHOLD(irb);
22835 		for (first_ire = irb->irb_ire;
22836 		    first_ire != NULL;
22837 		    first_ire = first_ire->ire_next) {
22838 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22839 			    (first_ire->ire_addr == ire->ire_addr) &&
22840 			    !(first_ire->ire_marks &
22841 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
22842 				break;
22843 		}
22844 
22845 		if ((first_ire != NULL) && (first_ire != ire)) {
22846 			/*
22847 			 * Don't change the ire if the packet must
22848 			 * be fragmented if sent via this new one.
22849 			 */
22850 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
22851 				IRE_REFHOLD(first_ire);
22852 				if (ire_need_rele)
22853 					ire_refrele(ire);
22854 				else
22855 					ire_need_rele = B_TRUE;
22856 				ire = first_ire;
22857 			}
22858 		}
22859 		IRB_REFRELE(irb);
22860 
22861 		multirt_send = B_TRUE;
22862 		max_frag = ire->ire_max_frag;
22863 	} else {
22864 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
22865 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
22866 			    "flag, attach_if %d\n", attach_if));
22867 		}
22868 	}
22869 
22870 	/*
22871 	 * In most cases, the emission loop below is entered only once.
22872 	 * Only in the case where the ire holds the RTF_MULTIRT
22873 	 * flag, we loop to process all RTF_MULTIRT ires in the
22874 	 * bucket, and send the packet through all crossed
22875 	 * RTF_MULTIRT routes.
22876 	 */
22877 	do {
22878 		if (multirt_send) {
22879 			/*
22880 			 * ire1 holds here the next ire to process in the
22881 			 * bucket. If multirouting is expected,
22882 			 * any non-RTF_MULTIRT ire that has the
22883 			 * right destination address is ignored.
22884 			 */
22885 			ASSERT(irb != NULL);
22886 			IRB_REFHOLD(irb);
22887 			for (ire1 = ire->ire_next;
22888 			    ire1 != NULL;
22889 			    ire1 = ire1->ire_next) {
22890 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22891 					continue;
22892 				if (ire1->ire_addr != ire->ire_addr)
22893 					continue;
22894 				if (ire1->ire_marks &
22895 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22896 					continue;
22897 				/* No loopback here */
22898 				if (ire1->ire_stq == NULL)
22899 					continue;
22900 				/*
22901 				 * Ensure we do not exceed the MTU
22902 				 * of the next route.
22903 				 */
22904 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
22905 					ip_multirt_bad_mtu(ire1, max_frag);
22906 					continue;
22907 				}
22908 
22909 				IRE_REFHOLD(ire1);
22910 				break;
22911 			}
22912 			IRB_REFRELE(irb);
22913 			if (ire1 != NULL) {
22914 				/*
22915 				 * We are in a multiple send case, need to
22916 				 * make a copy of the packet.
22917 				 */
22918 				next_mp = copymsg(ipsec_mp);
22919 				if (next_mp == NULL) {
22920 					ire_refrele(ire1);
22921 					ire1 = NULL;
22922 				}
22923 			}
22924 		}
22925 
22926 		/* Everything is done. Send it out on the wire */
22927 		mp1 = ip_wput_attach_llhdr(mp, ire, 0, 0);
22928 		if (mp1 == NULL) {
22929 			BUMP_MIB(&ip_mib, ipOutDiscards);
22930 			freemsg(ipsec_mp);
22931 			if (ire_need_rele)
22932 				ire_refrele(ire);
22933 			if (ire1 != NULL) {
22934 				ire_refrele(ire1);
22935 				freemsg(next_mp);
22936 			}
22937 			goto done;
22938 		}
22939 		UPDATE_OB_PKT_COUNT(ire);
22940 		ire->ire_last_used_time = lbolt;
22941 		if (!io->ipsec_out_accelerated) {
22942 			putnext(ire->ire_stq, mp1);
22943 		} else {
22944 			/*
22945 			 * Safety Pup says: make sure this is going to
22946 			 * the right interface!
22947 			 */
22948 			ill_t *ill1 = (ill_t *)ire->ire_stq->q_ptr;
22949 			int ifindex = ill1->ill_phyint->phyint_ifindex;
22950 
22951 			if (ifindex != io->ipsec_out_capab_ill_index) {
22952 				/* IPsec kstats: bump lose counter */
22953 				freemsg(mp1);
22954 			} else {
22955 				ipsec_hw_putnext(ire->ire_stq, mp1);
22956 			}
22957 		}
22958 
22959 		freeb(ipsec_mp);
22960 		if (ire_need_rele)
22961 			ire_refrele(ire);
22962 
22963 		if (ire1 != NULL) {
22964 			ire = ire1;
22965 			ire_need_rele = B_TRUE;
22966 			ASSERT(next_mp);
22967 			ipsec_mp = next_mp;
22968 			mp = ipsec_mp->b_cont;
22969 			ire1 = NULL;
22970 			next_mp = NULL;
22971 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
22972 		} else {
22973 			multirt_send = B_FALSE;
22974 		}
22975 	} while (multirt_send);
22976 done:
22977 	if (ill != NULL && ill_need_rele)
22978 		ill_refrele(ill);
22979 	if (ipif != NULL)
22980 		ipif_refrele(ipif);
22981 }
22982 
22983 /*
22984  * Get the ill corresponding to the specified ire, and compare its
22985  * capabilities with the protocol and algorithms specified by the
22986  * the SA obtained from ipsec_out. If they match, annotate the
22987  * ipsec_out structure to indicate that the packet needs acceleration.
22988  *
22989  *
22990  * A packet is eligible for outbound hardware acceleration if the
22991  * following conditions are satisfied:
22992  *
22993  * 1. the packet will not be fragmented
22994  * 2. the provider supports the algorithm
22995  * 3. there is no pending control message being exchanged
22996  * 4. snoop is not attached
22997  * 5. the destination address is not a broadcast or multicast address.
22998  *
22999  * Rationale:
23000  *	- Hardware drivers do not support fragmentation with
23001  *	  the current interface.
23002  *	- snoop, multicast, and broadcast may result in exposure of
23003  *	  a cleartext datagram.
23004  * We check all five of these conditions here.
23005  *
23006  * XXX would like to nuke "ire_t *" parameter here; problem is that
23007  * IRE is only way to figure out if a v4 address is a broadcast and
23008  * thus ineligible for acceleration...
23009  */
23010 static void
23011 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
23012 {
23013 	ipsec_out_t *io;
23014 	mblk_t *data_mp;
23015 	uint_t plen, overhead;
23016 
23017 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
23018 		return;
23019 
23020 	if (ill == NULL)
23021 		return;
23022 
23023 	/*
23024 	 * Destination address is a broadcast or multicast.  Punt.
23025 	 */
23026 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
23027 	    IRE_LOCAL)))
23028 		return;
23029 
23030 	data_mp = ipsec_mp->b_cont;
23031 
23032 	if (ill->ill_isv6) {
23033 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
23034 
23035 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
23036 			return;
23037 
23038 		plen = ip6h->ip6_plen;
23039 	} else {
23040 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
23041 
23042 		if (CLASSD(ipha->ipha_dst))
23043 			return;
23044 
23045 		plen = ipha->ipha_length;
23046 	}
23047 	/*
23048 	 * Is there a pending DLPI control message being exchanged
23049 	 * between IP/IPsec and the DLS Provider? If there is, it
23050 	 * could be a SADB update, and the state of the DLS Provider
23051 	 * SADB might not be in sync with the SADB maintained by
23052 	 * IPsec. To avoid dropping packets or using the wrong keying
23053 	 * material, we do not accelerate this packet.
23054 	 */
23055 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
23056 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
23057 		    "ill_dlpi_pending! don't accelerate packet\n"));
23058 		return;
23059 	}
23060 
23061 	/*
23062 	 * Is the Provider in promiscous mode? If it does, we don't
23063 	 * accelerate the packet since it will bounce back up to the
23064 	 * listeners in the clear.
23065 	 */
23066 	if (ill->ill_promisc_on_phys) {
23067 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
23068 		    "ill in promiscous mode, don't accelerate packet\n"));
23069 		return;
23070 	}
23071 
23072 	/*
23073 	 * Will the packet require fragmentation?
23074 	 */
23075 
23076 	/*
23077 	 * IPsec ESP note: this is a pessimistic estimate, but the same
23078 	 * as is used elsewhere.
23079 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
23080 	 *	+ 2-byte trailer
23081 	 */
23082 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
23083 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
23084 
23085 	if ((plen + overhead) > ill->ill_max_mtu)
23086 		return;
23087 
23088 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23089 
23090 	/*
23091 	 * Can the ill accelerate this IPsec protocol and algorithm
23092 	 * specified by the SA?
23093 	 */
23094 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
23095 	    ill->ill_isv6, sa)) {
23096 		return;
23097 	}
23098 
23099 	/*
23100 	 * Tell AH or ESP that the outbound ill is capable of
23101 	 * accelerating this packet.
23102 	 */
23103 	io->ipsec_out_is_capab_ill = B_TRUE;
23104 }
23105 
23106 /*
23107  * Select which AH & ESP SA's to use (if any) for the outbound packet.
23108  *
23109  * If this function returns B_TRUE, the requested SA's have been filled
23110  * into the ipsec_out_*_sa pointers.
23111  *
23112  * If the function returns B_FALSE, the packet has been "consumed", most
23113  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
23114  *
23115  * The SA references created by the protocol-specific "select"
23116  * function will be released when the ipsec_mp is freed, thanks to the
23117  * ipsec_out_free destructor -- see spd.c.
23118  */
23119 static boolean_t
23120 ipsec_out_select_sa(mblk_t *ipsec_mp)
23121 {
23122 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
23123 	ipsec_out_t *io;
23124 	ipsec_policy_t *pp;
23125 	ipsec_action_t *ap;
23126 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23127 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
23128 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
23129 
23130 	if (!io->ipsec_out_secure) {
23131 		/*
23132 		 * We came here by mistake.
23133 		 * Don't bother with ipsec processing
23134 		 * We should "discourage" this path in the future.
23135 		 */
23136 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
23137 		return (B_FALSE);
23138 	}
23139 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
23140 	ASSERT((io->ipsec_out_policy != NULL) ||
23141 	    (io->ipsec_out_act != NULL));
23142 
23143 	ASSERT(io->ipsec_out_failed == B_FALSE);
23144 
23145 	/*
23146 	 * IPSEC processing has started.
23147 	 */
23148 	io->ipsec_out_proc_begin = B_TRUE;
23149 	ap = io->ipsec_out_act;
23150 	if (ap == NULL) {
23151 		pp = io->ipsec_out_policy;
23152 		ASSERT(pp != NULL);
23153 		ap = pp->ipsp_act;
23154 		ASSERT(ap != NULL);
23155 	}
23156 
23157 	/*
23158 	 * We have an action.  now, let's select SA's.
23159 	 * (In the future, we can cache this in the conn_t..)
23160 	 */
23161 	if (ap->ipa_want_esp) {
23162 		if (io->ipsec_out_esp_sa == NULL) {
23163 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
23164 			    IPPROTO_ESP);
23165 		}
23166 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
23167 	}
23168 
23169 	if (ap->ipa_want_ah) {
23170 		if (io->ipsec_out_ah_sa == NULL) {
23171 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
23172 			    IPPROTO_AH);
23173 		}
23174 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
23175 		/*
23176 		 * The ESP and AH processing order needs to be preserved
23177 		 * when both protocols are required (ESP should be applied
23178 		 * before AH for an outbound packet). Force an ESP ACQUIRE
23179 		 * when both ESP and AH are required, and an AH ACQUIRE
23180 		 * is needed.
23181 		 */
23182 		if (ap->ipa_want_esp && need_ah_acquire)
23183 			need_esp_acquire = B_TRUE;
23184 	}
23185 
23186 	/*
23187 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
23188 	 * Release SAs that got referenced, but will not be used until we
23189 	 * acquire _all_ of the SAs we need.
23190 	 */
23191 	if (need_ah_acquire || need_esp_acquire) {
23192 		if (io->ipsec_out_ah_sa != NULL) {
23193 			IPSA_REFRELE(io->ipsec_out_ah_sa);
23194 			io->ipsec_out_ah_sa = NULL;
23195 		}
23196 		if (io->ipsec_out_esp_sa != NULL) {
23197 			IPSA_REFRELE(io->ipsec_out_esp_sa);
23198 			io->ipsec_out_esp_sa = NULL;
23199 		}
23200 
23201 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
23202 		return (B_FALSE);
23203 	}
23204 
23205 	return (B_TRUE);
23206 }
23207 
23208 /*
23209  * Process an IPSEC_OUT message and see what you can
23210  * do with it.
23211  * IPQoS Notes:
23212  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
23213  * IPSec.
23214  * XXX would like to nuke ire_t.
23215  * XXX ill_index better be "real"
23216  */
23217 void
23218 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
23219 {
23220 	ipsec_out_t *io;
23221 	ipsec_policy_t *pp;
23222 	ipsec_action_t *ap;
23223 	ipha_t *ipha;
23224 	ip6_t *ip6h;
23225 	mblk_t *mp;
23226 	ill_t *ill;
23227 	zoneid_t zoneid;
23228 	ipsec_status_t ipsec_rc;
23229 	boolean_t ill_need_rele = B_FALSE;
23230 
23231 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23232 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
23233 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
23234 	mp = ipsec_mp->b_cont;
23235 
23236 	/*
23237 	 * Initiate IPPF processing. We do it here to account for packets
23238 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
23239 	 * We can check for ipsec_out_proc_begin even for such packets, as
23240 	 * they will always be false (asserted below).
23241 	 */
23242 	if (IPP_ENABLED(IPP_LOCAL_OUT) && !io->ipsec_out_proc_begin) {
23243 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
23244 		    io->ipsec_out_ill_index : ill_index);
23245 		if (mp == NULL) {
23246 			ip2dbg(("ipsec_out_process: packet dropped "\
23247 			    "during IPPF processing\n"));
23248 			freeb(ipsec_mp);
23249 			BUMP_MIB(&ip_mib, ipOutDiscards);
23250 			return;
23251 		}
23252 	}
23253 
23254 	if (!io->ipsec_out_secure) {
23255 		/*
23256 		 * We came here by mistake.
23257 		 * Don't bother with ipsec processing
23258 		 * Should "discourage" this path in the future.
23259 		 */
23260 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
23261 		goto done;
23262 	}
23263 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
23264 	ASSERT((io->ipsec_out_policy != NULL) ||
23265 	    (io->ipsec_out_act != NULL));
23266 	ASSERT(io->ipsec_out_failed == B_FALSE);
23267 
23268 	if (!ipsec_loaded()) {
23269 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
23270 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
23271 			BUMP_MIB(&ip_mib, ipOutDiscards);
23272 		} else {
23273 			BUMP_MIB(&ip6_mib, ipv6OutDiscards);
23274 		}
23275 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
23276 		    &ipdrops_ip_ipsec_not_loaded, &ip_dropper);
23277 		return;
23278 	}
23279 
23280 	/*
23281 	 * IPSEC processing has started.
23282 	 */
23283 	io->ipsec_out_proc_begin = B_TRUE;
23284 	ap = io->ipsec_out_act;
23285 	if (ap == NULL) {
23286 		pp = io->ipsec_out_policy;
23287 		ASSERT(pp != NULL);
23288 		ap = pp->ipsp_act;
23289 		ASSERT(ap != NULL);
23290 	}
23291 
23292 	/*
23293 	 * Save the outbound ill index. When the packet comes back
23294 	 * from IPsec, we make sure the ill hasn't changed or disappeared
23295 	 * before sending it the accelerated packet.
23296 	 */
23297 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
23298 		int ifindex;
23299 		ill = ire_to_ill(ire);
23300 		ifindex = ill->ill_phyint->phyint_ifindex;
23301 		io->ipsec_out_capab_ill_index = ifindex;
23302 	}
23303 
23304 	/*
23305 	 * The order of processing is first insert a IP header if needed.
23306 	 * Then insert the ESP header and then the AH header.
23307 	 */
23308 	if ((io->ipsec_out_se_done == B_FALSE) &&
23309 	    (ap->ipa_want_se)) {
23310 		/*
23311 		 * First get the outer IP header before sending
23312 		 * it to ESP.
23313 		 */
23314 		ipha_t *oipha, *iipha;
23315 		mblk_t *outer_mp, *inner_mp;
23316 
23317 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
23318 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
23319 			    "ipsec_out_process: "
23320 			    "Self-Encapsulation failed: Out of memory\n");
23321 			freemsg(ipsec_mp);
23322 			BUMP_MIB(&ip_mib, ipOutDiscards);
23323 			return;
23324 		}
23325 		inner_mp = ipsec_mp->b_cont;
23326 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
23327 		oipha = (ipha_t *)outer_mp->b_rptr;
23328 		iipha = (ipha_t *)inner_mp->b_rptr;
23329 		*oipha = *iipha;
23330 		outer_mp->b_wptr += sizeof (ipha_t);
23331 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
23332 		    sizeof (ipha_t));
23333 		oipha->ipha_protocol = IPPROTO_ENCAP;
23334 		oipha->ipha_version_and_hdr_length =
23335 		    IP_SIMPLE_HDR_VERSION;
23336 		oipha->ipha_hdr_checksum = 0;
23337 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
23338 		outer_mp->b_cont = inner_mp;
23339 		ipsec_mp->b_cont = outer_mp;
23340 
23341 		io->ipsec_out_se_done = B_TRUE;
23342 		io->ipsec_out_encaps = B_TRUE;
23343 	}
23344 
23345 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
23346 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
23347 	    !ipsec_out_select_sa(ipsec_mp))
23348 		return;
23349 
23350 	/*
23351 	 * By now, we know what SA's to use.  Toss over to ESP & AH
23352 	 * to do the heavy lifting.
23353 	 */
23354 	zoneid = io->ipsec_out_zoneid;
23355 	ASSERT(zoneid != ALL_ZONES);
23356 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
23357 		ASSERT(io->ipsec_out_esp_sa != NULL);
23358 		io->ipsec_out_esp_done = B_TRUE;
23359 		/*
23360 		 * Note that since hw accel can only apply one transform,
23361 		 * not two, we skip hw accel for ESP if we also have AH
23362 		 * This is an design limitation of the interface
23363 		 * which should be revisited.
23364 		 */
23365 		ASSERT(ire != NULL);
23366 		if (io->ipsec_out_ah_sa == NULL) {
23367 			ill = (ill_t *)ire->ire_stq->q_ptr;
23368 			ipsec_out_is_accelerated(ipsec_mp,
23369 			    io->ipsec_out_esp_sa, ill, ire);
23370 		}
23371 
23372 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
23373 		switch (ipsec_rc) {
23374 		case IPSEC_STATUS_SUCCESS:
23375 			break;
23376 		case IPSEC_STATUS_FAILED:
23377 			BUMP_MIB(&ip_mib, ipOutDiscards);
23378 			/* FALLTHRU */
23379 		case IPSEC_STATUS_PENDING:
23380 			return;
23381 		}
23382 	}
23383 
23384 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
23385 		ASSERT(io->ipsec_out_ah_sa != NULL);
23386 		io->ipsec_out_ah_done = B_TRUE;
23387 		if (ire == NULL) {
23388 			int idx = io->ipsec_out_capab_ill_index;
23389 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
23390 			    NULL, NULL, NULL, NULL);
23391 			ill_need_rele = B_TRUE;
23392 		} else {
23393 			ill = (ill_t *)ire->ire_stq->q_ptr;
23394 		}
23395 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
23396 		    ire);
23397 
23398 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
23399 		switch (ipsec_rc) {
23400 		case IPSEC_STATUS_SUCCESS:
23401 			break;
23402 		case IPSEC_STATUS_FAILED:
23403 			BUMP_MIB(&ip_mib, ipOutDiscards);
23404 			/* FALLTHRU */
23405 		case IPSEC_STATUS_PENDING:
23406 			if (ill != NULL && ill_need_rele)
23407 				ill_refrele(ill);
23408 			return;
23409 		}
23410 	}
23411 	/*
23412 	 * We are done with IPSEC processing. Send it over
23413 	 * the wire.
23414 	 */
23415 done:
23416 	mp = ipsec_mp->b_cont;
23417 	ipha = (ipha_t *)mp->b_rptr;
23418 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
23419 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
23420 	} else {
23421 		ip6h = (ip6_t *)ipha;
23422 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
23423 	}
23424 	if (ill != NULL && ill_need_rele)
23425 		ill_refrele(ill);
23426 }
23427 
23428 /* ARGSUSED */
23429 void
23430 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
23431 {
23432 	opt_restart_t	*or;
23433 	int	err;
23434 	conn_t	*connp;
23435 
23436 	ASSERT(CONN_Q(q));
23437 	connp = Q_TO_CONN(q);
23438 
23439 	ASSERT(first_mp->b_datap->db_type == M_CTL);
23440 	or = (opt_restart_t *)first_mp->b_rptr;
23441 	/*
23442 	 * We don't need to pass any credentials here since this is just
23443 	 * a restart. The credentials are passed in when svr4_optcom_req
23444 	 * is called the first time (from ip_wput_nondata).
23445 	 */
23446 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
23447 		err = svr4_optcom_req(q, first_mp, NULL,
23448 		    &ip_opt_obj);
23449 	} else {
23450 		ASSERT(or->or_type == T_OPTMGMT_REQ);
23451 		err = tpi_optcom_req(q, first_mp, NULL,
23452 		    &ip_opt_obj);
23453 	}
23454 	if (err != EINPROGRESS) {
23455 		/* operation is done */
23456 		CONN_OPER_PENDING_DONE(connp);
23457 	}
23458 }
23459 
23460 /*
23461  * ioctls that go through a down/up sequence may need to wait for the down
23462  * to complete. This involves waiting for the ire and ipif refcnts to go down
23463  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
23464  */
23465 /* ARGSUSED */
23466 void
23467 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
23468 {
23469 	struct iocblk *iocp;
23470 	mblk_t *mp1;
23471 	ipif_t	*ipif;
23472 	ip_ioctl_cmd_t *ipip;
23473 	int err;
23474 	sin_t	*sin;
23475 	struct lifreq *lifr;
23476 	struct ifreq *ifr;
23477 
23478 	iocp = (struct iocblk *)mp->b_rptr;
23479 	ASSERT(ipsq != NULL);
23480 	/* Existence of mp1 verified in ip_wput_nondata */
23481 	mp1 = mp->b_cont->b_cont;
23482 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
23483 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
23484 		ill_t *ill;
23485 		/*
23486 		 * Special case where ipsq_current_ipif may not be set.
23487 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
23488 		 * ill could also have become part of a ipmp group in the
23489 		 * process, we are here as were not able to complete the
23490 		 * operation in ipif_set_values because we could not become
23491 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
23492 		 * will not be set so we need to set it.
23493 		 */
23494 		ill = (ill_t *)q->q_ptr;
23495 		ipsq->ipsq_current_ipif = ill->ill_ipif;
23496 		ipsq->ipsq_last_cmd = ipip->ipi_cmd;
23497 	}
23498 
23499 	ipif = ipsq->ipsq_current_ipif;
23500 	ASSERT(ipif != NULL);
23501 	if (ipip->ipi_cmd_type == IF_CMD) {
23502 		/* This a old style SIOC[GS]IF* command */
23503 		ifr = (struct ifreq *)mp1->b_rptr;
23504 		sin = (sin_t *)&ifr->ifr_addr;
23505 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
23506 		/* This a new style SIOC[GS]LIF* command */
23507 		lifr = (struct lifreq *)mp1->b_rptr;
23508 		sin = (sin_t *)&lifr->lifr_addr;
23509 	} else {
23510 		sin = NULL;
23511 	}
23512 
23513 	err = (*ipip->ipi_func_restart)(ipif, sin, q, mp, ipip,
23514 	    (void *)mp1->b_rptr);
23515 
23516 	/* SIOCLIFREMOVEIF could have removed the ipif */
23517 	ip_ioctl_finish(q, mp, err,
23518 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
23519 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ipif, ipsq);
23520 }
23521 
23522 /*
23523  * ioctl processing
23524  *
23525  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
23526  * the ioctl command in the ioctl tables and determines the copyin data size
23527  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
23528  * size.
23529  *
23530  * ioctl processing then continues when the M_IOCDATA makes its way down.
23531  * Now the ioctl is looked up again in the ioctl table, and its properties are
23532  * extracted. The associated 'conn' is then refheld till the end of the ioctl
23533  * and the general ioctl processing function ip_process_ioctl is called.
23534  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
23535  * so goes thru the serialization primitive ipsq_try_enter. Then the
23536  * appropriate function to handle the ioctl is called based on the entry in
23537  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
23538  * which also refreleases the 'conn' that was refheld at the start of the
23539  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
23540  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
23541  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
23542  *
23543  * Many exclusive ioctls go thru an internal down up sequence as part of
23544  * the operation. For example an attempt to change the IP address of an
23545  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
23546  * does all the cleanup such as deleting all ires that use this address.
23547  * Then we need to wait till all references to the interface go away.
23548  */
23549 void
23550 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
23551 {
23552 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
23553 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
23554 	cmd_info_t ci;
23555 	int err;
23556 	boolean_t entered_ipsq = B_FALSE;
23557 
23558 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
23559 
23560 	if (ipip == NULL)
23561 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
23562 
23563 	/*
23564 	 * SIOCLIFADDIF needs to go thru a special path since the
23565 	 * ill may not exist yet. This happens in the case of lo0
23566 	 * which is created using this ioctl.
23567 	 */
23568 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
23569 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
23570 		ip_ioctl_finish(q, mp, err,
23571 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
23572 		    NULL, NULL);
23573 		return;
23574 	}
23575 
23576 	ci.ci_ipif = NULL;
23577 	switch (ipip->ipi_cmd_type) {
23578 	case IF_CMD:
23579 	case LIF_CMD:
23580 		/*
23581 		 * ioctls that pass in a [l]ifreq appear here.
23582 		 * ip_extract_lifreq_cmn returns a refheld ipif in
23583 		 * ci.ci_ipif
23584 		 */
23585 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
23586 		    ipip->ipi_flags, &ci, ip_process_ioctl);
23587 		if (err != 0) {
23588 			ip_ioctl_finish(q, mp, err,
23589 			    ipip->ipi_flags & IPI_GET_CMD ?
23590 			    COPYOUT : NO_COPYOUT, NULL, NULL);
23591 			return;
23592 		}
23593 		ASSERT(ci.ci_ipif != NULL);
23594 		break;
23595 
23596 	case TUN_CMD:
23597 		/*
23598 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
23599 		 * a refheld ipif in ci.ci_ipif
23600 		 */
23601 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
23602 		if (err != 0) {
23603 			ip_ioctl_finish(q, mp, err,
23604 			    ipip->ipi_flags & IPI_GET_CMD ?
23605 			    COPYOUT : NO_COPYOUT, NULL, NULL);
23606 			return;
23607 		}
23608 		ASSERT(ci.ci_ipif != NULL);
23609 		break;
23610 
23611 	case MISC_CMD:
23612 		/*
23613 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
23614 		 * For eg. SIOCGLIFCONF will appear here.
23615 		 */
23616 		switch (ipip->ipi_cmd) {
23617 		case IF_UNITSEL:
23618 			/* ioctl comes down the ill */
23619 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
23620 			ipif_refhold(ci.ci_ipif);
23621 			break;
23622 		case SIOCGMSFILTER:
23623 		case SIOCSMSFILTER:
23624 		case SIOCGIPMSFILTER:
23625 		case SIOCSIPMSFILTER:
23626 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
23627 			    ip_process_ioctl);
23628 			if (err != 0) {
23629 				ip_ioctl_finish(q, mp, err,
23630 				    ipip->ipi_flags & IPI_GET_CMD ?
23631 				    COPYOUT : NO_COPYOUT, NULL, NULL);
23632 				return;
23633 			}
23634 			break;
23635 		}
23636 		err = 0;
23637 		ci.ci_sin = NULL;
23638 		ci.ci_sin6 = NULL;
23639 		ci.ci_lifr = NULL;
23640 		break;
23641 	}
23642 
23643 	/*
23644 	 * If ipsq is non-null, we are already being called exclusively
23645 	 */
23646 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
23647 	if (!(ipip->ipi_flags & IPI_WR)) {
23648 		/*
23649 		 * A return value of EINPROGRESS means the ioctl is
23650 		 * either queued and waiting for some reason or has
23651 		 * already completed.
23652 		 */
23653 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
23654 		    ci.ci_lifr);
23655 		if (ci.ci_ipif != NULL)
23656 			ipif_refrele(ci.ci_ipif);
23657 		ip_ioctl_finish(q, mp, err,
23658 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
23659 		    NULL, NULL);
23660 		return;
23661 	}
23662 
23663 	ASSERT(ci.ci_ipif != NULL);
23664 
23665 	if (ipsq == NULL) {
23666 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
23667 		    ip_process_ioctl, NEW_OP, B_TRUE);
23668 		entered_ipsq = B_TRUE;
23669 	}
23670 	/*
23671 	 * Release the ipif so that ipif_down and friends that wait for
23672 	 * references to go away are not misled about the current ipif_refcnt
23673 	 * values. We are writer so we can access the ipif even after releasing
23674 	 * the ipif.
23675 	 */
23676 	ipif_refrele(ci.ci_ipif);
23677 	if (ipsq == NULL)
23678 		return;
23679 
23680 	mutex_enter(&ipsq->ipsq_lock);
23681 	ASSERT(ipsq->ipsq_current_ipif == NULL);
23682 	ipsq->ipsq_current_ipif = ci.ci_ipif;
23683 	ipsq->ipsq_last_cmd = ipip->ipi_cmd;
23684 	mutex_exit(&ipsq->ipsq_lock);
23685 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
23686 	/*
23687 	 * For most set ioctls that come here, this serves as a single point
23688 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
23689 	 * be any new references to the ipif. This helps functions that go
23690 	 * through this path and end up trying to wait for the refcnts
23691 	 * associated with the ipif to go down to zero. Some exceptions are
23692 	 * Failover, Failback, and Groupname commands that operate on more than
23693 	 * just the ci.ci_ipif. These commands internally determine the
23694 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
23695 	 * flags on that set. Another exception is the Removeif command that
23696 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
23697 	 * ipif to operate on.
23698 	 */
23699 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
23700 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
23701 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
23702 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
23703 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
23704 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
23705 
23706 	/*
23707 	 * A return value of EINPROGRESS means the ioctl is
23708 	 * either queued and waiting for some reason or has
23709 	 * already completed.
23710 	 */
23711 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
23712 	    ci.ci_lifr);
23713 
23714 	/* SIOCLIFREMOVEIF could have removed the ipif */
23715 	ip_ioctl_finish(q, mp, err,
23716 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
23717 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ci.ci_ipif, ipsq);
23718 
23719 	if (entered_ipsq)
23720 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
23721 }
23722 
23723 /*
23724  * Complete the ioctl. Typically ioctls use the mi package and need to
23725  * do mi_copyout/mi_copy_done.
23726  */
23727 void
23728 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode,
23729     ipif_t *ipif, ipsq_t *ipsq)
23730 {
23731 	conn_t	*connp = NULL;
23732 
23733 	if (err == EINPROGRESS)
23734 		return;
23735 
23736 	if (CONN_Q(q)) {
23737 		connp = Q_TO_CONN(q);
23738 		ASSERT(connp->conn_ref >= 2);
23739 	}
23740 
23741 	switch (mode) {
23742 	case COPYOUT:
23743 		if (err == 0)
23744 			mi_copyout(q, mp);
23745 		else
23746 			mi_copy_done(q, mp, err);
23747 		break;
23748 
23749 	case NO_COPYOUT:
23750 		mi_copy_done(q, mp, err);
23751 		break;
23752 
23753 	default:
23754 		/* An ioctl aborted through a conn close would take this path */
23755 		break;
23756 	}
23757 
23758 	/*
23759 	 * The refhold placed at the start of the ioctl is released here.
23760 	 */
23761 	if (connp != NULL)
23762 		CONN_OPER_PENDING_DONE(connp);
23763 
23764 	/*
23765 	 * If the ioctl were an exclusive ioctl it would have set
23766 	 * IPIF_CHANGING at the start of the ioctl which is undone here.
23767 	 */
23768 	if (ipif != NULL) {
23769 		mutex_enter(&(ipif)->ipif_ill->ill_lock);
23770 		ipif->ipif_state_flags &= ~IPIF_CHANGING;
23771 		mutex_exit(&(ipif)->ipif_ill->ill_lock);
23772 	}
23773 
23774 	/*
23775 	 * Clear the current ipif in the ipsq at the completion of the ioctl.
23776 	 * Note that a non-null ipsq_current_ipif prevents new ioctls from
23777 	 * entering the ipsq
23778 	 */
23779 	if (ipsq != NULL) {
23780 		mutex_enter(&ipsq->ipsq_lock);
23781 		ipsq->ipsq_current_ipif = NULL;
23782 		mutex_exit(&ipsq->ipsq_lock);
23783 	}
23784 }
23785 
23786 /*
23787  * This is called from ip_wput_nondata to resume a deferred TCP bind.
23788  */
23789 /* ARGSUSED */
23790 void
23791 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
23792 {
23793 	conn_t *connp = (conn_t *)arg;
23794 	tcp_t	*tcp;
23795 
23796 	ASSERT(connp != NULL && connp->conn_tcp != NULL);
23797 	tcp = connp->conn_tcp;
23798 
23799 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
23800 		freemsg(mp);
23801 	else
23802 		tcp_rput_other(tcp, mp);
23803 	CONN_OPER_PENDING_DONE(connp);
23804 
23805 }
23806 
23807 /* Called from ip_wput for all non data messages */
23808 /* ARGSUSED */
23809 void
23810 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
23811 {
23812 	mblk_t		*mp1;
23813 	ire_t		*ire;
23814 	ill_t		*ill;
23815 	struct iocblk	*iocp;
23816 	ip_ioctl_cmd_t	*ipip;
23817 	cred_t		*cr;
23818 	conn_t		*connp = NULL;
23819 	int		cmd, err;
23820 
23821 	if (CONN_Q(q))
23822 		connp = Q_TO_CONN(q);
23823 
23824 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
23825 
23826 	/* Check if it is a queue to /dev/sctp. */
23827 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
23828 	    connp->conn_rq == NULL) {
23829 		sctp_wput(q, mp);
23830 		return;
23831 	}
23832 
23833 	switch (DB_TYPE(mp)) {
23834 	case M_IOCTL:
23835 		/*
23836 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
23837 		 * will arrange to copy in associated control structures.
23838 		 */
23839 		ip_sioctl_copyin_setup(q, mp);
23840 		return;
23841 	case M_IOCDATA:
23842 		/*
23843 		 * Ensure that this is associated with one of our trans-
23844 		 * parent ioctls.  If it's not ours, discard it if we're
23845 		 * running as a driver, or pass it on if we're a module.
23846 		 */
23847 		iocp = (struct iocblk *)mp->b_rptr;
23848 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
23849 		if (ipip == NULL) {
23850 			if (q->q_next == NULL) {
23851 				goto nak;
23852 			} else {
23853 				putnext(q, mp);
23854 			}
23855 			return;
23856 		} else if ((q->q_next != NULL) &&
23857 		    !(ipip->ipi_flags & IPI_MODOK)) {
23858 			/*
23859 			 * the ioctl is one we recognise, but is not
23860 			 * consumed by IP as a module, pass M_IOCDATA
23861 			 * for processing downstream, but only for
23862 			 * common Streams ioctls.
23863 			 */
23864 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
23865 				putnext(q, mp);
23866 				return;
23867 			} else {
23868 				goto nak;
23869 			}
23870 		}
23871 
23872 		/* IOCTL continuation following copyin or copyout. */
23873 		if (mi_copy_state(q, mp, NULL) == -1) {
23874 			/*
23875 			 * The copy operation failed.  mi_copy_state already
23876 			 * cleaned up, so we're out of here.
23877 			 */
23878 			return;
23879 		}
23880 		/*
23881 		 * If we just completed a copy in, we become writer and
23882 		 * continue processing in ip_sioctl_copyin_done.  If it
23883 		 * was a copy out, we call mi_copyout again.  If there is
23884 		 * nothing more to copy out, it will complete the IOCTL.
23885 		 */
23886 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
23887 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
23888 				mi_copy_done(q, mp, EPROTO);
23889 				return;
23890 			}
23891 			/*
23892 			 * Check for cases that need more copying.  A return
23893 			 * value of 0 means a second copyin has been started,
23894 			 * so we return; a return value of 1 means no more
23895 			 * copying is needed, so we continue.
23896 			 */
23897 			cmd = iocp->ioc_cmd;
23898 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
23899 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
23900 			    MI_COPY_COUNT(mp) == 1) {
23901 				if (ip_copyin_msfilter(q, mp) == 0)
23902 					return;
23903 			}
23904 			/*
23905 			 * Refhold the conn, till the ioctl completes. This is
23906 			 * needed in case the ioctl ends up in the pending mp
23907 			 * list. Every mp in the ill_pending_mp list and
23908 			 * the ipsq_pending_mp must have a refhold on the conn
23909 			 * to resume processing. The refhold is released when
23910 			 * the ioctl completes. (normally or abnormally)
23911 			 * In all cases ip_ioctl_finish is called to finish
23912 			 * the ioctl.
23913 			 */
23914 			if (connp != NULL) {
23915 				/* This is not a reentry */
23916 				ASSERT(ipsq == NULL);
23917 				CONN_INC_REF(connp);
23918 			} else {
23919 				if (!(ipip->ipi_flags & IPI_MODOK)) {
23920 					mi_copy_done(q, mp, EINVAL);
23921 					return;
23922 				}
23923 			}
23924 
23925 			ip_process_ioctl(ipsq, q, mp, ipip);
23926 
23927 		} else {
23928 			mi_copyout(q, mp);
23929 		}
23930 		return;
23931 nak:
23932 		iocp->ioc_error = EINVAL;
23933 		mp->b_datap->db_type = M_IOCNAK;
23934 		iocp->ioc_count = 0;
23935 		qreply(q, mp);
23936 		return;
23937 
23938 	case M_IOCNAK:
23939 		/*
23940 		 * The only way we could get here is if a resolver didn't like
23941 		 * an IOCTL we sent it.	 This shouldn't happen.
23942 		 */
23943 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
23944 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
23945 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
23946 		freemsg(mp);
23947 		return;
23948 	case M_IOCACK:
23949 		/* Finish socket ioctls passed through to ARP. */
23950 		ip_sioctl_iocack(q, mp);
23951 		return;
23952 	case M_FLUSH:
23953 		if (*mp->b_rptr & FLUSHW)
23954 			flushq(q, FLUSHALL);
23955 		if (q->q_next) {
23956 			/*
23957 			 * M_FLUSH is sent up to IP by some drivers during
23958 			 * unbind. ip_rput has already replied to it. We are
23959 			 * here for the M_FLUSH that we originated in IP
23960 			 * before sending the unbind request to the driver.
23961 			 * Just free it as we don't queue packets in IP
23962 			 * on the write side of the device instance.
23963 			 */
23964 			freemsg(mp);
23965 			return;
23966 		}
23967 		if (*mp->b_rptr & FLUSHR) {
23968 			*mp->b_rptr &= ~FLUSHW;
23969 			qreply(q, mp);
23970 			return;
23971 		}
23972 		freemsg(mp);
23973 		return;
23974 	case IRE_DB_REQ_TYPE:
23975 		/* An Upper Level Protocol wants a copy of an IRE. */
23976 		ip_ire_req(q, mp);
23977 		return;
23978 	case M_CTL:
23979 		/* M_CTL messages are used by ARP to tell us things. */
23980 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
23981 			break;
23982 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
23983 		case AR_ENTRY_SQUERY:
23984 			ip_wput_ctl(q, mp);
23985 			return;
23986 		case AR_CLIENT_NOTIFY:
23987 			ip_arp_news(q, mp);
23988 			return;
23989 		case AR_DLPIOP_DONE:
23990 			ASSERT(q->q_next != NULL);
23991 			ill = (ill_t *)q->q_ptr;
23992 			/* qwriter_ip releases the refhold */
23993 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
23994 			ill_refhold(ill);
23995 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
23996 			    CUR_OP, B_FALSE);
23997 			return;
23998 		case AR_ARP_CLOSING:
23999 			/*
24000 			 * ARP (above us) is closing. If no ARP bringup is
24001 			 * currently pending, ack the message so that ARP
24002 			 * can complete its close. Also mark ill_arp_closing
24003 			 * so that new ARP bringups will fail. If any
24004 			 * ARP bringup is currently in progress, we will
24005 			 * ack this when the current ARP bringup completes.
24006 			 */
24007 			ASSERT(q->q_next != NULL);
24008 			ill = (ill_t *)q->q_ptr;
24009 			mutex_enter(&ill->ill_lock);
24010 			ill->ill_arp_closing = 1;
24011 			if (!ill->ill_arp_bringup_pending) {
24012 				mutex_exit(&ill->ill_lock);
24013 				qreply(q, mp);
24014 			} else {
24015 				mutex_exit(&ill->ill_lock);
24016 				freemsg(mp);
24017 			}
24018 			return;
24019 		default:
24020 			break;
24021 		}
24022 		break;
24023 	case M_PROTO:
24024 	case M_PCPROTO:
24025 		/*
24026 		 * The only PROTO messages we expect are ULP binds and
24027 		 * copies of option negotiation acknowledgements.
24028 		 */
24029 		switch (((union T_primitives *)mp->b_rptr)->type) {
24030 		case O_T_BIND_REQ:
24031 		case T_BIND_REQ: {
24032 			/* Request can get queued in bind */
24033 			ASSERT(connp != NULL);
24034 			/* Don't increment refcnt if this is a re-entry */
24035 			if (ipsq == NULL)
24036 				CONN_INC_REF(connp);
24037 			mp = connp->conn_af_isv6 ?
24038 			    ip_bind_v6(q, mp, connp, NULL) :
24039 				ip_bind_v4(q, mp, connp);
24040 			if (mp != NULL) {
24041 				tcp_t	*tcp;
24042 
24043 				tcp = connp->conn_tcp;
24044 				if (tcp != NULL) {
24045 					if (ipsq == NULL) {
24046 						tcp_rput_other(tcp, mp);
24047 					} else {
24048 						CONN_INC_REF(connp);
24049 						squeue_fill(connp->conn_sqp, mp,
24050 						    ip_resume_tcp_bind,
24051 						    connp, SQTAG_TCP_RPUTOTHER);
24052 						return;
24053 					}
24054 				} else {
24055 					qreply(q, mp);
24056 				}
24057 				CONN_OPER_PENDING_DONE(connp);
24058 			}
24059 			return;
24060 		}
24061 		case T_SVR4_OPTMGMT_REQ:
24062 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
24063 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
24064 
24065 			ASSERT(connp != NULL);
24066 			if (!snmpcom_req(q, mp, ip_snmp_set,
24067 			    ip_snmp_get, cr)) {
24068 				/*
24069 				 * Call svr4_optcom_req so that it can
24070 				 * generate the ack. We don't come here
24071 				 * if this operation is being restarted.
24072 				 * ip_restart_optmgmt will drop the conn ref.
24073 				 * In the case of ipsec option after the ipsec
24074 				 * load is complete conn_restart_ipsec_waiter
24075 				 * drops the conn ref.
24076 				 */
24077 				ASSERT(ipsq == NULL);
24078 				CONN_INC_REF(connp);
24079 				if (ip_check_for_ipsec_opt(q, mp))
24080 					return;
24081 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
24082 				if (err != EINPROGRESS) {
24083 					/* Operation is done */
24084 					CONN_OPER_PENDING_DONE(connp);
24085 				}
24086 			}
24087 			return;
24088 		case T_OPTMGMT_REQ:
24089 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
24090 			/*
24091 			 * Note: No snmpcom_req support through new
24092 			 * T_OPTMGMT_REQ.
24093 			 * Call tpi_optcom_req so that it can
24094 			 * generate the ack.
24095 			 */
24096 			ASSERT(connp != NULL);
24097 			ASSERT(ipsq == NULL);
24098 			/*
24099 			 * We don't come here for restart. ip_restart_optmgmt
24100 			 * will drop the conn ref. In the case of ipsec option
24101 			 * after the ipsec load is complete
24102 			 * conn_restart_ipsec_waiter drops the conn ref.
24103 			 */
24104 			CONN_INC_REF(connp);
24105 			if (ip_check_for_ipsec_opt(q, mp))
24106 				return;
24107 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
24108 			if (err != EINPROGRESS) {
24109 				/* Operation is done */
24110 				CONN_OPER_PENDING_DONE(connp);
24111 			}
24112 			return;
24113 		case T_UNBIND_REQ:
24114 			ip_unbind(q, mp);
24115 			return;
24116 		default:
24117 			/*
24118 			 * Have to drop any DLPI messages coming down from
24119 			 * arp (such as an info_req which would cause ip
24120 			 * to receive an extra info_ack if it was passed
24121 			 * through.
24122 			 */
24123 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
24124 			    (int)*(uint_t *)mp->b_rptr));
24125 			freemsg(mp);
24126 			return;
24127 		}
24128 		/* NOTREACHED */
24129 	case IRE_DB_TYPE: {
24130 		nce_t		*nce;
24131 		ill_t		*ill;
24132 		in6_addr_t	gw_addr_v6;
24133 
24134 
24135 		/*
24136 		 * This is a response back from a resolver.  It
24137 		 * consists of a message chain containing:
24138 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
24139 		 * The IRE_MBLK is the one we allocated in ip_newroute.
24140 		 * The LL_HDR_MBLK is the DLPI header to use to get
24141 		 * the attached packet, and subsequent ones for the
24142 		 * same destination, transmitted.
24143 		 */
24144 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
24145 			break;
24146 		/*
24147 		 * First, check to make sure the resolution succeeded.
24148 		 * If it failed, the second mblk will be empty.
24149 		 * If it is, free the chain, dropping the packet.
24150 		 * (We must ire_delete the ire; that frees the ire mblk)
24151 		 * We're doing this now to support PVCs for ATM; it's
24152 		 * a partial xresolv implementation. When we fully implement
24153 		 * xresolv interfaces, instead of freeing everything here
24154 		 * we'll initiate neighbor discovery.
24155 		 *
24156 		 * For v4 (ARP and other external resolvers) the resolver
24157 		 * frees the message, so no check is needed. This check
24158 		 * is required, though, for a full xresolve implementation.
24159 		 * Including this code here now both shows how external
24160 		 * resolvers can NACK a resolution request using an
24161 		 * existing design that has no specific provisions for NACKs,
24162 		 * and also takes into account that the current non-ARP
24163 		 * external resolver has been coded to use this method of
24164 		 * NACKing for all IPv6 (xresolv) cases,
24165 		 * whether our xresolv implementation is complete or not.
24166 		 *
24167 		 */
24168 		ire = (ire_t *)mp->b_rptr;
24169 		ill = ire_to_ill(ire);
24170 		mp1 = mp->b_cont;		/* dl_unitdata_req */
24171 		if (mp1->b_rptr == mp1->b_wptr) {
24172 			if (ire->ire_ipversion == IPV6_VERSION) {
24173 				/*
24174 				 * XRESOLV interface.
24175 				 */
24176 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
24177 				mutex_enter(&ire->ire_lock);
24178 				gw_addr_v6 = ire->ire_gateway_addr_v6;
24179 				mutex_exit(&ire->ire_lock);
24180 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
24181 					nce = ndp_lookup(ill,
24182 					    &ire->ire_addr_v6, B_FALSE);
24183 				} else {
24184 					nce = ndp_lookup(ill, &gw_addr_v6,
24185 					    B_FALSE);
24186 				}
24187 				if (nce != NULL) {
24188 					nce_resolv_failed(nce);
24189 					ndp_delete(nce);
24190 					NCE_REFRELE(nce);
24191 				}
24192 			}
24193 			mp->b_cont = NULL;
24194 			freemsg(mp1);		/* frees the pkt as well */
24195 			ire_delete((ire_t *)mp->b_rptr);
24196 			return;
24197 		}
24198 		/*
24199 		 * Split them into IRE_MBLK and pkt and feed it into
24200 		 * ire_add_then_send. Then in ire_add_then_send
24201 		 * the IRE will be added, and then the packet will be
24202 		 * run back through ip_wput. This time it will make
24203 		 * it to the wire.
24204 		 */
24205 		mp->b_cont = NULL;
24206 		mp = mp1->b_cont;		/* now, mp points to pkt */
24207 		mp1->b_cont = NULL;
24208 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
24209 		if (ire->ire_ipversion == IPV6_VERSION) {
24210 			/*
24211 			 * XRESOLV interface. Find the nce and put a copy
24212 			 * of the dl_unitdata_req in nce_res_mp
24213 			 */
24214 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
24215 			mutex_enter(&ire->ire_lock);
24216 			gw_addr_v6 = ire->ire_gateway_addr_v6;
24217 			mutex_exit(&ire->ire_lock);
24218 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
24219 				nce = ndp_lookup(ill, &ire->ire_addr_v6,
24220 				    B_FALSE);
24221 			} else {
24222 				nce = ndp_lookup(ill, &gw_addr_v6, B_FALSE);
24223 			}
24224 			if (nce != NULL) {
24225 				/*
24226 				 * We have to protect nce_res_mp here
24227 				 * from being accessed by other threads
24228 				 * while we change the mblk pointer.
24229 				 * Other functions will also lock the nce when
24230 				 * accessing nce_res_mp.
24231 				 *
24232 				 * The reason we change the mblk pointer
24233 				 * here rather than copying the resolved address
24234 				 * into the template is that, unlike with
24235 				 * ethernet, we have no guarantee that the
24236 				 * resolved address length will be
24237 				 * smaller than or equal to the lla length
24238 				 * with which the template was allocated,
24239 				 * (for ethernet, they're equal)
24240 				 * so we have to use the actual resolved
24241 				 * address mblk - which holds the real
24242 				 * dl_unitdata_req with the resolved address.
24243 				 *
24244 				 * Doing this is the same behavior as was
24245 				 * previously used in the v4 ARP case.
24246 				 */
24247 				mutex_enter(&nce->nce_lock);
24248 				if (nce->nce_res_mp != NULL)
24249 					freemsg(nce->nce_res_mp);
24250 				nce->nce_res_mp = mp1;
24251 				mutex_exit(&nce->nce_lock);
24252 				/*
24253 				 * We do a fastpath probe here because
24254 				 * we have resolved the address without
24255 				 * using Neighbor Discovery.
24256 				 * In the non-XRESOLV v6 case, the fastpath
24257 				 * probe is done right after neighbor
24258 				 * discovery completes.
24259 				 */
24260 				if (nce->nce_res_mp != NULL) {
24261 					int res;
24262 					nce_fastpath_list_add(nce);
24263 					res = ill_fastpath_probe(ill,
24264 					    nce->nce_res_mp);
24265 					if (res != 0 && res != EAGAIN)
24266 						nce_fastpath_list_delete(nce);
24267 				}
24268 
24269 				ire_add_then_send(q, ire, mp);
24270 				/*
24271 				 * Now we have to clean out any packets
24272 				 * that may have been queued on the nce
24273 				 * while it was waiting for address resolution
24274 				 * to complete.
24275 				 */
24276 				mutex_enter(&nce->nce_lock);
24277 				mp1 = nce->nce_qd_mp;
24278 				nce->nce_qd_mp = NULL;
24279 				mutex_exit(&nce->nce_lock);
24280 				while (mp1 != NULL) {
24281 					mblk_t *nxt_mp;
24282 					queue_t *fwdq = NULL;
24283 					ill_t   *inbound_ill;
24284 					uint_t ifindex;
24285 
24286 					nxt_mp = mp1->b_next;
24287 					mp1->b_next = NULL;
24288 					/*
24289 					 * Retrieve ifindex stored in
24290 					 * ip_rput_data_v6()
24291 					 */
24292 					ifindex =
24293 					    (uint_t)(uintptr_t)mp1->b_prev;
24294 					inbound_ill =
24295 						ill_lookup_on_ifindex(ifindex,
24296 						    B_TRUE, NULL, NULL, NULL,
24297 						    NULL);
24298 					mp1->b_prev = NULL;
24299 					if (inbound_ill != NULL)
24300 						fwdq = inbound_ill->ill_rq;
24301 
24302 					if (fwdq != NULL) {
24303 						put(fwdq, mp1);
24304 						ill_refrele(inbound_ill);
24305 					} else
24306 						put(WR(ill->ill_rq), mp1);
24307 					mp1 = nxt_mp;
24308 				}
24309 				NCE_REFRELE(nce);
24310 			} else {	/* nce is NULL; clean up */
24311 				ire_delete(ire);
24312 				freemsg(mp);
24313 				freemsg(mp1);
24314 				return;
24315 			}
24316 		} else {
24317 			ire->ire_dlureq_mp = mp1;
24318 			ire_add_then_send(q, ire, mp);
24319 		}
24320 		return;	/* All is well, the packet has been sent. */
24321 	}
24322 	default:
24323 		break;
24324 	}
24325 	if (q->q_next) {
24326 		putnext(q, mp);
24327 	} else
24328 		freemsg(mp);
24329 }
24330 
24331 /*
24332  * Process IP options in an outbound packet.  Modify the destination if there
24333  * is a source route option.
24334  * Returns non-zero if something fails in which case an ICMP error has been
24335  * sent and mp freed.
24336  */
24337 static int
24338 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
24339     boolean_t mctl_present, zoneid_t zoneid)
24340 {
24341 	ipoptp_t	opts;
24342 	uchar_t		*opt;
24343 	uint8_t		optval;
24344 	uint8_t		optlen;
24345 	ipaddr_t	dst;
24346 	intptr_t	code = 0;
24347 	mblk_t		*mp;
24348 	ire_t		*ire = NULL;
24349 
24350 	ip2dbg(("ip_wput_options\n"));
24351 	mp = ipsec_mp;
24352 	if (mctl_present) {
24353 		mp = ipsec_mp->b_cont;
24354 	}
24355 
24356 	dst = ipha->ipha_dst;
24357 	for (optval = ipoptp_first(&opts, ipha);
24358 	    optval != IPOPT_EOL;
24359 	    optval = ipoptp_next(&opts)) {
24360 		opt = opts.ipoptp_cur;
24361 		optlen = opts.ipoptp_len;
24362 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
24363 		    optval, optlen));
24364 		switch (optval) {
24365 			uint32_t off;
24366 		case IPOPT_SSRR:
24367 		case IPOPT_LSRR:
24368 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
24369 				ip1dbg((
24370 				    "ip_wput_options: bad option offset\n"));
24371 				code = (char *)&opt[IPOPT_OLEN] -
24372 				    (char *)ipha;
24373 				goto param_prob;
24374 			}
24375 			off = opt[IPOPT_OFFSET];
24376 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
24377 			    ntohl(dst)));
24378 			/*
24379 			 * For strict: verify that dst is directly
24380 			 * reachable.
24381 			 */
24382 			if (optval == IPOPT_SSRR) {
24383 				ire = ire_ftable_lookup(dst, 0, 0,
24384 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
24385 				    MATCH_IRE_TYPE);
24386 				if (ire == NULL) {
24387 					ip1dbg(("ip_wput_options: SSRR not"
24388 					    " directly reachable: 0x%x\n",
24389 					    ntohl(dst)));
24390 					goto bad_src_route;
24391 				}
24392 				ire_refrele(ire);
24393 			}
24394 			break;
24395 		case IPOPT_RR:
24396 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
24397 				ip1dbg((
24398 				    "ip_wput_options: bad option offset\n"));
24399 				code = (char *)&opt[IPOPT_OLEN] -
24400 				    (char *)ipha;
24401 				goto param_prob;
24402 			}
24403 			break;
24404 		case IPOPT_TS:
24405 			/*
24406 			 * Verify that length >=5 and that there is either
24407 			 * room for another timestamp or that the overflow
24408 			 * counter is not maxed out.
24409 			 */
24410 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
24411 			if (optlen < IPOPT_MINLEN_IT) {
24412 				goto param_prob;
24413 			}
24414 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
24415 				ip1dbg((
24416 				    "ip_wput_options: bad option offset\n"));
24417 				code = (char *)&opt[IPOPT_OFFSET] -
24418 				    (char *)ipha;
24419 				goto param_prob;
24420 			}
24421 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24422 			case IPOPT_TS_TSONLY:
24423 				off = IPOPT_TS_TIMELEN;
24424 				break;
24425 			case IPOPT_TS_TSANDADDR:
24426 			case IPOPT_TS_PRESPEC:
24427 			case IPOPT_TS_PRESPEC_RFC791:
24428 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
24429 				break;
24430 			default:
24431 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
24432 				    (char *)ipha;
24433 				goto param_prob;
24434 			}
24435 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
24436 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
24437 				/*
24438 				 * No room and the overflow counter is 15
24439 				 * already.
24440 				 */
24441 				goto param_prob;
24442 			}
24443 			break;
24444 		}
24445 	}
24446 
24447 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
24448 		return (0);
24449 
24450 	ip1dbg(("ip_wput_options: error processing IP options."));
24451 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
24452 
24453 param_prob:
24454 	/*
24455 	 * Since ip_wput() isn't close to finished, we fill
24456 	 * in enough of the header for credible error reporting.
24457 	 */
24458 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
24459 		/* Failed */
24460 		freemsg(ipsec_mp);
24461 		return (-1);
24462 	}
24463 	icmp_param_problem(q, ipsec_mp, (uint8_t)code);
24464 	return (-1);
24465 
24466 bad_src_route:
24467 	/*
24468 	 * Since ip_wput() isn't close to finished, we fill
24469 	 * in enough of the header for credible error reporting.
24470 	 */
24471 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
24472 		/* Failed */
24473 		freemsg(ipsec_mp);
24474 		return (-1);
24475 	}
24476 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED);
24477 	return (-1);
24478 }
24479 
24480 /*
24481  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
24482  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
24483  * thru /etc/system.
24484  */
24485 #define	CONN_MAXDRAINCNT	64
24486 
24487 static void
24488 conn_drain_init(void)
24489 {
24490 	int i;
24491 
24492 	conn_drain_list_cnt = conn_drain_nthreads;
24493 
24494 	if ((conn_drain_list_cnt == 0) ||
24495 	    (conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
24496 		/*
24497 		 * Default value of the number of drainers is the
24498 		 * number of cpus, subject to maximum of 8 drainers.
24499 		 */
24500 		if (boot_max_ncpus != -1)
24501 			conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
24502 		else
24503 			conn_drain_list_cnt = MIN(max_ncpus, 8);
24504 	}
24505 
24506 	conn_drain_list = kmem_zalloc(conn_drain_list_cnt * sizeof (idl_t),
24507 	    KM_SLEEP);
24508 
24509 	for (i = 0; i < conn_drain_list_cnt; i++) {
24510 		mutex_init(&conn_drain_list[i].idl_lock, NULL,
24511 		    MUTEX_DEFAULT, NULL);
24512 	}
24513 }
24514 
24515 static void
24516 conn_drain_fini(void)
24517 {
24518 	int i;
24519 
24520 	for (i = 0; i < conn_drain_list_cnt; i++)
24521 		mutex_destroy(&conn_drain_list[i].idl_lock);
24522 	kmem_free(conn_drain_list, conn_drain_list_cnt * sizeof (idl_t));
24523 	conn_drain_list = NULL;
24524 }
24525 
24526 /*
24527  * Note: For an overview of how flowcontrol is handled in IP please see the
24528  * IP Flowcontrol notes at the top of this file.
24529  *
24530  * Flow control has blocked us from proceeding. Insert the given conn in one
24531  * of the conn drain lists. These conn wq's will be qenabled later on when
24532  * STREAMS flow control does a backenable. conn_walk_drain will enable
24533  * the first conn in each of these drain lists. Each of these qenabled conns
24534  * in turn enables the next in the list, after it runs, or when it closes,
24535  * thus sustaining the drain process.
24536  *
24537  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
24538  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
24539  * running at any time, on a given conn, since there can be only 1 service proc
24540  * running on a queue at any time.
24541  */
24542 void
24543 conn_drain_insert(conn_t *connp)
24544 {
24545 	idl_t	*idl;
24546 	uint_t	index;
24547 
24548 	mutex_enter(&connp->conn_lock);
24549 	if (connp->conn_state_flags & CONN_CLOSING) {
24550 		/*
24551 		 * The conn is closing as a result of which CONN_CLOSING
24552 		 * is set. Return.
24553 		 */
24554 		mutex_exit(&connp->conn_lock);
24555 		return;
24556 	} else if (connp->conn_idl == NULL) {
24557 		/*
24558 		 * Assign the next drain list round robin. We dont' use
24559 		 * a lock, and thus it may not be strictly round robin.
24560 		 * Atomicity of load/stores is enough to make sure that
24561 		 * conn_drain_list_index is always within bounds.
24562 		 */
24563 		index = conn_drain_list_index;
24564 		ASSERT(index < conn_drain_list_cnt);
24565 		connp->conn_idl = &conn_drain_list[index];
24566 		index++;
24567 		if (index == conn_drain_list_cnt)
24568 			index = 0;
24569 		conn_drain_list_index = index;
24570 	}
24571 	mutex_exit(&connp->conn_lock);
24572 
24573 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
24574 	if ((connp->conn_drain_prev != NULL) ||
24575 	    (connp->conn_state_flags & CONN_CLOSING)) {
24576 		/*
24577 		 * The conn is already in the drain list, OR
24578 		 * the conn is closing. We need to check again for
24579 		 * the closing case again since close can happen
24580 		 * after we drop the conn_lock, and before we
24581 		 * acquire the CONN_DRAIN_LIST_LOCK.
24582 		 */
24583 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
24584 		return;
24585 	} else {
24586 		idl = connp->conn_idl;
24587 	}
24588 
24589 	/*
24590 	 * The conn is not in the drain list. Insert it at the
24591 	 * tail of the drain list. The drain list is circular
24592 	 * and doubly linked. idl_conn points to the 1st element
24593 	 * in the list.
24594 	 */
24595 	if (idl->idl_conn == NULL) {
24596 		idl->idl_conn = connp;
24597 		connp->conn_drain_next = connp;
24598 		connp->conn_drain_prev = connp;
24599 	} else {
24600 		conn_t *head = idl->idl_conn;
24601 
24602 		connp->conn_drain_next = head;
24603 		connp->conn_drain_prev = head->conn_drain_prev;
24604 		head->conn_drain_prev->conn_drain_next = connp;
24605 		head->conn_drain_prev = connp;
24606 	}
24607 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
24608 }
24609 
24610 /*
24611  * This conn is closing, and we are called from ip_close. OR
24612  * This conn has been serviced by ip_wsrv, and we need to do the tail
24613  * processing.
24614  * If this conn is part of the drain list, we may need to sustain the drain
24615  * process by qenabling the next conn in the drain list. We may also need to
24616  * remove this conn from the list, if it is done.
24617  */
24618 static void
24619 conn_drain_tail(conn_t *connp, boolean_t closing)
24620 {
24621 	idl_t *idl;
24622 
24623 	/*
24624 	 * connp->conn_idl is stable at this point, and no lock is needed
24625 	 * to check it. If we are called from ip_close, close has already
24626 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
24627 	 * called us only because conn_idl is non-null. If we are called thru
24628 	 * service, conn_idl could be null, but it cannot change because
24629 	 * service is single-threaded per queue, and there cannot be another
24630 	 * instance of service trying to call conn_drain_insert on this conn
24631 	 * now.
24632 	 */
24633 	ASSERT(!closing || (connp->conn_idl != NULL));
24634 
24635 	/*
24636 	 * If connp->conn_idl is null, the conn has not been inserted into any
24637 	 * drain list even once since creation of the conn. Just return.
24638 	 */
24639 	if (connp->conn_idl == NULL)
24640 		return;
24641 
24642 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
24643 
24644 	if (connp->conn_drain_prev == NULL) {
24645 		/* This conn is currently not in the drain list.  */
24646 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
24647 		return;
24648 	}
24649 	idl = connp->conn_idl;
24650 	if (idl->idl_conn_draining == connp) {
24651 		/*
24652 		 * This conn is the current drainer. If this is the last conn
24653 		 * in the drain list, we need to do more checks, in the 'if'
24654 		 * below. Otherwwise we need to just qenable the next conn,
24655 		 * to sustain the draining, and is handled in the 'else'
24656 		 * below.
24657 		 */
24658 		if (connp->conn_drain_next == idl->idl_conn) {
24659 			/*
24660 			 * This conn is the last in this list. This round
24661 			 * of draining is complete. If idl_repeat is set,
24662 			 * it means another flow enabling has happened from
24663 			 * the driver/streams and we need to another round
24664 			 * of draining.
24665 			 * If there are more than 2 conns in the drain list,
24666 			 * do a left rotate by 1, so that all conns except the
24667 			 * conn at the head move towards the head by 1, and the
24668 			 * the conn at the head goes to the tail. This attempts
24669 			 * a more even share for all queues that are being
24670 			 * drained.
24671 			 */
24672 			if ((connp->conn_drain_next != connp) &&
24673 			    (idl->idl_conn->conn_drain_next != connp)) {
24674 				idl->idl_conn = idl->idl_conn->conn_drain_next;
24675 			}
24676 			if (idl->idl_repeat) {
24677 				qenable(idl->idl_conn->conn_wq);
24678 				idl->idl_conn_draining = idl->idl_conn;
24679 				idl->idl_repeat = 0;
24680 			} else {
24681 				idl->idl_conn_draining = NULL;
24682 			}
24683 		} else {
24684 			/*
24685 			 * If the next queue that we are now qenable'ing,
24686 			 * is closing, it will remove itself from this list
24687 			 * and qenable the subsequent queue in ip_close().
24688 			 * Serialization is acheived thru idl_lock.
24689 			 */
24690 			qenable(connp->conn_drain_next->conn_wq);
24691 			idl->idl_conn_draining = connp->conn_drain_next;
24692 		}
24693 	}
24694 	if (!connp->conn_did_putbq || closing) {
24695 		/*
24696 		 * Remove ourself from the drain list, if we did not do
24697 		 * a putbq, or if the conn is closing.
24698 		 * Note: It is possible that q->q_first is non-null. It means
24699 		 * that these messages landed after we did a enableok() in
24700 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
24701 		 * service them.
24702 		 */
24703 		if (connp->conn_drain_next == connp) {
24704 			/* Singleton in the list */
24705 			ASSERT(connp->conn_drain_prev == connp);
24706 			idl->idl_conn = NULL;
24707 			idl->idl_conn_draining = NULL;
24708 		} else {
24709 			connp->conn_drain_prev->conn_drain_next =
24710 			    connp->conn_drain_next;
24711 			connp->conn_drain_next->conn_drain_prev =
24712 			    connp->conn_drain_prev;
24713 			if (idl->idl_conn == connp)
24714 				idl->idl_conn = connp->conn_drain_next;
24715 			ASSERT(idl->idl_conn_draining != connp);
24716 
24717 		}
24718 		connp->conn_drain_next = NULL;
24719 		connp->conn_drain_prev = NULL;
24720 	}
24721 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
24722 }
24723 
24724 /*
24725  * Write service routine. Shared perimeter entry point.
24726  * ip_wsrv can be called in any of the following ways.
24727  * 1. The device queue's messages has fallen below the low water mark
24728  *    and STREAMS has backenabled the ill_wq. We walk thru all the
24729  *    the drain lists and backenable the first conn in each list.
24730  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
24731  *    qenabled non-tcp upper layers. We start dequeing messages and call
24732  *    ip_wput for each message.
24733  */
24734 
24735 void
24736 ip_wsrv(queue_t *q)
24737 {
24738 	conn_t	*connp;
24739 	ill_t	*ill;
24740 	mblk_t	*mp;
24741 
24742 	if (q->q_next) {
24743 		ill = (ill_t *)q->q_ptr;
24744 		if (ill->ill_state_flags == 0) {
24745 			/*
24746 			 * The device flow control has opened up.
24747 			 * Walk through conn drain lists and qenable the
24748 			 * first conn in each list. This makes sense only
24749 			 * if the stream is fully plumbed and setup.
24750 			 * Hence the if check above.
24751 			 */
24752 			ip1dbg(("ip_wsrv: walking\n"));
24753 			conn_walk_drain();
24754 		}
24755 		return;
24756 	}
24757 
24758 	connp = Q_TO_CONN(q);
24759 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
24760 
24761 	/*
24762 	 * 1. Set conn_draining flag to signal that service is active.
24763 	 *
24764 	 * 2. ip_output determines whether it has been called from service,
24765 	 *    based on the last parameter. If it is IP_WSRV it concludes it
24766 	 *    has been called from service.
24767 	 *
24768 	 * 3. Message ordering is preserved by the following logic.
24769 	 *    i. A directly called ip_output (i.e. not thru service) will queue
24770 	 *    the message at the tail, if conn_draining is set (i.e. service
24771 	 *    is running) or if q->q_first is non-null.
24772 	 *
24773 	 *    ii. If ip_output is called from service, and if ip_output cannot
24774 	 *    putnext due to flow control, it does a putbq.
24775 	 *
24776 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
24777 	 *    (causing an infinite loop).
24778 	 */
24779 	ASSERT(!connp->conn_did_putbq);
24780 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
24781 		connp->conn_draining = 1;
24782 		noenable(q);
24783 		while ((mp = getq(q)) != NULL) {
24784 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
24785 			if (connp->conn_did_putbq) {
24786 				/* ip_wput did a putbq */
24787 				break;
24788 			}
24789 		}
24790 		/*
24791 		 * At this point, a thread coming down from top, calling
24792 		 * ip_wput, may end up queueing the message. We have not yet
24793 		 * enabled the queue, so ip_wsrv won't be called again.
24794 		 * To avoid this race, check q->q_first again (in the loop)
24795 		 * If the other thread queued the message before we call
24796 		 * enableok(), we will catch it in the q->q_first check.
24797 		 * If the other thread queues the message after we call
24798 		 * enableok(), ip_wsrv will be called again by STREAMS.
24799 		 */
24800 		connp->conn_draining = 0;
24801 		enableok(q);
24802 	}
24803 
24804 	/* Enable the next conn for draining */
24805 	conn_drain_tail(connp, B_FALSE);
24806 
24807 	connp->conn_did_putbq = 0;
24808 }
24809 
24810 /*
24811  * Walk the list of all conn's calling the function provided with the
24812  * specified argument for each.	 Note that this only walks conn's that
24813  * have been bound.
24814  * Applies to both IPv4 and IPv6.
24815  */
24816 static void
24817 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid)
24818 {
24819 	conn_walk_fanout_table(ipcl_udp_fanout, ipcl_udp_fanout_size,
24820 	    func, arg, zoneid);
24821 	conn_walk_fanout_table(ipcl_conn_fanout, ipcl_conn_fanout_size,
24822 	    func, arg, zoneid);
24823 	conn_walk_fanout_table(ipcl_bind_fanout, ipcl_bind_fanout_size,
24824 	    func, arg, zoneid);
24825 	conn_walk_fanout_table(ipcl_proto_fanout,
24826 	    A_CNT(ipcl_proto_fanout), func, arg, zoneid);
24827 	conn_walk_fanout_table(ipcl_proto_fanout_v6,
24828 	    A_CNT(ipcl_proto_fanout_v6), func, arg, zoneid);
24829 }
24830 
24831 /*
24832  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
24833  * of conns that need to be drained, check if drain is already in progress.
24834  * If so set the idl_repeat bit, indicating that the last conn in the list
24835  * needs to reinitiate the drain once again, for the list. If drain is not
24836  * in progress for the list, initiate the draining, by qenabling the 1st
24837  * conn in the list. The drain is self-sustaining, each qenabled conn will
24838  * in turn qenable the next conn, when it is done/blocked/closing.
24839  */
24840 static void
24841 conn_walk_drain(void)
24842 {
24843 	int i;
24844 	idl_t *idl;
24845 
24846 	IP_STAT(ip_conn_walk_drain);
24847 
24848 	for (i = 0; i < conn_drain_list_cnt; i++) {
24849 		idl = &conn_drain_list[i];
24850 		mutex_enter(&idl->idl_lock);
24851 		if (idl->idl_conn == NULL) {
24852 			mutex_exit(&idl->idl_lock);
24853 			continue;
24854 		}
24855 		/*
24856 		 * If this list is not being drained currently by
24857 		 * an ip_wsrv thread, start the process.
24858 		 */
24859 		if (idl->idl_conn_draining == NULL) {
24860 			ASSERT(idl->idl_repeat == 0);
24861 			qenable(idl->idl_conn->conn_wq);
24862 			idl->idl_conn_draining = idl->idl_conn;
24863 		} else {
24864 			idl->idl_repeat = 1;
24865 		}
24866 		mutex_exit(&idl->idl_lock);
24867 	}
24868 }
24869 
24870 /*
24871  * Walk an conn hash table of `count' buckets, calling func for each entry.
24872  */
24873 static void
24874 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
24875     zoneid_t zoneid)
24876 {
24877 	conn_t	*connp;
24878 
24879 	while (count-- > 0) {
24880 		mutex_enter(&connfp->connf_lock);
24881 		for (connp = connfp->connf_head; connp != NULL;
24882 		    connp = connp->conn_next) {
24883 			if (zoneid == GLOBAL_ZONEID ||
24884 			    zoneid == connp->conn_zoneid) {
24885 				CONN_INC_REF(connp);
24886 				mutex_exit(&connfp->connf_lock);
24887 				(*func)(connp, arg);
24888 				mutex_enter(&connfp->connf_lock);
24889 				CONN_DEC_REF(connp);
24890 			}
24891 		}
24892 		mutex_exit(&connfp->connf_lock);
24893 		connfp++;
24894 	}
24895 }
24896 
24897 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
24898 static void
24899 conn_report1(conn_t *connp, void *mp)
24900 {
24901 	char	buf1[INET6_ADDRSTRLEN];
24902 	char	buf2[INET6_ADDRSTRLEN];
24903 	uint_t	print_len, buf_len;
24904 
24905 	ASSERT(connp != NULL);
24906 
24907 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
24908 	if (buf_len <= 0)
24909 		return;
24910 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
24911 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
24912 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
24913 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
24914 	    "%5d %s/%05d %s/%05d\n",
24915 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
24916 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
24917 	    buf1, connp->conn_lport,
24918 	    buf2, connp->conn_fport);
24919 	if (print_len < buf_len) {
24920 		((mblk_t *)mp)->b_wptr += print_len;
24921 	} else {
24922 		((mblk_t *)mp)->b_wptr += buf_len;
24923 	}
24924 }
24925 
24926 /*
24927  * Named Dispatch routine to produce a formatted report on all conns
24928  * that are listed in one of the fanout tables.
24929  * This report is accessed by using the ndd utility to "get" ND variable
24930  * "ip_conn_status".
24931  */
24932 /* ARGSUSED */
24933 static int
24934 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
24935 {
24936 	(void) mi_mpprintf(mp,
24937 	    "CONN      " MI_COL_HDRPAD_STR
24938 	    "rfq      " MI_COL_HDRPAD_STR
24939 	    "stq      " MI_COL_HDRPAD_STR
24940 	    " zone local                 remote");
24941 
24942 	/*
24943 	 * Because of the ndd constraint, at most we can have 64K buffer
24944 	 * to put in all conn info.  So to be more efficient, just
24945 	 * allocate a 64K buffer here, assuming we need that large buffer.
24946 	 * This should be OK as only privileged processes can do ndd /dev/ip.
24947 	 */
24948 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
24949 		/* The following may work even if we cannot get a large buf. */
24950 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
24951 		return (0);
24952 	}
24953 
24954 	conn_walk_fanout(conn_report1, mp->b_cont, Q_TO_CONN(q)->conn_zoneid);
24955 	return (0);
24956 }
24957 
24958 /*
24959  * Determine if the ill and multicast aspects of that packets
24960  * "matches" the conn.
24961  */
24962 boolean_t
24963 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
24964     zoneid_t zoneid)
24965 {
24966 	ill_t *in_ill;
24967 	boolean_t found;
24968 	ipif_t *ipif;
24969 	ire_t *ire;
24970 	ipaddr_t dst, src;
24971 
24972 	dst = ipha->ipha_dst;
24973 	src = ipha->ipha_src;
24974 
24975 	/*
24976 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
24977 	 * unicast, broadcast and multicast reception to
24978 	 * conn_incoming_ill. conn_wantpacket itself is called
24979 	 * only for BROADCAST and multicast.
24980 	 *
24981 	 * 1) ip_rput supresses duplicate broadcasts if the ill
24982 	 *    is part of a group. Hence, we should be receiving
24983 	 *    just one copy of broadcast for the whole group.
24984 	 *    Thus, if it is part of the group the packet could
24985 	 *    come on any ill of the group and hence we need a
24986 	 *    match on the group. Otherwise, match on ill should
24987 	 *    be sufficient.
24988 	 *
24989 	 * 2) ip_rput does not suppress duplicate multicast packets.
24990 	 *    If there are two interfaces in a ill group and we have
24991 	 *    2 applications (conns) joined a multicast group G on
24992 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
24993 	 *    will give us two packets because we join G on both the
24994 	 *    interfaces rather than nominating just one interface
24995 	 *    for receiving multicast like broadcast above. So,
24996 	 *    we have to call ilg_lookup_ill to filter out duplicate
24997 	 *    copies, if ill is part of a group.
24998 	 */
24999 	in_ill = connp->conn_incoming_ill;
25000 	if (in_ill != NULL) {
25001 		if (in_ill->ill_group == NULL) {
25002 			if (in_ill != ill)
25003 				return (B_FALSE);
25004 		} else if (in_ill->ill_group != ill->ill_group) {
25005 			return (B_FALSE);
25006 		}
25007 	}
25008 
25009 	if (!CLASSD(dst)) {
25010 		if (connp->conn_zoneid == zoneid)
25011 			return (B_TRUE);
25012 		/*
25013 		 * The conn is in a different zone; we need to check that this
25014 		 * broadcast address is configured in the application's zone and
25015 		 * on one ill in the group.
25016 		 */
25017 		ipif = ipif_get_next_ipif(NULL, ill);
25018 		if (ipif == NULL)
25019 			return (B_FALSE);
25020 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
25021 		    connp->conn_zoneid, (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
25022 		ipif_refrele(ipif);
25023 		if (ire != NULL) {
25024 			ire_refrele(ire);
25025 			return (B_TRUE);
25026 		} else {
25027 			return (B_FALSE);
25028 		}
25029 	}
25030 
25031 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
25032 	    connp->conn_zoneid == zoneid) {
25033 		/*
25034 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
25035 		 * disabled, therefore we don't dispatch the multicast packet to
25036 		 * the sending zone.
25037 		 */
25038 		return (B_FALSE);
25039 	}
25040 
25041 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
25042 	    connp->conn_zoneid != zoneid) {
25043 		/*
25044 		 * Multicast packet on the loopback interface: we only match
25045 		 * conns who joined the group in the specified zone.
25046 		 */
25047 		return (B_FALSE);
25048 	}
25049 
25050 	if (connp->conn_multi_router) {
25051 		/* multicast packet and multicast router socket: send up */
25052 		return (B_TRUE);
25053 	}
25054 
25055 	mutex_enter(&connp->conn_lock);
25056 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
25057 	mutex_exit(&connp->conn_lock);
25058 	return (found);
25059 }
25060 
25061 /*
25062  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
25063  */
25064 /* ARGSUSED */
25065 static void
25066 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
25067 {
25068 	ill_t *ill = (ill_t *)q->q_ptr;
25069 	mblk_t	*mp1, *mp2;
25070 	ipif_t  *ipif;
25071 	int err = 0;
25072 	conn_t *connp = NULL;
25073 	ipsq_t	*ipsq;
25074 	arc_t	*arc;
25075 
25076 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
25077 
25078 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
25079 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
25080 
25081 	ASSERT(IAM_WRITER_ILL(ill));
25082 	mp2 = mp->b_cont;
25083 	mp->b_cont = NULL;
25084 
25085 	/*
25086 	 * We have now received the arp bringup completion message
25087 	 * from ARP. Mark the arp bringup as done. Also if the arp
25088 	 * stream has already started closing, send up the AR_ARP_CLOSING
25089 	 * ack now since ARP is waiting in close for this ack.
25090 	 */
25091 	mutex_enter(&ill->ill_lock);
25092 	ill->ill_arp_bringup_pending = 0;
25093 	if (ill->ill_arp_closing) {
25094 		mutex_exit(&ill->ill_lock);
25095 		/* Let's reuse the mp for sending the ack */
25096 		arc = (arc_t *)mp->b_rptr;
25097 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
25098 		arc->arc_cmd = AR_ARP_CLOSING;
25099 		qreply(q, mp);
25100 	} else {
25101 		mutex_exit(&ill->ill_lock);
25102 		freeb(mp);
25103 	}
25104 
25105 	/* We should have an IOCTL waiting on this. */
25106 	ipsq = ill->ill_phyint->phyint_ipsq;
25107 	ipif = ipsq->ipsq_pending_ipif;
25108 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
25109 	ASSERT(!((mp1 != NULL)  ^ (ipif != NULL)));
25110 	if (mp1 == NULL) {
25111 		/* bringup was aborted by the user */
25112 		freemsg(mp2);
25113 		return;
25114 	}
25115 	ASSERT(connp != NULL);
25116 	q = CONNP_TO_WQ(connp);
25117 	/*
25118 	 * If the DL_BIND_REQ fails, it is noted
25119 	 * in arc_name_offset.
25120 	 */
25121 	err = *((int *)mp2->b_rptr);
25122 	if (err == 0) {
25123 		if (ipif->ipif_isv6) {
25124 			if ((err = ipif_up_done_v6(ipif)) != 0)
25125 				ip0dbg(("ip_arp_done: init failed\n"));
25126 		} else {
25127 			if ((err = ipif_up_done(ipif)) != 0)
25128 				ip0dbg(("ip_arp_done: init failed\n"));
25129 		}
25130 	} else {
25131 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
25132 	}
25133 
25134 	freemsg(mp2);
25135 
25136 	if ((err == 0) && (ill->ill_up_ipifs)) {
25137 		err = ill_up_ipifs(ill, q, mp1);
25138 		if (err == EINPROGRESS)
25139 			return;
25140 	}
25141 
25142 	if (ill->ill_up_ipifs) {
25143 		ill_group_cleanup(ill);
25144 	}
25145 
25146 	/*
25147 	 * The ioctl must complete now without EINPROGRESS
25148 	 * since ipsq_pending_mp_get has removed the ioctl mblk
25149 	 * from ipsq_pending_mp. Otherwise the ioctl will be
25150 	 * stuck for ever in the ipsq.
25151 	 */
25152 	ASSERT(err != EINPROGRESS);
25153 	ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipif, ipsq);
25154 }
25155 
25156 /* Allocate the private structure */
25157 static int
25158 ip_priv_alloc(void **bufp)
25159 {
25160 	void	*buf;
25161 
25162 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
25163 		return (ENOMEM);
25164 
25165 	*bufp = buf;
25166 	return (0);
25167 }
25168 
25169 /* Function to delete the private structure */
25170 void
25171 ip_priv_free(void *buf)
25172 {
25173 	ASSERT(buf != NULL);
25174 	kmem_free(buf, sizeof (ip_priv_t));
25175 }
25176 
25177 /*
25178  * The entry point for IPPF processing.
25179  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
25180  * routine just returns.
25181  *
25182  * When called, ip_process generates an ipp_packet_t structure
25183  * which holds the state information for this packet and invokes the
25184  * the classifier (via ipp_packet_process). The classification, depending on
25185  * configured filters, results in a list of actions for this packet. Invoking
25186  * an action may cause the packet to be dropped, in which case the resulting
25187  * mblk (*mpp) is NULL. proc indicates the callout position for
25188  * this packet and ill_index is the interface this packet on or will leave
25189  * on (inbound and outbound resp.).
25190  */
25191 void
25192 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
25193 {
25194 	mblk_t		*mp;
25195 	ip_priv_t	*priv;
25196 	ipp_action_id_t	aid;
25197 	int		rc = 0;
25198 	ipp_packet_t	*pp;
25199 #define	IP_CLASS	"ip"
25200 
25201 	/* If the classifier is not loaded, return  */
25202 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
25203 		return;
25204 	}
25205 
25206 	mp = *mpp;
25207 	ASSERT(mp != NULL);
25208 
25209 	/* Allocate the packet structure */
25210 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
25211 	if (rc != 0) {
25212 		*mpp = NULL;
25213 		freemsg(mp);
25214 		return;
25215 	}
25216 
25217 	/* Allocate the private structure */
25218 	rc = ip_priv_alloc((void **)&priv);
25219 	if (rc != 0) {
25220 		*mpp = NULL;
25221 		freemsg(mp);
25222 		ipp_packet_free(pp);
25223 		return;
25224 	}
25225 	priv->proc = proc;
25226 	priv->ill_index = ill_index;
25227 	ipp_packet_set_private(pp, priv, ip_priv_free);
25228 	ipp_packet_set_data(pp, mp);
25229 
25230 	/* Invoke the classifier */
25231 	rc = ipp_packet_process(&pp);
25232 	if (pp != NULL) {
25233 		mp = ipp_packet_get_data(pp);
25234 		ipp_packet_free(pp);
25235 		if (rc != 0) {
25236 			freemsg(mp);
25237 			*mpp = NULL;
25238 		}
25239 	} else {
25240 		*mpp = NULL;
25241 	}
25242 #undef	IP_CLASS
25243 }
25244 
25245 /*
25246  * Propagate a multicast group membership operation (add/drop) on
25247  * all the interfaces crossed by the related multirt routes.
25248  * The call is considered successful if the operation succeeds
25249  * on at least one interface.
25250  */
25251 static int
25252 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
25253     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
25254     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
25255     mblk_t *first_mp)
25256 {
25257 	ire_t		*ire_gw;
25258 	irb_t		*irb;
25259 	int		error = 0;
25260 	opt_restart_t	*or;
25261 
25262 	irb = ire->ire_bucket;
25263 	ASSERT(irb != NULL);
25264 
25265 	ASSERT(DB_TYPE(first_mp) == M_CTL);
25266 
25267 	or = (opt_restart_t *)first_mp->b_rptr;
25268 	IRB_REFHOLD(irb);
25269 	for (; ire != NULL; ire = ire->ire_next) {
25270 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
25271 			continue;
25272 		if (ire->ire_addr != group)
25273 			continue;
25274 
25275 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
25276 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
25277 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE);
25278 		/* No resolver exists for the gateway; skip this ire. */
25279 		if (ire_gw == NULL)
25280 			continue;
25281 
25282 		/*
25283 		 * This function can return EINPROGRESS. If so the operation
25284 		 * will be restarted from ip_restart_optmgmt which will
25285 		 * call ip_opt_set and option processing will restart for
25286 		 * this option. So we may end up calling 'fn' more than once.
25287 		 * This requires that 'fn' is idempotent except for the
25288 		 * return value. The operation is considered a success if
25289 		 * it succeeds at least once on any one interface.
25290 		 */
25291 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
25292 		    NULL, fmode, src, first_mp);
25293 		if (error == 0)
25294 			or->or_private = CGTP_MCAST_SUCCESS;
25295 
25296 		if (ip_debug > 0) {
25297 			ulong_t	off;
25298 			char	*ksym;
25299 			ksym = kobj_getsymname((uintptr_t)fn, &off);
25300 			ip2dbg(("ip_multirt_apply_membership: "
25301 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
25302 			    "error %d [success %u]\n",
25303 			    ksym ? ksym : "?",
25304 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
25305 			    error, or->or_private));
25306 		}
25307 
25308 		ire_refrele(ire_gw);
25309 		if (error == EINPROGRESS) {
25310 			IRB_REFRELE(irb);
25311 			return (error);
25312 		}
25313 	}
25314 	IRB_REFRELE(irb);
25315 	/*
25316 	 * Consider the call as successful if we succeeded on at least
25317 	 * one interface. Otherwise, return the last encountered error.
25318 	 */
25319 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
25320 }
25321 
25322 
25323 /*
25324  * Issue a warning regarding a route crossing an interface with an
25325  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
25326  * amount of time is logged.
25327  */
25328 static void
25329 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
25330 {
25331 	hrtime_t	current = gethrtime();
25332 	char		buf[16];
25333 
25334 	/* Convert interval in ms to hrtime in ns */
25335 	if (multirt_bad_mtu_last_time +
25336 	    ((hrtime_t)ip_multirt_log_interval * (hrtime_t)1000000) <=
25337 	    current) {
25338 		cmn_err(CE_WARN, "ip: ignoring multiroute "
25339 		    "to %s, incorrect MTU %u (expected %u)\n",
25340 		    ip_dot_addr(ire->ire_addr, buf),
25341 		    ire->ire_max_frag, max_frag);
25342 
25343 		multirt_bad_mtu_last_time = current;
25344 	}
25345 }
25346 
25347 
25348 /*
25349  * Get the CGTP (multirouting) filtering status.
25350  * If 0, the CGTP hooks are transparent.
25351  */
25352 /* ARGSUSED */
25353 static int
25354 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
25355 {
25356 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
25357 
25358 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
25359 	return (0);
25360 }
25361 
25362 
25363 /*
25364  * Set the CGTP (multirouting) filtering status.
25365  * If the status is changed from active to transparent
25366  * or from transparent to active, forward the new status
25367  * to the filtering module (if loaded).
25368  */
25369 /* ARGSUSED */
25370 static int
25371 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
25372     cred_t *ioc_cr)
25373 {
25374 	long		new_value;
25375 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
25376 
25377 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
25378 	    new_value < 0 || new_value > 1) {
25379 		return (EINVAL);
25380 	}
25381 
25382 	/*
25383 	 * Do not enable CGTP filtering - thus preventing the hooks
25384 	 * from being invoked - if the version number of the
25385 	 * filtering module hooks does not match.
25386 	 */
25387 	if ((ip_cgtp_filter_ops != NULL) &&
25388 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
25389 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
25390 		    "(module hooks version %d, expecting %d)\n",
25391 		    ip_cgtp_filter_ops->cfo_filter_rev, CGTP_FILTER_REV);
25392 		return (ENOTSUP);
25393 	}
25394 
25395 	if ((!*ip_cgtp_filter_value) && new_value) {
25396 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
25397 		    ip_cgtp_filter_ops == NULL ?
25398 		    " (module not loaded)" : "");
25399 	}
25400 	if (*ip_cgtp_filter_value && (!new_value)) {
25401 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
25402 		    ip_cgtp_filter_ops == NULL ?
25403 		    " (module not loaded)" : "");
25404 	}
25405 
25406 	if (ip_cgtp_filter_ops != NULL) {
25407 		int	res;
25408 		if ((res = ip_cgtp_filter_ops->cfo_change_state(new_value))) {
25409 			return (res);
25410 		}
25411 	}
25412 
25413 	*ip_cgtp_filter_value = (boolean_t)new_value;
25414 
25415 	return (0);
25416 }
25417 
25418 
25419 /*
25420  * Return the expected CGTP hooks version number.
25421  */
25422 int
25423 ip_cgtp_filter_supported(void)
25424 {
25425 	return (ip_cgtp_filter_rev);
25426 }
25427 
25428 
25429 /*
25430  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
25431  * or by invoking this function. In the first case, the version number
25432  * of the registered structure is checked at hooks activation time
25433  * in ip_cgtp_filter_set().
25434  */
25435 int
25436 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
25437 {
25438 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
25439 		return (ENOTSUP);
25440 
25441 	ip_cgtp_filter_ops = ops;
25442 	return (0);
25443 }
25444 
25445 static squeue_func_t
25446 ip_squeue_switch(int val)
25447 {
25448 	squeue_func_t rval = squeue_fill;
25449 
25450 	switch (val) {
25451 	case IP_SQUEUE_ENTER_NODRAIN:
25452 		rval = squeue_enter_nodrain;
25453 		break;
25454 	case IP_SQUEUE_ENTER:
25455 		rval = squeue_enter;
25456 		break;
25457 	default:
25458 		break;
25459 	}
25460 	return (rval);
25461 }
25462 
25463 /* ARGSUSED */
25464 static int
25465 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
25466     caddr_t addr, cred_t *cr)
25467 {
25468 	int *v = (int *)addr;
25469 	long new_value;
25470 
25471 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
25472 		return (EINVAL);
25473 
25474 	ip_input_proc = ip_squeue_switch(new_value);
25475 	*v = new_value;
25476 	return (0);
25477 }
25478 
25479 /* ARGSUSED */
25480 static int
25481 ip_fanout_set(queue_t *q, mblk_t *mp, char *value,
25482     caddr_t addr, cred_t *cr)
25483 {
25484 	int *v = (int *)addr;
25485 	long new_value;
25486 
25487 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
25488 		return (EINVAL);
25489 
25490 	*v = new_value;
25491 	return (0);
25492 }
25493 
25494 
25495 static void
25496 ip_kstat_init(void)
25497 {
25498 	ip_named_kstat_t template = {
25499 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
25500 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
25501 		{ "inReceives",		KSTAT_DATA_UINT32, 0 },
25502 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
25503 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
25504 		{ "forwDatagrams",	KSTAT_DATA_UINT32, 0 },
25505 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
25506 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
25507 		{ "inDelivers",		KSTAT_DATA_UINT32, 0 },
25508 		{ "outRequests",	KSTAT_DATA_UINT32, 0 },
25509 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
25510 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
25511 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
25512 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
25513 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
25514 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
25515 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
25516 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
25517 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
25518 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
25519 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
25520 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
25521 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
25522 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
25523 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
25524 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
25525 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
25526 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
25527 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
25528 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
25529 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
25530 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
25531 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
25532 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
25533 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
25534 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
25535 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
25536 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
25537 	};
25538 
25539 	ip_mibkp = kstat_create("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
25540 					NUM_OF_FIELDS(ip_named_kstat_t),
25541 					0);
25542 	if (!ip_mibkp)
25543 		return;
25544 
25545 	template.forwarding.value.ui32 = WE_ARE_FORWARDING ? 1:2;
25546 	template.defaultTTL.value.ui32 = (uint32_t)ip_def_ttl;
25547 	template.reasmTimeout.value.ui32 = ip_g_frag_timeout;
25548 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
25549 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
25550 
25551 	template.netToMediaEntrySize.value.i32 =
25552 		sizeof (mib2_ipNetToMediaEntry_t);
25553 
25554 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
25555 
25556 	bcopy(&template, ip_mibkp->ks_data, sizeof (template));
25557 
25558 	ip_mibkp->ks_update = ip_kstat_update;
25559 
25560 	kstat_install(ip_mibkp);
25561 }
25562 
25563 static void
25564 ip_kstat_fini(void)
25565 {
25566 
25567 	if (ip_mibkp != NULL) {
25568 		kstat_delete(ip_mibkp);
25569 		ip_mibkp = NULL;
25570 	}
25571 }
25572 
25573 static int
25574 ip_kstat_update(kstat_t *kp, int rw)
25575 {
25576 	ip_named_kstat_t *ipkp;
25577 
25578 	if (!kp || !kp->ks_data)
25579 		return (EIO);
25580 
25581 	if (rw == KSTAT_WRITE)
25582 		return (EACCES);
25583 
25584 	ipkp = (ip_named_kstat_t *)kp->ks_data;
25585 
25586 	ipkp->forwarding.value.ui32 =		ip_mib.ipForwarding;
25587 	ipkp->defaultTTL.value.ui32 =		ip_mib.ipDefaultTTL;
25588 	ipkp->inReceives.value.ui32 =		ip_mib.ipInReceives;
25589 	ipkp->inHdrErrors.value.ui32 =		ip_mib.ipInHdrErrors;
25590 	ipkp->inAddrErrors.value.ui32 =		ip_mib.ipInAddrErrors;
25591 	ipkp->forwDatagrams.value.ui32 =	ip_mib.ipForwDatagrams;
25592 	ipkp->inUnknownProtos.value.ui32 =	ip_mib.ipInUnknownProtos;
25593 	ipkp->inDiscards.value.ui32 =		ip_mib.ipInDiscards;
25594 	ipkp->inDelivers.value.ui32 =		ip_mib.ipInDelivers;
25595 	ipkp->outRequests.value.ui32 =		ip_mib.ipOutRequests;
25596 	ipkp->outDiscards.value.ui32 =		ip_mib.ipOutDiscards;
25597 	ipkp->outNoRoutes.value.ui32 =		ip_mib.ipOutNoRoutes;
25598 	ipkp->reasmTimeout.value.ui32 =		ip_mib.ipReasmTimeout;
25599 	ipkp->reasmReqds.value.ui32 =		ip_mib.ipReasmReqds;
25600 	ipkp->reasmOKs.value.ui32 =		ip_mib.ipReasmOKs;
25601 	ipkp->reasmFails.value.ui32 =		ip_mib.ipReasmFails;
25602 	ipkp->fragOKs.value.ui32 =		ip_mib.ipFragOKs;
25603 	ipkp->fragFails.value.ui32 =		ip_mib.ipFragFails;
25604 	ipkp->fragCreates.value.ui32 =		ip_mib.ipFragCreates;
25605 
25606 	ipkp->routingDiscards.value.ui32 =	ip_mib.ipRoutingDiscards;
25607 	ipkp->inErrs.value.ui32 =		ip_mib.tcpInErrs;
25608 	ipkp->noPorts.value.ui32 =		ip_mib.udpNoPorts;
25609 	ipkp->inCksumErrs.value.ui32 =		ip_mib.ipInCksumErrs;
25610 	ipkp->reasmDuplicates.value.ui32 =	ip_mib.ipReasmDuplicates;
25611 	ipkp->reasmPartDups.value.ui32 =	ip_mib.ipReasmPartDups;
25612 	ipkp->forwProhibits.value.ui32 =	ip_mib.ipForwProhibits;
25613 	ipkp->udpInCksumErrs.value.ui32 =	ip_mib.udpInCksumErrs;
25614 	ipkp->udpInOverflows.value.ui32 =	ip_mib.udpInOverflows;
25615 	ipkp->rawipInOverflows.value.ui32 =	ip_mib.rawipInOverflows;
25616 	ipkp->ipsecInSucceeded.value.ui32 =	ip_mib.ipsecInSucceeded;
25617 	ipkp->ipsecInFailed.value.i32 =		ip_mib.ipsecInFailed;
25618 
25619 	ipkp->inIPv6.value.ui32 =		ip_mib.ipInIPv6;
25620 	ipkp->outIPv6.value.ui32 =		ip_mib.ipOutIPv6;
25621 	ipkp->outSwitchIPv6.value.ui32 =	ip_mib.ipOutSwitchIPv6;
25622 
25623 	return (0);
25624 }
25625 
25626 static void
25627 icmp_kstat_init(void)
25628 {
25629 	icmp_named_kstat_t template = {
25630 		{ "inMsgs",		KSTAT_DATA_UINT32 },
25631 		{ "inErrors",		KSTAT_DATA_UINT32 },
25632 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
25633 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
25634 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
25635 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
25636 		{ "inRedirects",	KSTAT_DATA_UINT32 },
25637 		{ "inEchos",		KSTAT_DATA_UINT32 },
25638 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
25639 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
25640 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
25641 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
25642 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
25643 		{ "outMsgs",		KSTAT_DATA_UINT32 },
25644 		{ "outErrors",		KSTAT_DATA_UINT32 },
25645 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
25646 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
25647 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
25648 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
25649 		{ "outRedirects",	KSTAT_DATA_UINT32 },
25650 		{ "outEchos",		KSTAT_DATA_UINT32 },
25651 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
25652 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
25653 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
25654 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
25655 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
25656 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
25657 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
25658 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
25659 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
25660 		{ "outDrops",		KSTAT_DATA_UINT32 },
25661 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
25662 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
25663 	};
25664 
25665 	icmp_mibkp = kstat_create("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
25666 					NUM_OF_FIELDS(icmp_named_kstat_t),
25667 					0);
25668 	if (icmp_mibkp == NULL)
25669 		return;
25670 
25671 	bcopy(&template, icmp_mibkp->ks_data, sizeof (template));
25672 
25673 	icmp_mibkp->ks_update = icmp_kstat_update;
25674 
25675 	kstat_install(icmp_mibkp);
25676 }
25677 
25678 static void
25679 icmp_kstat_fini(void)
25680 {
25681 
25682 	if (icmp_mibkp != NULL) {
25683 		kstat_delete(icmp_mibkp);
25684 		icmp_mibkp = NULL;
25685 	}
25686 }
25687 
25688 static int
25689 icmp_kstat_update(kstat_t *kp, int rw)
25690 {
25691 	icmp_named_kstat_t *icmpkp;
25692 
25693 	if ((kp == NULL) || (kp->ks_data == NULL))
25694 		return (EIO);
25695 
25696 	if (rw == KSTAT_WRITE)
25697 		return (EACCES);
25698 
25699 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
25700 
25701 	icmpkp->inMsgs.value.ui32 =		icmp_mib.icmpInMsgs;
25702 	icmpkp->inErrors.value.ui32 =		icmp_mib.icmpInErrors;
25703 	icmpkp->inDestUnreachs.value.ui32 =	icmp_mib.icmpInDestUnreachs;
25704 	icmpkp->inTimeExcds.value.ui32 =	icmp_mib.icmpInTimeExcds;
25705 	icmpkp->inParmProbs.value.ui32 =	icmp_mib.icmpInParmProbs;
25706 	icmpkp->inSrcQuenchs.value.ui32 =	icmp_mib.icmpInSrcQuenchs;
25707 	icmpkp->inRedirects.value.ui32 =	icmp_mib.icmpInRedirects;
25708 	icmpkp->inEchos.value.ui32 =		icmp_mib.icmpInEchos;
25709 	icmpkp->inEchoReps.value.ui32 =		icmp_mib.icmpInEchoReps;
25710 	icmpkp->inTimestamps.value.ui32 =	icmp_mib.icmpInTimestamps;
25711 	icmpkp->inTimestampReps.value.ui32 =	icmp_mib.icmpInTimestampReps;
25712 	icmpkp->inAddrMasks.value.ui32 =	icmp_mib.icmpInAddrMasks;
25713 	icmpkp->inAddrMaskReps.value.ui32 =	icmp_mib.icmpInAddrMaskReps;
25714 	icmpkp->outMsgs.value.ui32 =		icmp_mib.icmpOutMsgs;
25715 	icmpkp->outErrors.value.ui32 =		icmp_mib.icmpOutErrors;
25716 	icmpkp->outDestUnreachs.value.ui32 =	icmp_mib.icmpOutDestUnreachs;
25717 	icmpkp->outTimeExcds.value.ui32 =	icmp_mib.icmpOutTimeExcds;
25718 	icmpkp->outParmProbs.value.ui32 =	icmp_mib.icmpOutParmProbs;
25719 	icmpkp->outSrcQuenchs.value.ui32 =	icmp_mib.icmpOutSrcQuenchs;
25720 	icmpkp->outRedirects.value.ui32 =	icmp_mib.icmpOutRedirects;
25721 	icmpkp->outEchos.value.ui32 =		icmp_mib.icmpOutEchos;
25722 	icmpkp->outEchoReps.value.ui32 =	icmp_mib.icmpOutEchoReps;
25723 	icmpkp->outTimestamps.value.ui32 =	icmp_mib.icmpOutTimestamps;
25724 	icmpkp->outTimestampReps.value.ui32 =	icmp_mib.icmpOutTimestampReps;
25725 	icmpkp->outAddrMasks.value.ui32 =	icmp_mib.icmpOutAddrMasks;
25726 	icmpkp->outAddrMaskReps.value.ui32 =	icmp_mib.icmpOutAddrMaskReps;
25727 	icmpkp->inCksumErrs.value.ui32 =	icmp_mib.icmpInCksumErrs;
25728 	icmpkp->inUnknowns.value.ui32 =		icmp_mib.icmpInUnknowns;
25729 	icmpkp->inFragNeeded.value.ui32 =	icmp_mib.icmpInFragNeeded;
25730 	icmpkp->outFragNeeded.value.ui32 =	icmp_mib.icmpOutFragNeeded;
25731 	icmpkp->outDrops.value.ui32 =		icmp_mib.icmpOutDrops;
25732 	icmpkp->inOverflows.value.ui32 =	icmp_mib.icmpInOverflows;
25733 	icmpkp->inBadRedirects.value.ui32 =	icmp_mib.icmpInBadRedirects;
25734 
25735 	return (0);
25736 }
25737 
25738 /*
25739  * This is the fanout function for raw socket opened for SCTP.  Note
25740  * that it is called after SCTP checks that there is no socket which
25741  * wants a packet.  Then before SCTP handles this out of the blue packet,
25742  * this function is called to see if there is any raw socket for SCTP.
25743  * If there is and it is bound to the correct address, the packet will
25744  * be sent to that socket.  Note that only one raw socket can be bound to
25745  * a port.  This is assured in ipcl_sctp_hash_insert();
25746  */
25747 void
25748 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
25749     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
25750     uint_t ipif_seqid, zoneid_t zoneid)
25751 {
25752 	conn_t		*connp;
25753 	queue_t		*rq;
25754 	mblk_t		*first_mp;
25755 	boolean_t	secure;
25756 	ip6_t		*ip6h;
25757 
25758 	first_mp = mp;
25759 	if (mctl_present) {
25760 		mp = first_mp->b_cont;
25761 		secure = ipsec_in_is_secure(first_mp);
25762 		ASSERT(mp != NULL);
25763 	} else {
25764 		secure = B_FALSE;
25765 	}
25766 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
25767 
25768 	connp = ipcl_classify_raw(IPPROTO_SCTP, zoneid, ports, ipha);
25769 	if (connp == NULL) {
25770 		sctp_ootb_input(first_mp, recv_ill, ipif_seqid, zoneid,
25771 		    mctl_present);
25772 		return;
25773 	}
25774 	rq = connp->conn_rq;
25775 	if (!canputnext(rq)) {
25776 		CONN_DEC_REF(connp);
25777 		BUMP_MIB(&ip_mib, rawipInOverflows);
25778 		freemsg(first_mp);
25779 		return;
25780 	}
25781 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp) :
25782 	    CONN_INBOUND_POLICY_PRESENT_V6(connp)) || secure) {
25783 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
25784 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
25785 		if (first_mp == NULL) {
25786 			CONN_DEC_REF(connp);
25787 			return;
25788 		}
25789 	}
25790 	/*
25791 	 * We probably should not send M_CTL message up to
25792 	 * raw socket.
25793 	 */
25794 	if (mctl_present)
25795 		freeb(first_mp);
25796 
25797 	/* Initiate IPPF processing here if needed. */
25798 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) ||
25799 	    (!isv4 && IP6_IN_IPP(flags))) {
25800 		ip_process(IPP_LOCAL_IN, &mp,
25801 		    recv_ill->ill_phyint->phyint_ifindex);
25802 		if (mp == NULL) {
25803 			CONN_DEC_REF(connp);
25804 			return;
25805 		}
25806 	}
25807 
25808 	if (connp->conn_recvif || connp->conn_recvslla ||
25809 	    ((connp->conn_ipv6_recvpktinfo ||
25810 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
25811 	    (flags & IP_FF_IP6INFO))) {
25812 		int in_flags = 0;
25813 
25814 		if (connp->conn_recvif || connp->conn_ipv6_recvpktinfo) {
25815 			in_flags = IPF_RECVIF;
25816 		}
25817 		if (connp->conn_recvslla) {
25818 			in_flags |= IPF_RECVSLLA;
25819 		}
25820 		if (isv4) {
25821 			mp = ip_add_info(mp, recv_ill, in_flags);
25822 		} else {
25823 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
25824 			if (mp == NULL) {
25825 				CONN_DEC_REF(connp);
25826 				return;
25827 			}
25828 		}
25829 	}
25830 
25831 	BUMP_MIB(&ip_mib, ipInDelivers);
25832 	/*
25833 	 * We are sending the IPSEC_IN message also up. Refer
25834 	 * to comments above this function.
25835 	 */
25836 	putnext(rq, mp);
25837 	CONN_DEC_REF(connp);
25838 }
25839 
25840 /*
25841  * Martian Address Filtering [RFC 1812, Section 5.3.7]
25842  */
25843 static boolean_t
25844 ip_no_forward(ipha_t *ipha, ill_t *ill)
25845 {
25846 	ipaddr_t ip_src, ip_dst;
25847 	ire_t *src_ire = NULL;
25848 
25849 	ip_src = ntohl(ipha->ipha_src);
25850 	ip_dst = ntohl(ipha->ipha_dst);
25851 
25852 	if (ip_dst == INADDR_ANY)
25853 		goto dont_forward;
25854 
25855 	if (IN_CLASSD(ip_src))
25856 		goto dont_forward;
25857 
25858 	if ((ip_src >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
25859 		goto dont_forward;
25860 
25861 	if (IN_BADCLASS(ip_dst))
25862 		goto dont_forward;
25863 
25864 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
25865 	    ALL_ZONES, MATCH_IRE_TYPE);
25866 	if (src_ire != NULL) {
25867 		ire_refrele(src_ire);
25868 		goto dont_forward;
25869 	}
25870 
25871 	return (B_FALSE);
25872 
25873 dont_forward:
25874 	if (ip_debug > 2) {
25875 		printf("ip_no_forward: dropping packet received on %s\n",
25876 		    ill->ill_name);
25877 		pr_addr_dbg("ip_no_forward: from src %s\n",
25878 		    AF_INET, &ipha->ipha_src);
25879 		pr_addr_dbg("ip_no_forward: to dst %s\n",
25880 		    AF_INET, &ipha->ipha_dst);
25881 	}
25882 	BUMP_MIB(&ip_mib, ipForwProhibits);
25883 	return (B_TRUE);
25884 }
25885 
25886 static boolean_t
25887 ip_loopback_src_or_dst(ipha_t *ipha, ill_t *ill)
25888 {
25889 	if (((ntohl(ipha->ipha_src) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) ||
25890 	    ((ntohl(ipha->ipha_dst) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)) {
25891 		if (ip_debug > 2) {
25892 			if (ill != NULL) {
25893 				printf("ip_loopback_src_or_dst: "
25894 				    "dropping packet received on %s\n",
25895 				    ill->ill_name);
25896 			} else {
25897 				printf("ip_loopback_src_or_dst: "
25898 				    "dropping packet\n");
25899 			}
25900 
25901 			pr_addr_dbg(
25902 			    "ip_loopback_src_or_dst: from src %s\n",
25903 			    AF_INET, &ipha->ipha_src);
25904 			pr_addr_dbg(
25905 			    "ip_loopback_src_or_dst: to dst %s\n",
25906 			    AF_INET, &ipha->ipha_dst);
25907 		}
25908 
25909 		BUMP_MIB(&ip_mib, ipInAddrErrors);
25910 		return (B_TRUE);
25911 	}
25912 	return (B_FALSE);
25913 }
25914