xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 3d393ee6c37fa10ac512ed6d36109ad616dc7c1a)
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 (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/dlpi.h>
31 #include <sys/stropts.h>
32 #include <sys/sysmacros.h>
33 #include <sys/strsubr.h>
34 #include <sys/strlog.h>
35 #include <sys/strsun.h>
36 #include <sys/zone.h>
37 #define	_SUN_TPI_VERSION 2
38 #include <sys/tihdr.h>
39 #include <sys/xti_inet.h>
40 #include <sys/ddi.h>
41 #include <sys/cmn_err.h>
42 #include <sys/debug.h>
43 #include <sys/kobj.h>
44 #include <sys/modctl.h>
45 #include <sys/atomic.h>
46 #include <sys/policy.h>
47 #include <sys/priv.h>
48 #include <sys/taskq.h>
49 
50 #include <sys/systm.h>
51 #include <sys/param.h>
52 #include <sys/kmem.h>
53 #include <sys/sdt.h>
54 #include <sys/socket.h>
55 #include <sys/vtrace.h>
56 #include <sys/isa_defs.h>
57 #include <sys/mac.h>
58 #include <net/if.h>
59 #include <net/if_arp.h>
60 #include <net/route.h>
61 #include <sys/sockio.h>
62 #include <netinet/in.h>
63 #include <net/if_dl.h>
64 
65 #include <inet/common.h>
66 #include <inet/mi.h>
67 #include <inet/mib2.h>
68 #include <inet/nd.h>
69 #include <inet/arp.h>
70 #include <inet/snmpcom.h>
71 #include <inet/optcom.h>
72 #include <inet/kstatcom.h>
73 
74 #include <netinet/igmp_var.h>
75 #include <netinet/ip6.h>
76 #include <netinet/icmp6.h>
77 #include <netinet/sctp.h>
78 
79 #include <inet/ip.h>
80 #include <inet/ip_impl.h>
81 #include <inet/ip6.h>
82 #include <inet/ip6_asp.h>
83 #include <inet/tcp.h>
84 #include <inet/tcp_impl.h>
85 #include <inet/ip_multi.h>
86 #include <inet/ip_if.h>
87 #include <inet/ip_ire.h>
88 #include <inet/ip_ftable.h>
89 #include <inet/ip_rts.h>
90 #include <inet/ip_ndp.h>
91 #include <inet/ip_listutils.h>
92 #include <netinet/igmp.h>
93 #include <netinet/ip_mroute.h>
94 #include <inet/ipp_common.h>
95 
96 #include <net/pfkeyv2.h>
97 #include <inet/ipsec_info.h>
98 #include <inet/sadb.h>
99 #include <inet/ipsec_impl.h>
100 #include <sys/iphada.h>
101 #include <inet/tun.h>
102 #include <inet/ipdrop.h>
103 #include <inet/ip_netinfo.h>
104 
105 #include <sys/ethernet.h>
106 #include <net/if_types.h>
107 #include <sys/cpuvar.h>
108 
109 #include <ipp/ipp.h>
110 #include <ipp/ipp_impl.h>
111 #include <ipp/ipgpc/ipgpc.h>
112 
113 #include <sys/multidata.h>
114 #include <sys/pattr.h>
115 
116 #include <inet/ipclassifier.h>
117 #include <inet/sctp_ip.h>
118 #include <inet/sctp/sctp_impl.h>
119 #include <inet/udp_impl.h>
120 #include <inet/rawip_impl.h>
121 #include <inet/rts_impl.h>
122 
123 #include <sys/tsol/label.h>
124 #include <sys/tsol/tnet.h>
125 
126 #include <rpc/pmap_prot.h>
127 #include <sys/squeue_impl.h>
128 
129 /*
130  * Values for squeue switch:
131  * IP_SQUEUE_ENTER_NODRAIN: SQ_NODRAIN
132  * IP_SQUEUE_ENTER: SQ_PROCESS
133  * IP_SQUEUE_FILL: SQ_FILL
134  */
135 int ip_squeue_enter = 2;	/* Setable in /etc/system */
136 
137 int ip_squeue_flag;
138 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
139 
140 /*
141  * Setable in /etc/system
142  */
143 int ip_poll_normal_ms = 100;
144 int ip_poll_normal_ticks = 0;
145 int ip_modclose_ackwait_ms = 3000;
146 
147 /*
148  * It would be nice to have these present only in DEBUG systems, but the
149  * current design of the global symbol checking logic requires them to be
150  * unconditionally present.
151  */
152 uint_t ip_thread_data;			/* TSD key for debug support */
153 krwlock_t ip_thread_rwlock;
154 list_t	ip_thread_list;
155 
156 /*
157  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
158  */
159 
160 struct listptr_s {
161 	mblk_t	*lp_head;	/* pointer to the head of the list */
162 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
163 };
164 
165 typedef struct listptr_s listptr_t;
166 
167 /*
168  * This is used by ip_snmp_get_mib2_ip_route_media and
169  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
170  */
171 typedef struct iproutedata_s {
172 	uint_t		ird_idx;
173 	uint_t		ird_flags;	/* see below */
174 	listptr_t	ird_route;	/* ipRouteEntryTable */
175 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
176 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
177 } iproutedata_t;
178 
179 #define	IRD_REPORT_TESTHIDDEN	0x01	/* include IRE_MARK_TESTHIDDEN routes */
180 
181 /*
182  * Cluster specific hooks. These should be NULL when booted as a non-cluster
183  */
184 
185 /*
186  * Hook functions to enable cluster networking
187  * On non-clustered systems these vectors must always be NULL.
188  *
189  * Hook function to Check ip specified ip address is a shared ip address
190  * in the cluster
191  *
192  */
193 int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
194     sa_family_t addr_family, uint8_t *laddrp, void *args) = NULL;
195 
196 /*
197  * Hook function to generate cluster wide ip fragment identifier
198  */
199 uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
200     sa_family_t addr_family, uint8_t *laddrp, uint8_t *faddrp,
201     void *args) = NULL;
202 
203 /*
204  * Hook function to generate cluster wide SPI.
205  */
206 void (*cl_inet_getspi)(netstackid_t, uint8_t, uint8_t *, size_t,
207     void *) = NULL;
208 
209 /*
210  * Hook function to verify if the SPI is already utlized.
211  */
212 
213 int (*cl_inet_checkspi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
214 
215 /*
216  * Hook function to delete the SPI from the cluster wide repository.
217  */
218 
219 void (*cl_inet_deletespi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
220 
221 /*
222  * Hook function to inform the cluster when packet received on an IDLE SA
223  */
224 
225 void (*cl_inet_idlesa)(netstackid_t, uint8_t, uint32_t, sa_family_t,
226     in6_addr_t, in6_addr_t, void *) = NULL;
227 
228 /*
229  * Synchronization notes:
230  *
231  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
232  * MT level protection given by STREAMS. IP uses a combination of its own
233  * internal serialization mechanism and standard Solaris locking techniques.
234  * The internal serialization is per phyint.  This is used to serialize
235  * plumbing operations, certain multicast operations, most set ioctls,
236  * igmp/mld timers etc.
237  *
238  * Plumbing is a long sequence of operations involving message
239  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
240  * involved in plumbing operations. A natural model is to serialize these
241  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
242  * parallel without any interference. But various set ioctls on hme0 are best
243  * serialized, along with multicast join/leave operations, igmp/mld timer
244  * operations, and processing of DLPI control messages received from drivers
245  * on a per phyint basis.  This serialization is provided by the ipsq_t and
246  * primitives operating on this. Details can be found in ip_if.c above the
247  * core primitives operating on ipsq_t.
248  *
249  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
250  * Simiarly lookup of an ire by a thread also returns a refheld ire.
251  * In addition ipif's and ill's referenced by the ire are also indirectly
252  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
253  * the ipif's address or netmask change as long as an ipif is refheld
254  * directly or indirectly. For example an SIOCSLIFADDR ioctl that changes the
255  * address of an ipif has to go through the ipsq_t. This ensures that only
256  * 1 such exclusive operation proceeds at any time on the ipif. It then
257  * deletes all ires associated with this ipif, and waits for all refcnts
258  * associated with this ipif to come down to zero. The address is changed
259  * only after the ipif has been quiesced. Then the ipif is brought up again.
260  * More details are described above the comment in ip_sioctl_flags.
261  *
262  * Packet processing is based mostly on IREs and are fully multi-threaded
263  * using standard Solaris MT techniques.
264  *
265  * There are explicit locks in IP to handle:
266  * - The ip_g_head list maintained by mi_open_link() and friends.
267  *
268  * - The reassembly data structures (one lock per hash bucket)
269  *
270  * - conn_lock is meant to protect conn_t fields. The fields actually
271  *   protected by conn_lock are documented in the conn_t definition.
272  *
273  * - ire_lock to protect some of the fields of the ire, IRE tables
274  *   (one lock per hash bucket). Refer to ip_ire.c for details.
275  *
276  * - ndp_g_lock and nce_lock for protecting NCEs.
277  *
278  * - ill_lock protects fields of the ill and ipif. Details in ip.h
279  *
280  * - ill_g_lock: This is a global reader/writer lock. Protects the following
281  *	* The AVL tree based global multi list of all ills.
282  *	* The linked list of all ipifs of an ill
283  *	* The <ipsq-xop> mapping
284  *	* <ill-phyint> association
285  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
286  *   into an ill, changing the <ipsq-xop> mapping of an ill, changing the
287  *   <ill-phyint> assoc of an ill will all have to hold the ill_g_lock as
288  *   writer for the actual duration of the insertion/deletion/change.
289  *
290  * - ill_lock:  This is a per ill mutex.
291  *   It protects some members of the ill_t struct; see ip.h for details.
292  *   It also protects the <ill-phyint> assoc.
293  *   It also protects the list of ipifs hanging off the ill.
294  *
295  * - ipsq_lock: This is a per ipsq_t mutex lock.
296  *   This protects some members of the ipsq_t struct; see ip.h for details.
297  *   It also protects the <ipsq-ipxop> mapping
298  *
299  * - ipx_lock: This is a per ipxop_t mutex lock.
300  *   This protects some members of the ipxop_t struct; see ip.h for details.
301  *
302  * - phyint_lock: This is a per phyint mutex lock. Protects just the
303  *   phyint_flags
304  *
305  * - ip_g_nd_lock: This is a global reader/writer lock.
306  *   Any call to nd_load to load a new parameter to the ND table must hold the
307  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
308  *   as reader.
309  *
310  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
311  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
312  *   uniqueness check also done atomically.
313  *
314  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
315  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
316  *   as a writer when adding or deleting elements from these lists, and
317  *   as a reader when walking these lists to send a SADB update to the
318  *   IPsec capable ills.
319  *
320  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
321  *   group list linked by ill_usesrc_grp_next. It also protects the
322  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
323  *   group is being added or deleted.  This lock is taken as a reader when
324  *   walking the list/group(eg: to get the number of members in a usesrc group).
325  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
326  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
327  *   example, it is not necessary to take this lock in the initial portion
328  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_flags since these
329  *   operations are executed exclusively and that ensures that the "usesrc
330  *   group state" cannot change. The "usesrc group state" change can happen
331  *   only in the latter part of ip_sioctl_slifusesrc and in ill_delete.
332  *
333  * Changing <ill-phyint>, <ipsq-xop> assocications:
334  *
335  * To change the <ill-phyint> association, the ill_g_lock must be held
336  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
337  * must be held.
338  *
339  * To change the <ipsq-xop> association, the ill_g_lock must be held as
340  * writer, the ipsq_lock must be held, and one must be writer on the ipsq.
341  * This is only done when ills are added or removed from IPMP groups.
342  *
343  * To add or delete an ipif from the list of ipifs hanging off the ill,
344  * ill_g_lock (writer) and ill_lock must be held and the thread must be
345  * a writer on the associated ipsq.
346  *
347  * To add or delete an ill to the system, the ill_g_lock must be held as
348  * writer and the thread must be a writer on the associated ipsq.
349  *
350  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
351  * must be a writer on the associated ipsq.
352  *
353  * Lock hierarchy
354  *
355  * Some lock hierarchy scenarios are listed below.
356  *
357  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock -> ipx_lock
358  * ill_g_lock -> ill_lock(s) -> phyint_lock
359  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
360  * ill_g_lock -> ip_addr_avail_lock
361  * conn_lock -> irb_lock -> ill_lock -> ire_lock
362  * ill_g_lock -> ip_g_nd_lock
363  *
364  * When more than 1 ill lock is needed to be held, all ill lock addresses
365  * are sorted on address and locked starting from highest addressed lock
366  * downward.
367  *
368  * IPsec scenarios
369  *
370  * ipsa_lock -> ill_g_lock -> ill_lock
371  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
372  * ipsec_capab_ills_lock -> ipsa_lock
373  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
374  *
375  * Trusted Solaris scenarios
376  *
377  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
378  * igsa_lock -> gcdb_lock
379  * gcgrp_rwlock -> ire_lock
380  * gcgrp_rwlock -> gcdb_lock
381  *
382  * squeue(sq_lock), flow related (ft_lock, fe_lock) locking
383  *
384  * cpu_lock --> ill_lock --> sqset_lock --> sq_lock
385  * sq_lock -> conn_lock -> QLOCK(q)
386  * ill_lock -> ft_lock -> fe_lock
387  *
388  * Routing/forwarding table locking notes:
389  *
390  * Lock acquisition order: Radix tree lock, irb_lock.
391  * Requirements:
392  * i.  Walker must not hold any locks during the walker callback.
393  * ii  Walker must not see a truncated tree during the walk because of any node
394  *     deletion.
395  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
396  *     in many places in the code to walk the irb list. Thus even if all the
397  *     ires in a bucket have been deleted, we still can't free the radix node
398  *     until the ires have actually been inactive'd (freed).
399  *
400  * Tree traversal - Need to hold the global tree lock in read mode.
401  * Before dropping the global tree lock, need to either increment the ire_refcnt
402  * to ensure that the radix node can't be deleted.
403  *
404  * Tree add - Need to hold the global tree lock in write mode to add a
405  * radix node. To prevent the node from being deleted, increment the
406  * irb_refcnt, after the node is added to the tree. The ire itself is
407  * added later while holding the irb_lock, but not the tree lock.
408  *
409  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
410  * All associated ires must be inactive (i.e. freed), and irb_refcnt
411  * must be zero.
412  *
413  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
414  * global tree lock (read mode) for traversal.
415  *
416  * IPsec notes :
417  *
418  * IP interacts with the IPsec code (AH/ESP) by tagging a M_CTL message
419  * in front of the actual packet. For outbound datagrams, the M_CTL
420  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
421  * information used by the IPsec code for applying the right level of
422  * protection. The information initialized by IP in the ipsec_out_t
423  * is determined by the per-socket policy or global policy in the system.
424  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
425  * ipsec_info.h) which starts out with nothing in it. It gets filled
426  * with the right information if it goes through the AH/ESP code, which
427  * happens if the incoming packet is secure. The information initialized
428  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
429  * the policy requirements needed by per-socket policy or global policy
430  * is met or not.
431  *
432  * If there is both per-socket policy (set using setsockopt) and there
433  * is also global policy match for the 5 tuples of the socket,
434  * ipsec_override_policy() makes the decision of which one to use.
435  *
436  * For fully connected sockets i.e dst, src [addr, port] is known,
437  * conn_policy_cached is set indicating that policy has been cached.
438  * conn_in_enforce_policy may or may not be set depending on whether
439  * there is a global policy match or per-socket policy match.
440  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
441  * Once the right policy is set on the conn_t, policy cannot change for
442  * this socket. This makes life simpler for TCP (UDP ?) where
443  * re-transmissions go out with the same policy. For symmetry, policy
444  * is cached for fully connected UDP sockets also. Thus if policy is cached,
445  * it also implies that policy is latched i.e policy cannot change
446  * on these sockets. As we have the right policy on the conn, we don't
447  * have to lookup global policy for every outbound and inbound datagram
448  * and thus serving as an optimization. Note that a global policy change
449  * does not affect fully connected sockets if they have policy. If fully
450  * connected sockets did not have any policy associated with it, global
451  * policy change may affect them.
452  *
453  * IP Flow control notes:
454  *
455  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
456  * cannot be sent down to the driver by IP, because of a canput failure, IP
457  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
458  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
459  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
460  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
461  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
462  * the queued messages, and removes the conn from the drain list, if all
463  * messages were drained. It also qenables the next conn in the drain list to
464  * continue the drain process.
465  *
466  * In reality the drain list is not a single list, but a configurable number
467  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
468  * list. If the ip_wsrv of the next qenabled conn does not run, because the
469  * stream closes, ip_close takes responsibility to qenable the next conn in
470  * the drain list. The directly called ip_wput path always does a putq, if
471  * it cannot putnext. Thus synchronization problems are handled between
472  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
473  * functions that manipulate this drain list. Furthermore conn_drain_insert
474  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
475  * running on a queue at any time. conn_drain_tail can be simultaneously called
476  * from both ip_wsrv and ip_close.
477  *
478  * IPQOS notes:
479  *
480  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
481  * and IPQoS modules. IPPF includes hooks in IP at different control points
482  * (callout positions) which direct packets to IPQoS modules for policy
483  * processing. Policies, if present, are global.
484  *
485  * The callout positions are located in the following paths:
486  *		o local_in (packets destined for this host)
487  *		o local_out (packets orginating from this host )
488  *		o fwd_in  (packets forwarded by this m/c - inbound)
489  *		o fwd_out (packets forwarded by this m/c - outbound)
490  * Hooks at these callout points can be enabled/disabled using the ndd variable
491  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
492  * By default all the callout positions are enabled.
493  *
494  * Outbound (local_out)
495  * Hooks are placed in ip_wput_ire and ipsec_out_process.
496  *
497  * Inbound (local_in)
498  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
499  * TCP and UDP fanout routines.
500  *
501  * Forwarding (in and out)
502  * Hooks are placed in ip_rput_forward.
503  *
504  * IP Policy Framework processing (IPPF processing)
505  * Policy processing for a packet is initiated by ip_process, which ascertains
506  * that the classifier (ipgpc) is loaded and configured, failing which the
507  * packet resumes normal processing in IP. If the clasifier is present, the
508  * packet is acted upon by one or more IPQoS modules (action instances), per
509  * filters configured in ipgpc and resumes normal IP processing thereafter.
510  * An action instance can drop a packet in course of its processing.
511  *
512  * A boolean variable, ip_policy, is used in all the fanout routines that can
513  * invoke ip_process for a packet. This variable indicates if the packet should
514  * to be sent for policy processing. The variable is set to B_TRUE by default,
515  * i.e. when the routines are invoked in the normal ip procesing path for a
516  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
517  * ip_policy is set to B_FALSE for all the routines called in these two
518  * functions because, in the former case,  we don't process loopback traffic
519  * currently while in the latter, the packets have already been processed in
520  * icmp_inbound.
521  *
522  * Zones notes:
523  *
524  * The partitioning rules for networking are as follows:
525  * 1) Packets coming from a zone must have a source address belonging to that
526  * zone.
527  * 2) Packets coming from a zone can only be sent on a physical interface on
528  * which the zone has an IP address.
529  * 3) Between two zones on the same machine, packet delivery is only allowed if
530  * there's a matching route for the destination and zone in the forwarding
531  * table.
532  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
533  * different zones can bind to the same port with the wildcard address
534  * (INADDR_ANY).
535  *
536  * The granularity of interface partitioning is at the logical interface level.
537  * Therefore, every zone has its own IP addresses, and incoming packets can be
538  * attributed to a zone unambiguously. A logical interface is placed into a zone
539  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
540  * structure. Rule (1) is implemented by modifying the source address selection
541  * algorithm so that the list of eligible addresses is filtered based on the
542  * sending process zone.
543  *
544  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
545  * across all zones, depending on their type. Here is the break-up:
546  *
547  * IRE type				Shared/exclusive
548  * --------				----------------
549  * IRE_BROADCAST			Exclusive
550  * IRE_DEFAULT (default routes)		Shared (*)
551  * IRE_LOCAL				Exclusive (x)
552  * IRE_LOOPBACK				Exclusive
553  * IRE_PREFIX (net routes)		Shared (*)
554  * IRE_CACHE				Exclusive
555  * IRE_IF_NORESOLVER (interface routes)	Exclusive
556  * IRE_IF_RESOLVER (interface routes)	Exclusive
557  * IRE_HOST (host routes)		Shared (*)
558  *
559  * (*) A zone can only use a default or off-subnet route if the gateway is
560  * directly reachable from the zone, that is, if the gateway's address matches
561  * one of the zone's logical interfaces.
562  *
563  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
564  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
565  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
566  * address of the zone itself (the destination). Since IRE_LOCAL is used
567  * for communication between zones, ip_wput_ire has special logic to set
568  * the right source address when sending using an IRE_LOCAL.
569  *
570  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
571  * ire_cache_lookup restricts loopback using an IRE_LOCAL
572  * between zone to the case when L2 would have conceptually looped the packet
573  * back, i.e. the loopback which is required since neither Ethernet drivers
574  * nor Ethernet hardware loops them back. This is the case when the normal
575  * routes (ignoring IREs with different zoneids) would send out the packet on
576  * the same ill as the ill with which is IRE_LOCAL is associated.
577  *
578  * Multiple zones can share a common broadcast address; typically all zones
579  * share the 255.255.255.255 address. Incoming as well as locally originated
580  * broadcast packets must be dispatched to all the zones on the broadcast
581  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
582  * since some zones may not be on the 10.16.72/24 network. To handle this, each
583  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
584  * sent to every zone that has an IRE_BROADCAST entry for the destination
585  * address on the input ill, see conn_wantpacket().
586  *
587  * Applications in different zones can join the same multicast group address.
588  * For IPv4, group memberships are per-logical interface, so they're already
589  * inherently part of a zone. For IPv6, group memberships are per-physical
590  * interface, so we distinguish IPv6 group memberships based on group address,
591  * interface and zoneid. In both cases, received multicast packets are sent to
592  * every zone for which a group membership entry exists. On IPv6 we need to
593  * check that the target zone still has an address on the receiving physical
594  * interface; it could have been removed since the application issued the
595  * IPV6_JOIN_GROUP.
596  */
597 
598 /*
599  * Squeue Fanout flags:
600  *	0: No fanout.
601  *	1: Fanout across all squeues
602  */
603 boolean_t	ip_squeue_fanout = 0;
604 
605 /*
606  * Maximum dups allowed per packet.
607  */
608 uint_t ip_max_frag_dups = 10;
609 
610 #define	IS_SIMPLE_IPH(ipha)						\
611 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
612 
613 /* RFC 1122 Conformance */
614 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
615 
616 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
617 
618 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
619 
620 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
621 		    cred_t *credp, boolean_t isv6);
622 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t,
623 		    ipha_t **);
624 
625 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
626 		    ip_stack_t *);
627 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
628 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
629 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
630 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
631 		    mblk_t *, int, ip_stack_t *);
632 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
633 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
634 		    ill_t *, zoneid_t);
635 static void	icmp_options_update(ipha_t *);
636 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
637 		    ip_stack_t *);
638 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
639 		    zoneid_t zoneid, ip_stack_t *);
640 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
641 static void	icmp_redirect(ill_t *, mblk_t *);
642 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
643 		    ip_stack_t *);
644 
645 static void	ip_arp_news(queue_t *, mblk_t *);
646 static boolean_t ip_bind_get_ire_v4(mblk_t **, ire_t *, iulp_t *, ip_stack_t *);
647 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
648 char		*ip_dot_addr(ipaddr_t, char *);
649 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
650 int		ip_close(queue_t *, int);
651 static char	*ip_dot_saddr(uchar_t *, char *);
652 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
653 		    boolean_t, boolean_t, ill_t *, zoneid_t);
654 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
655 		    boolean_t, boolean_t, zoneid_t);
656 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
657 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
658 static void	ip_lrput(queue_t *, mblk_t *);
659 ipaddr_t	ip_net_mask(ipaddr_t);
660 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
661 		    ip_stack_t *);
662 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
663 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
664 char		*ip_nv_lookup(nv_t *, int);
665 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
666 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
667 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
668 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
669     ipndp_t *, size_t);
670 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
671 void	ip_rput(queue_t *, mblk_t *);
672 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
673 		    void *dummy_arg);
674 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
675 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
676     ip_stack_t *);
677 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
678 			    ire_t *, ip_stack_t *);
679 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
680 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
681 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
682     ip_stack_t *);
683 static boolean_t ip_rput_fragment(ill_t *, ill_t *, mblk_t **, ipha_t *,
684     uint32_t *, uint16_t *);
685 int		ip_snmp_get(queue_t *, mblk_t *, int);
686 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
687 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
688 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
689 		    ip_stack_t *);
690 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
691 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
692 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
693 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
694 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
695 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
696 		    ip_stack_t *ipst);
697 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
698 		    ip_stack_t *ipst);
699 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
700 		    ip_stack_t *ipst);
701 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
702 		    ip_stack_t *ipst);
703 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
704 		    ip_stack_t *ipst);
705 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
706 		    ip_stack_t *ipst);
707 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
708 		    ip_stack_t *ipst);
709 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
710 		    ip_stack_t *ipst);
711 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *, int,
712 		    ip_stack_t *ipst);
713 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *, int,
714 		    ip_stack_t *ipst);
715 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
716 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
717 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
718 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
719 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
720 static boolean_t	ip_source_route_included(ipha_t *);
721 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
722 
723 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
724 		    zoneid_t, ip_stack_t *, conn_t *);
725 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *);
726 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
727 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
728 		    zoneid_t, ip_stack_t *);
729 
730 static void	conn_drain_init(ip_stack_t *);
731 static void	conn_drain_fini(ip_stack_t *);
732 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
733 
734 static void	conn_walk_drain(ip_stack_t *);
735 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
736     zoneid_t);
737 
738 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
739 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
740 static void	ip_stack_fini(netstackid_t stackid, void *arg);
741 
742 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
743     zoneid_t);
744 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
745     void *dummy_arg);
746 
747 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
748 
749 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
750     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
751     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
752 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
753 
754 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
755 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
756     caddr_t, cred_t *);
757 extern int	ip_helper_stream_setup(queue_t *, dev_t *, int, int,
758     cred_t *, boolean_t);
759 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
760     caddr_t cp, cred_t *cr);
761 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
762     cred_t *);
763 static int	ip_squeue_switch(int);
764 
765 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
766 static void	ip_kstat_fini(netstackid_t, kstat_t *);
767 static int	ip_kstat_update(kstat_t *kp, int rw);
768 static void	*icmp_kstat_init(netstackid_t);
769 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
770 static int	icmp_kstat_update(kstat_t *kp, int rw);
771 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
772 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
773 
774 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
775 
776 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
777     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
778 
779 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
780     ipha_t *, ill_t *, boolean_t, boolean_t);
781 
782 static void ipobs_init(ip_stack_t *);
783 static void ipobs_fini(ip_stack_t *);
784 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
785 
786 /* How long, in seconds, we allow frags to hang around. */
787 #define	IP_FRAG_TIMEOUT	15
788 
789 /*
790  * Threshold which determines whether MDT should be used when
791  * generating IP fragments; payload size must be greater than
792  * this threshold for MDT to take place.
793  */
794 #define	IP_WPUT_FRAG_MDT_MIN	32768
795 
796 /* Setable in /etc/system only */
797 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
798 
799 static long ip_rput_pullups;
800 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
801 
802 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
803 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
804 
805 int	ip_debug;
806 
807 #ifdef DEBUG
808 uint32_t ipsechw_debug = 0;
809 #endif
810 
811 /*
812  * Multirouting/CGTP stuff
813  */
814 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
815 
816 /*
817  * XXX following really should only be in a header. Would need more
818  * header and .c clean up first.
819  */
820 extern optdb_obj_t	ip_opt_obj;
821 
822 ulong_t ip_squeue_enter_unbound = 0;
823 
824 /*
825  * Named Dispatch Parameter Table.
826  * All of these are alterable, within the min/max values given, at run time.
827  */
828 static ipparam_t	lcl_param_arr[] = {
829 	/* min	max	value	name */
830 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
831 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
832 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
833 	{  0,	1,	0,	"ip_respond_to_timestamp"},
834 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
835 	{  0,	1,	1,	"ip_send_redirects"},
836 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
837 	{  0,	10,	0,	"ip_mrtdebug"},
838 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
839 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
840 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
841 	{  1,	255,	255,	"ip_def_ttl" },
842 	{  0,	1,	0,	"ip_forward_src_routed"},
843 	{  0,	256,	32,	"ip_wroff_extra" },
844 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
845 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
846 	{  0,	1,	1,	"ip_path_mtu_discovery" },
847 	{  0,	240,	30,	"ip_ignore_delete_time" },
848 	{  0,	1,	0,	"ip_ignore_redirect" },
849 	{  0,	1,	1,	"ip_output_queue" },
850 	{  1,	254,	1,	"ip_broadcast_ttl" },
851 	{  0,	99999,	100,	"ip_icmp_err_interval" },
852 	{  1,	99999,	10,	"ip_icmp_err_burst" },
853 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
854 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
855 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
856 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
857 	{  0,	1,	1,	"icmp_accept_clear_messages" },
858 	{  0,	1,	1,	"igmp_accept_clear_messages" },
859 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
860 				"ip_ndp_delay_first_probe_time"},
861 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
862 				"ip_ndp_max_unicast_solicit"},
863 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
864 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
865 	{  0,	1,	0,	"ip6_forward_src_routed"},
866 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
867 	{  0,	1,	1,	"ip6_send_redirects"},
868 	{  0,	1,	0,	"ip6_ignore_redirect" },
869 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
870 
871 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
872 
873 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
874 
875 	{  0,	1,	1,	"pim_accept_clear_messages" },
876 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
877 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
878 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
879 	{  0,	15,	0,	"ip_policy_mask" },
880 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
881 	{  0,	255,	1,	"ip_multirt_ttl" },
882 	{  0,	1,	1,	"ip_multidata_outbound" },
883 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
884 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
885 	{  0,	1000,	1,	"ip_max_temp_defend" },
886 	{  0,	1000,	3,	"ip_max_defend" },
887 	{  0,	999999,	30,	"ip_defend_interval" },
888 	{  0,	3600000, 300000, "ip_dup_recovery" },
889 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
890 	{  0,	1,	1,	"ip_lso_outbound" },
891 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
892 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
893 	{ 68,	65535,	576,	"ip_pmtu_min" },
894 #ifdef DEBUG
895 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
896 #else
897 	{  0,	0,	0,	"" },
898 #endif
899 };
900 
901 /*
902  * Extended NDP table
903  * The addresses for the first two are filled in to be ips_ip_g_forward
904  * and ips_ipv6_forward at init time.
905  */
906 static ipndp_t	lcl_ndp_arr[] = {
907 	/* getf			setf		data			name */
908 #define	IPNDP_IP_FORWARDING_OFFSET	0
909 	{  ip_param_generic_get,	ip_forward_set,	NULL,
910 	    "ip_forwarding" },
911 #define	IPNDP_IP6_FORWARDING_OFFSET	1
912 	{  ip_param_generic_get,	ip_forward_set,	NULL,
913 	    "ip6_forwarding" },
914 	{  ip_ill_report,	NULL,		NULL,
915 	    "ip_ill_status" },
916 	{  ip_ipif_report,	NULL,		NULL,
917 	    "ip_ipif_status" },
918 	{  ip_conn_report,	NULL,		NULL,
919 	    "ip_conn_status" },
920 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
921 	    "ip_rput_pullups" },
922 	{  ip_srcid_report,	NULL,		NULL,
923 	    "ip_srcid_status" },
924 	{ ip_param_generic_get, ip_input_proc_set,
925 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
926 	{ ip_param_generic_get, ip_int_set,
927 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
928 #define	IPNDP_CGTP_FILTER_OFFSET	9
929 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
930 	    "ip_cgtp_filter" },
931 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
932 	    "ip_debug" },
933 };
934 
935 /*
936  * Table of IP ioctls encoding the various properties of the ioctl and
937  * indexed based on the last byte of the ioctl command. Occasionally there
938  * is a clash, and there is more than 1 ioctl with the same last byte.
939  * In such a case 1 ioctl is encoded in the ndx table and the remaining
940  * ioctls are encoded in the misc table. An entry in the ndx table is
941  * retrieved by indexing on the last byte of the ioctl command and comparing
942  * the ioctl command with the value in the ndx table. In the event of a
943  * mismatch the misc table is then searched sequentially for the desired
944  * ioctl command.
945  *
946  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
947  */
948 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
949 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
950 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
951 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
952 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
953 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
954 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
955 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
956 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
957 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
958 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
959 
960 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
961 			MISC_CMD, ip_siocaddrt, NULL },
962 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
963 			MISC_CMD, ip_siocdelrt, NULL },
964 
965 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
966 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
967 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
968 			IF_CMD, ip_sioctl_get_addr, NULL },
969 
970 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
971 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
972 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
973 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
974 
975 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
976 			IPI_PRIV | IPI_WR,
977 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
978 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
979 			IPI_MODOK | IPI_GET_CMD,
980 			IF_CMD, ip_sioctl_get_flags, NULL },
981 
982 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
983 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
984 
985 	/* copyin size cannot be coded for SIOCGIFCONF */
986 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
987 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
988 
989 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
990 			IF_CMD, ip_sioctl_mtu, NULL },
991 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD,
992 			IF_CMD, ip_sioctl_get_mtu, NULL },
993 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
994 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
995 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
996 			IF_CMD, ip_sioctl_brdaddr, NULL },
997 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
998 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
999 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1000 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1001 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1002 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
1003 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1004 			IF_CMD, ip_sioctl_metric, NULL },
1005 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1006 
1007 	/* See 166-168 below for extended SIOC*XARP ioctls */
1008 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1009 			ARP_CMD, ip_sioctl_arp, NULL },
1010 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
1011 			ARP_CMD, ip_sioctl_arp, NULL },
1012 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1013 			ARP_CMD, ip_sioctl_arp, NULL },
1014 
1015 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1016 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1017 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1018 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1019 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1020 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1021 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1022 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1023 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1024 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1025 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036 
1037 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1038 			MISC_CMD, if_unitsel, if_unitsel_restart },
1039 
1040 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1041 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1042 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 
1059 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1060 			IPI_PRIV | IPI_WR | IPI_MODOK,
1061 			IF_CMD, ip_sioctl_sifname, NULL },
1062 
1063 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1064 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1065 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1066 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 
1077 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
1078 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1079 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
1080 			IF_CMD, ip_sioctl_get_muxid, NULL },
1081 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1082 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
1083 
1084 	/* Both if and lif variants share same func */
1085 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
1086 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1087 	/* Both if and lif variants share same func */
1088 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1089 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
1090 
1091 	/* copyin size cannot be coded for SIOCGIFCONF */
1092 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1093 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1094 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1095 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1096 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1097 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 
1112 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1113 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
1114 			ip_sioctl_removeif_restart },
1115 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1116 			IPI_GET_CMD | IPI_PRIV | IPI_WR,
1117 			LIF_CMD, ip_sioctl_addif, NULL },
1118 #define	SIOCLIFADDR_NDX 112
1119 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1120 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1121 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1122 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
1123 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1124 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1125 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1126 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1127 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1128 			IPI_PRIV | IPI_WR,
1129 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1130 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1131 			IPI_GET_CMD | IPI_MODOK,
1132 			LIF_CMD, ip_sioctl_get_flags, NULL },
1133 
1134 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1135 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1136 
1137 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1138 			ip_sioctl_get_lifconf, NULL },
1139 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1140 			LIF_CMD, ip_sioctl_mtu, NULL },
1141 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
1142 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1143 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1144 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1145 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1146 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1147 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1148 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
1149 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1150 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1151 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1152 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
1153 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1154 			LIF_CMD, ip_sioctl_metric, NULL },
1155 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1156 			IPI_PRIV | IPI_WR | IPI_MODOK,
1157 			LIF_CMD, ip_sioctl_slifname,
1158 			ip_sioctl_slifname_restart },
1159 
1160 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
1161 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1162 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1163 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
1164 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1165 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
1166 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1167 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
1168 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1169 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
1170 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1171 			LIF_CMD, ip_sioctl_token, NULL },
1172 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1173 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1174 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1175 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1176 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1177 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1178 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1179 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1180 
1181 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1182 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1183 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1184 			LIF_CMD, ip_siocdelndp_v6, NULL },
1185 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1186 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1187 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1188 			LIF_CMD, ip_siocsetndp_v6, NULL },
1189 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1190 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1191 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1192 			MISC_CMD, ip_sioctl_tonlink, NULL },
1193 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1194 			MISC_CMD, ip_sioctl_tmysite, NULL },
1195 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), 0,
1196 			TUN_CMD, ip_sioctl_tunparam, NULL },
1197 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1198 		    IPI_PRIV | IPI_WR,
1199 		    TUN_CMD, ip_sioctl_tunparam, NULL },
1200 
1201 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1202 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1203 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1204 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1205 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1206 
1207 	/* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1208 
1209 	/* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
1210 			LIF_CMD, ip_sioctl_get_binding, NULL },
1211 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1212 			IPI_PRIV | IPI_WR,
1213 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1214 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1215 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1216 	/* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1217 			IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1218 
1219 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1220 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1221 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1222 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1223 
1224 	/* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1225 
1226 	/* These are handled in ip_sioctl_copyin_setup itself */
1227 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1228 			MISC_CMD, NULL, NULL },
1229 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1230 			MISC_CMD, NULL, NULL },
1231 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1232 
1233 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1234 			ip_sioctl_get_lifconf, NULL },
1235 
1236 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1237 			XARP_CMD, ip_sioctl_arp, NULL },
1238 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1239 			XARP_CMD, ip_sioctl_arp, NULL },
1240 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1241 			XARP_CMD, ip_sioctl_arp, NULL },
1242 
1243 	/* SIOCPOPSOCKFS is not handled by IP */
1244 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1245 
1246 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1247 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1248 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1249 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1250 			ip_sioctl_slifzone_restart },
1251 	/* 172-174 are SCTP ioctls and not handled by IP */
1252 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1253 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1254 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1255 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1256 			IPI_GET_CMD, LIF_CMD,
1257 			ip_sioctl_get_lifusesrc, 0 },
1258 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1259 			IPI_PRIV | IPI_WR,
1260 			LIF_CMD, ip_sioctl_slifusesrc,
1261 			NULL },
1262 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1263 			ip_sioctl_get_lifsrcof, NULL },
1264 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1265 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1266 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1267 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1268 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1269 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1270 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1271 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1272 	/* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1273 	/* SIOCSENABLESDP is handled by SDP */
1274 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1275 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1276 };
1277 
1278 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1279 
1280 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1281 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1282 		IPI_GET_CMD, TUN_CMD, ip_sioctl_tunparam, NULL },
1283 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1284 		TUN_CMD, ip_sioctl_tunparam, NULL },
1285 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1286 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1287 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1288 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1289 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1290 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1291 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1292 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1293 		MISC_CMD, mrt_ioctl},
1294 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_GET_CMD,
1295 		MISC_CMD, mrt_ioctl},
1296 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1297 		MISC_CMD, mrt_ioctl}
1298 };
1299 
1300 int ip_misc_ioctl_count =
1301     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1302 
1303 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1304 					/* Settable in /etc/system */
1305 /* Defined in ip_ire.c */
1306 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1307 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1308 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1309 
1310 static nv_t	ire_nv_arr[] = {
1311 	{ IRE_BROADCAST, "BROADCAST" },
1312 	{ IRE_LOCAL, "LOCAL" },
1313 	{ IRE_LOOPBACK, "LOOPBACK" },
1314 	{ IRE_CACHE, "CACHE" },
1315 	{ IRE_DEFAULT, "DEFAULT" },
1316 	{ IRE_PREFIX, "PREFIX" },
1317 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1318 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1319 	{ IRE_HOST, "HOST" },
1320 	{ 0 }
1321 };
1322 
1323 nv_t	*ire_nv_tbl = ire_nv_arr;
1324 
1325 /* Simple ICMP IP Header Template */
1326 static ipha_t icmp_ipha = {
1327 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1328 };
1329 
1330 struct module_info ip_mod_info = {
1331 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1332 	IP_MOD_LOWAT
1333 };
1334 
1335 /*
1336  * Duplicate static symbols within a module confuses mdb; so we avoid the
1337  * problem by making the symbols here distinct from those in udp.c.
1338  */
1339 
1340 /*
1341  * Entry points for IP as a device and as a module.
1342  * FIXME: down the road we might want a separate module and driver qinit.
1343  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1344  */
1345 static struct qinit iprinitv4 = {
1346 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1347 	&ip_mod_info
1348 };
1349 
1350 struct qinit iprinitv6 = {
1351 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1352 	&ip_mod_info
1353 };
1354 
1355 static struct qinit ipwinitv4 = {
1356 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1357 	&ip_mod_info
1358 };
1359 
1360 struct qinit ipwinitv6 = {
1361 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1362 	&ip_mod_info
1363 };
1364 
1365 static struct qinit iplrinit = {
1366 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1367 	&ip_mod_info
1368 };
1369 
1370 static struct qinit iplwinit = {
1371 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1372 	&ip_mod_info
1373 };
1374 
1375 /* For AF_INET aka /dev/ip */
1376 struct streamtab ipinfov4 = {
1377 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1378 };
1379 
1380 /* For AF_INET6 aka /dev/ip6 */
1381 struct streamtab ipinfov6 = {
1382 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1383 };
1384 
1385 #ifdef	DEBUG
1386 static boolean_t skip_sctp_cksum = B_FALSE;
1387 #endif
1388 
1389 /*
1390  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1391  * ip_rput_v6(), ip_output(), etc.  If the message
1392  * block already has a M_CTL at the front of it, then simply set the zoneid
1393  * appropriately.
1394  */
1395 mblk_t *
1396 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1397 {
1398 	mblk_t		*first_mp;
1399 	ipsec_out_t	*io;
1400 
1401 	ASSERT(zoneid != ALL_ZONES);
1402 	if (mp->b_datap->db_type == M_CTL) {
1403 		io = (ipsec_out_t *)mp->b_rptr;
1404 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1405 		io->ipsec_out_zoneid = zoneid;
1406 		return (mp);
1407 	}
1408 
1409 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1410 	if (first_mp == NULL)
1411 		return (NULL);
1412 	io = (ipsec_out_t *)first_mp->b_rptr;
1413 	/* This is not a secure packet */
1414 	io->ipsec_out_secure = B_FALSE;
1415 	io->ipsec_out_zoneid = zoneid;
1416 	first_mp->b_cont = mp;
1417 	return (first_mp);
1418 }
1419 
1420 /*
1421  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1422  */
1423 mblk_t *
1424 ip_copymsg(mblk_t *mp)
1425 {
1426 	mblk_t *nmp;
1427 	ipsec_info_t *in;
1428 
1429 	if (mp->b_datap->db_type != M_CTL)
1430 		return (copymsg(mp));
1431 
1432 	in = (ipsec_info_t *)mp->b_rptr;
1433 
1434 	/*
1435 	 * Note that M_CTL is also used for delivering ICMP error messages
1436 	 * upstream to transport layers.
1437 	 */
1438 	if (in->ipsec_info_type != IPSEC_OUT &&
1439 	    in->ipsec_info_type != IPSEC_IN)
1440 		return (copymsg(mp));
1441 
1442 	nmp = copymsg(mp->b_cont);
1443 
1444 	if (in->ipsec_info_type == IPSEC_OUT) {
1445 		return (ipsec_out_tag(mp, nmp,
1446 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1447 	} else {
1448 		return (ipsec_in_tag(mp, nmp,
1449 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1450 	}
1451 }
1452 
1453 /* Generate an ICMP fragmentation needed message. */
1454 static void
1455 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1456     ip_stack_t *ipst)
1457 {
1458 	icmph_t	icmph;
1459 	mblk_t *first_mp;
1460 	boolean_t mctl_present;
1461 
1462 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1463 
1464 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1465 		if (mctl_present)
1466 			freeb(first_mp);
1467 		return;
1468 	}
1469 
1470 	bzero(&icmph, sizeof (icmph_t));
1471 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1472 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1473 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1474 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1475 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1476 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1477 	    ipst);
1478 }
1479 
1480 /*
1481  * icmp_inbound deals with ICMP messages in the following ways.
1482  *
1483  * 1) It needs to send a reply back and possibly delivering it
1484  *    to the "interested" upper clients.
1485  * 2) It needs to send it to the upper clients only.
1486  * 3) It needs to change some values in IP only.
1487  * 4) It needs to change some values in IP and upper layers e.g TCP.
1488  *
1489  * We need to accomodate icmp messages coming in clear until we get
1490  * everything secure from the wire. If icmp_accept_clear_messages
1491  * is zero we check with the global policy and act accordingly. If
1492  * it is non-zero, we accept the message without any checks. But
1493  * *this does not mean* that this will be delivered to the upper
1494  * clients. By accepting we might send replies back, change our MTU
1495  * value etc. but delivery to the ULP/clients depends on their policy
1496  * dispositions.
1497  *
1498  * We handle the above 4 cases in the context of IPsec in the
1499  * following way :
1500  *
1501  * 1) Send the reply back in the same way as the request came in.
1502  *    If it came in encrypted, it goes out encrypted. If it came in
1503  *    clear, it goes out in clear. Thus, this will prevent chosen
1504  *    plain text attack.
1505  * 2) The client may or may not expect things to come in secure.
1506  *    If it comes in secure, the policy constraints are checked
1507  *    before delivering it to the upper layers. If it comes in
1508  *    clear, ipsec_inbound_accept_clear will decide whether to
1509  *    accept this in clear or not. In both the cases, if the returned
1510  *    message (IP header + 8 bytes) that caused the icmp message has
1511  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1512  *    sending up. If there are only 8 bytes of returned message, then
1513  *    upper client will not be notified.
1514  * 3) Check with global policy to see whether it matches the constaints.
1515  *    But this will be done only if icmp_accept_messages_in_clear is
1516  *    zero.
1517  * 4) If we need to change both in IP and ULP, then the decision taken
1518  *    while affecting the values in IP and while delivering up to TCP
1519  *    should be the same.
1520  *
1521  * 	There are two cases.
1522  *
1523  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1524  *	   failed), we will not deliver it to the ULP, even though they
1525  *	   are *willing* to accept in *clear*. This is fine as our global
1526  *	   disposition to icmp messages asks us reject the datagram.
1527  *
1528  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1529  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1530  *	   to deliver it to ULP (policy failed), it can lead to
1531  *	   consistency problems. The cases known at this time are
1532  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1533  *	   values :
1534  *
1535  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1536  *	     and Upper layer rejects. Then the communication will
1537  *	     come to a stop. This is solved by making similar decisions
1538  *	     at both levels. Currently, when we are unable to deliver
1539  *	     to the Upper Layer (due to policy failures) while IP has
1540  *	     adjusted ire_max_frag, the next outbound datagram would
1541  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1542  *	     will be with the right level of protection. Thus the right
1543  *	     value will be communicated even if we are not able to
1544  *	     communicate when we get from the wire initially. But this
1545  *	     assumes there would be at least one outbound datagram after
1546  *	     IP has adjusted its ire_max_frag value. To make things
1547  *	     simpler, we accept in clear after the validation of
1548  *	     AH/ESP headers.
1549  *
1550  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1551  *	     upper layer depending on the level of protection the upper
1552  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1553  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1554  *	     should be accepted in clear when the Upper layer expects secure.
1555  *	     Thus the communication may get aborted by some bad ICMP
1556  *	     packets.
1557  *
1558  * IPQoS Notes:
1559  * The only instance when a packet is sent for processing is when there
1560  * isn't an ICMP client and if we are interested in it.
1561  * If there is a client, IPPF processing will take place in the
1562  * ip_fanout_proto routine.
1563  *
1564  * Zones notes:
1565  * The packet is only processed in the context of the specified zone: typically
1566  * only this zone will reply to an echo request, and only interested clients in
1567  * this zone will receive a copy of the packet. This means that the caller must
1568  * call icmp_inbound() for each relevant zone.
1569  */
1570 static void
1571 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1572     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1573     ill_t *recv_ill, zoneid_t zoneid)
1574 {
1575 	icmph_t	*icmph;
1576 	ipha_t	*ipha;
1577 	int	iph_hdr_length;
1578 	int	hdr_length;
1579 	boolean_t	interested;
1580 	uint32_t	ts;
1581 	uchar_t	*wptr;
1582 	ipif_t	*ipif;
1583 	mblk_t *first_mp;
1584 	ipsec_in_t *ii;
1585 	timestruc_t now;
1586 	uint32_t ill_index;
1587 	ip_stack_t *ipst;
1588 
1589 	ASSERT(ill != NULL);
1590 	ipst = ill->ill_ipst;
1591 
1592 	first_mp = mp;
1593 	if (mctl_present) {
1594 		mp = first_mp->b_cont;
1595 		ASSERT(mp != NULL);
1596 	}
1597 
1598 	ipha = (ipha_t *)mp->b_rptr;
1599 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1600 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1601 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1602 		if (first_mp == NULL)
1603 			return;
1604 	}
1605 
1606 	/*
1607 	 * On a labeled system, we have to check whether the zone itself is
1608 	 * permitted to receive raw traffic.
1609 	 */
1610 	if (is_system_labeled()) {
1611 		if (zoneid == ALL_ZONES)
1612 			zoneid = tsol_packet_to_zoneid(mp);
1613 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1614 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1615 			    zoneid));
1616 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1617 			freemsg(first_mp);
1618 			return;
1619 		}
1620 	}
1621 
1622 	/*
1623 	 * We have accepted the ICMP message. It means that we will
1624 	 * respond to the packet if needed. It may not be delivered
1625 	 * to the upper client depending on the policy constraints
1626 	 * and the disposition in ipsec_inbound_accept_clear.
1627 	 */
1628 
1629 	ASSERT(ill != NULL);
1630 
1631 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1632 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1633 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1634 		/* Last chance to get real. */
1635 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1636 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1637 			freemsg(first_mp);
1638 			return;
1639 		}
1640 		/* Refresh iph following the pullup. */
1641 		ipha = (ipha_t *)mp->b_rptr;
1642 	}
1643 	/* ICMP header checksum, including checksum field, should be zero. */
1644 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1645 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1646 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1647 		freemsg(first_mp);
1648 		return;
1649 	}
1650 	/* The IP header will always be a multiple of four bytes */
1651 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1652 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1653 	    icmph->icmph_code));
1654 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1655 	/* We will set "interested" to "true" if we want a copy */
1656 	interested = B_FALSE;
1657 	switch (icmph->icmph_type) {
1658 	case ICMP_ECHO_REPLY:
1659 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1660 		break;
1661 	case ICMP_DEST_UNREACHABLE:
1662 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1663 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1664 		interested = B_TRUE;	/* Pass up to transport */
1665 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1666 		break;
1667 	case ICMP_SOURCE_QUENCH:
1668 		interested = B_TRUE;	/* Pass up to transport */
1669 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1670 		break;
1671 	case ICMP_REDIRECT:
1672 		if (!ipst->ips_ip_ignore_redirect)
1673 			interested = B_TRUE;
1674 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1675 		break;
1676 	case ICMP_ECHO_REQUEST:
1677 		/*
1678 		 * Whether to respond to echo requests that come in as IP
1679 		 * broadcasts or as IP multicast is subject to debate
1680 		 * (what isn't?).  We aim to please, you pick it.
1681 		 * Default is do it.
1682 		 */
1683 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1684 			/* unicast: always respond */
1685 			interested = B_TRUE;
1686 		} else if (CLASSD(ipha->ipha_dst)) {
1687 			/* multicast: respond based on tunable */
1688 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1689 		} else if (broadcast) {
1690 			/* broadcast: respond based on tunable */
1691 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1692 		}
1693 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1694 		break;
1695 	case ICMP_ROUTER_ADVERTISEMENT:
1696 	case ICMP_ROUTER_SOLICITATION:
1697 		break;
1698 	case ICMP_TIME_EXCEEDED:
1699 		interested = B_TRUE;	/* Pass up to transport */
1700 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1701 		break;
1702 	case ICMP_PARAM_PROBLEM:
1703 		interested = B_TRUE;	/* Pass up to transport */
1704 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1705 		break;
1706 	case ICMP_TIME_STAMP_REQUEST:
1707 		/* Response to Time Stamp Requests is local policy. */
1708 		if (ipst->ips_ip_g_resp_to_timestamp &&
1709 		    /* So is whether to respond if it was an IP broadcast. */
1710 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1711 			int tstamp_len = 3 * sizeof (uint32_t);
1712 
1713 			if (wptr +  tstamp_len > mp->b_wptr) {
1714 				if (!pullupmsg(mp, wptr + tstamp_len -
1715 				    mp->b_rptr)) {
1716 					BUMP_MIB(ill->ill_ip_mib,
1717 					    ipIfStatsInDiscards);
1718 					freemsg(first_mp);
1719 					return;
1720 				}
1721 				/* Refresh ipha following the pullup. */
1722 				ipha = (ipha_t *)mp->b_rptr;
1723 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1724 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1725 			}
1726 			interested = B_TRUE;
1727 		}
1728 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1729 		break;
1730 	case ICMP_TIME_STAMP_REPLY:
1731 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1732 		break;
1733 	case ICMP_INFO_REQUEST:
1734 		/* Per RFC 1122 3.2.2.7, ignore this. */
1735 	case ICMP_INFO_REPLY:
1736 		break;
1737 	case ICMP_ADDRESS_MASK_REQUEST:
1738 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1739 		    !broadcast) &&
1740 		    /* TODO m_pullup of complete header? */
1741 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1742 			interested = B_TRUE;
1743 		}
1744 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1745 		break;
1746 	case ICMP_ADDRESS_MASK_REPLY:
1747 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1748 		break;
1749 	default:
1750 		interested = B_TRUE;	/* Pass up to transport */
1751 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1752 		break;
1753 	}
1754 	/* See if there is an ICMP client. */
1755 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1756 		/* If there is an ICMP client and we want one too, copy it. */
1757 		mblk_t *first_mp1;
1758 
1759 		if (!interested) {
1760 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1761 			    ip_policy, recv_ill, zoneid);
1762 			return;
1763 		}
1764 		first_mp1 = ip_copymsg(first_mp);
1765 		if (first_mp1 != NULL) {
1766 			ip_fanout_proto(q, first_mp1, ill, ipha,
1767 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1768 		}
1769 	} else if (!interested) {
1770 		freemsg(first_mp);
1771 		return;
1772 	} else {
1773 		/*
1774 		 * Initiate policy processing for this packet if ip_policy
1775 		 * is true.
1776 		 */
1777 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1778 			ill_index = ill->ill_phyint->phyint_ifindex;
1779 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1780 			if (mp == NULL) {
1781 				if (mctl_present) {
1782 					freeb(first_mp);
1783 				}
1784 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1785 				return;
1786 			}
1787 		}
1788 	}
1789 	/* We want to do something with it. */
1790 	/* Check db_ref to make sure we can modify the packet. */
1791 	if (mp->b_datap->db_ref > 1) {
1792 		mblk_t	*first_mp1;
1793 
1794 		first_mp1 = ip_copymsg(first_mp);
1795 		freemsg(first_mp);
1796 		if (!first_mp1) {
1797 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1798 			return;
1799 		}
1800 		first_mp = first_mp1;
1801 		if (mctl_present) {
1802 			mp = first_mp->b_cont;
1803 			ASSERT(mp != NULL);
1804 		} else {
1805 			mp = first_mp;
1806 		}
1807 		ipha = (ipha_t *)mp->b_rptr;
1808 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1809 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1810 	}
1811 	switch (icmph->icmph_type) {
1812 	case ICMP_ADDRESS_MASK_REQUEST:
1813 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1814 		if (ipif == NULL) {
1815 			freemsg(first_mp);
1816 			return;
1817 		}
1818 		/*
1819 		 * outging interface must be IPv4
1820 		 */
1821 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1822 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1823 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1824 		ipif_refrele(ipif);
1825 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1826 		break;
1827 	case ICMP_ECHO_REQUEST:
1828 		icmph->icmph_type = ICMP_ECHO_REPLY;
1829 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1830 		break;
1831 	case ICMP_TIME_STAMP_REQUEST: {
1832 		uint32_t *tsp;
1833 
1834 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1835 		tsp = (uint32_t *)wptr;
1836 		tsp++;		/* Skip past 'originate time' */
1837 		/* Compute # of milliseconds since midnight */
1838 		gethrestime(&now);
1839 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1840 		    now.tv_nsec / (NANOSEC / MILLISEC);
1841 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1842 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1843 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1844 		break;
1845 	}
1846 	default:
1847 		ipha = (ipha_t *)&icmph[1];
1848 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1849 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1850 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1851 				freemsg(first_mp);
1852 				return;
1853 			}
1854 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1855 			ipha = (ipha_t *)&icmph[1];
1856 		}
1857 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1858 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1859 			freemsg(first_mp);
1860 			return;
1861 		}
1862 		hdr_length = IPH_HDR_LENGTH(ipha);
1863 		if (hdr_length < sizeof (ipha_t)) {
1864 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1865 			freemsg(first_mp);
1866 			return;
1867 		}
1868 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1869 			if (!pullupmsg(mp,
1870 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1871 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1872 				freemsg(first_mp);
1873 				return;
1874 			}
1875 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1876 			ipha = (ipha_t *)&icmph[1];
1877 		}
1878 		switch (icmph->icmph_type) {
1879 		case ICMP_REDIRECT:
1880 			/*
1881 			 * As there is no upper client to deliver, we don't
1882 			 * need the first_mp any more.
1883 			 */
1884 			if (mctl_present) {
1885 				freeb(first_mp);
1886 			}
1887 			icmp_redirect(ill, mp);
1888 			return;
1889 		case ICMP_DEST_UNREACHABLE:
1890 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1891 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1892 				    zoneid, mp, iph_hdr_length, ipst)) {
1893 					freemsg(first_mp);
1894 					return;
1895 				}
1896 				/*
1897 				 * icmp_inbound_too_big() may alter mp.
1898 				 * Resynch ipha and icmph accordingly.
1899 				 */
1900 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1901 				ipha = (ipha_t *)&icmph[1];
1902 			}
1903 			/* FALLTHRU */
1904 		default :
1905 			/*
1906 			 * IPQoS notes: Since we have already done IPQoS
1907 			 * processing we don't want to do it again in
1908 			 * the fanout routines called by
1909 			 * icmp_inbound_error_fanout, hence the last
1910 			 * argument, ip_policy, is B_FALSE.
1911 			 */
1912 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1913 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1914 			    B_FALSE, recv_ill, zoneid);
1915 		}
1916 		return;
1917 	}
1918 	/* Send out an ICMP packet */
1919 	icmph->icmph_checksum = 0;
1920 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1921 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1922 		ipif_t	*ipif_chosen;
1923 		/*
1924 		 * Make it look like it was directed to us, so we don't look
1925 		 * like a fool with a broadcast or multicast source address.
1926 		 */
1927 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1928 		/*
1929 		 * Make sure that we haven't grabbed an interface that's DOWN.
1930 		 */
1931 		if (ipif != NULL) {
1932 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1933 			    ipha->ipha_src, zoneid);
1934 			if (ipif_chosen != NULL) {
1935 				ipif_refrele(ipif);
1936 				ipif = ipif_chosen;
1937 			}
1938 		}
1939 		if (ipif == NULL) {
1940 			ip0dbg(("icmp_inbound: "
1941 			    "No source for broadcast/multicast:\n"
1942 			    "\tsrc 0x%x dst 0x%x ill %p "
1943 			    "ipif_lcl_addr 0x%x\n",
1944 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1945 			    (void *)ill,
1946 			    ill->ill_ipif->ipif_lcl_addr));
1947 			freemsg(first_mp);
1948 			return;
1949 		}
1950 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1951 		ipha->ipha_dst = ipif->ipif_src_addr;
1952 		ipif_refrele(ipif);
1953 	}
1954 	/* Reset time to live. */
1955 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1956 	{
1957 		/* Swap source and destination addresses */
1958 		ipaddr_t tmp;
1959 
1960 		tmp = ipha->ipha_src;
1961 		ipha->ipha_src = ipha->ipha_dst;
1962 		ipha->ipha_dst = tmp;
1963 	}
1964 	ipha->ipha_ident = 0;
1965 	if (!IS_SIMPLE_IPH(ipha))
1966 		icmp_options_update(ipha);
1967 
1968 	if (!mctl_present) {
1969 		/*
1970 		 * This packet should go out the same way as it
1971 		 * came in i.e in clear. To make sure that global
1972 		 * policy will not be applied to this in ip_wput_ire,
1973 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
1974 		 */
1975 		ASSERT(first_mp == mp);
1976 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
1977 		if (first_mp == NULL) {
1978 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1979 			freemsg(mp);
1980 			return;
1981 		}
1982 		ii = (ipsec_in_t *)first_mp->b_rptr;
1983 
1984 		/* This is not a secure packet */
1985 		ii->ipsec_in_secure = B_FALSE;
1986 		first_mp->b_cont = mp;
1987 	} else {
1988 		ii = (ipsec_in_t *)first_mp->b_rptr;
1989 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
1990 	}
1991 	ii->ipsec_in_zoneid = zoneid;
1992 	ASSERT(zoneid != ALL_ZONES);
1993 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
1994 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1995 		return;
1996 	}
1997 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
1998 	put(WR(q), first_mp);
1999 }
2000 
2001 static ipaddr_t
2002 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2003 {
2004 	conn_t *connp;
2005 	connf_t *connfp;
2006 	ipaddr_t nexthop_addr = INADDR_ANY;
2007 	int hdr_length = IPH_HDR_LENGTH(ipha);
2008 	uint16_t *up;
2009 	uint32_t ports;
2010 	ip_stack_t *ipst = ill->ill_ipst;
2011 
2012 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2013 	switch (ipha->ipha_protocol) {
2014 		case IPPROTO_TCP:
2015 		{
2016 			tcph_t *tcph;
2017 
2018 			/* do a reverse lookup */
2019 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2020 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2021 			    TCPS_LISTEN, ipst);
2022 			break;
2023 		}
2024 		case IPPROTO_UDP:
2025 		{
2026 			uint32_t dstport, srcport;
2027 
2028 			((uint16_t *)&ports)[0] = up[1];
2029 			((uint16_t *)&ports)[1] = up[0];
2030 
2031 			/* Extract ports in net byte order */
2032 			dstport = htons(ntohl(ports) & 0xFFFF);
2033 			srcport = htons(ntohl(ports) >> 16);
2034 
2035 			connfp = &ipst->ips_ipcl_udp_fanout[
2036 			    IPCL_UDP_HASH(dstport, ipst)];
2037 			mutex_enter(&connfp->connf_lock);
2038 			connp = connfp->connf_head;
2039 
2040 			/* do a reverse lookup */
2041 			while ((connp != NULL) &&
2042 			    (!IPCL_UDP_MATCH(connp, dstport,
2043 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2044 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2045 				connp = connp->conn_next;
2046 			}
2047 			if (connp != NULL)
2048 				CONN_INC_REF(connp);
2049 			mutex_exit(&connfp->connf_lock);
2050 			break;
2051 		}
2052 		case IPPROTO_SCTP:
2053 		{
2054 			in6_addr_t map_src, map_dst;
2055 
2056 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2057 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2058 			((uint16_t *)&ports)[0] = up[1];
2059 			((uint16_t *)&ports)[1] = up[0];
2060 
2061 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2062 			    zoneid, ipst->ips_netstack->netstack_sctp);
2063 			if (connp == NULL) {
2064 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2065 				    zoneid, ports, ipha, ipst);
2066 			} else {
2067 				CONN_INC_REF(connp);
2068 				SCTP_REFRELE(CONN2SCTP(connp));
2069 			}
2070 			break;
2071 		}
2072 		default:
2073 		{
2074 			ipha_t ripha;
2075 
2076 			ripha.ipha_src = ipha->ipha_dst;
2077 			ripha.ipha_dst = ipha->ipha_src;
2078 			ripha.ipha_protocol = ipha->ipha_protocol;
2079 
2080 			connfp = &ipst->ips_ipcl_proto_fanout[
2081 			    ipha->ipha_protocol];
2082 			mutex_enter(&connfp->connf_lock);
2083 			connp = connfp->connf_head;
2084 			for (connp = connfp->connf_head; connp != NULL;
2085 			    connp = connp->conn_next) {
2086 				if (IPCL_PROTO_MATCH(connp,
2087 				    ipha->ipha_protocol, &ripha, ill,
2088 				    0, zoneid)) {
2089 					CONN_INC_REF(connp);
2090 					break;
2091 				}
2092 			}
2093 			mutex_exit(&connfp->connf_lock);
2094 		}
2095 	}
2096 	if (connp != NULL) {
2097 		if (connp->conn_nexthop_set)
2098 			nexthop_addr = connp->conn_nexthop_v4;
2099 		CONN_DEC_REF(connp);
2100 	}
2101 	return (nexthop_addr);
2102 }
2103 
2104 /* Table from RFC 1191 */
2105 static int icmp_frag_size_table[] =
2106 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2107 
2108 /*
2109  * Process received ICMP Packet too big.
2110  * After updating any IRE it does the fanout to any matching transport streams.
2111  * Assumes the message has been pulled up till the IP header that caused
2112  * the error.
2113  *
2114  * Returns B_FALSE on failure and B_TRUE on success.
2115  */
2116 static boolean_t
2117 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2118     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2119     ip_stack_t *ipst)
2120 {
2121 	ire_t	*ire, *first_ire;
2122 	int	mtu, orig_mtu;
2123 	int	hdr_length;
2124 	ipaddr_t nexthop_addr;
2125 	boolean_t disable_pmtud;
2126 
2127 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2128 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2129 	ASSERT(ill != NULL);
2130 
2131 	hdr_length = IPH_HDR_LENGTH(ipha);
2132 
2133 	/* Drop if the original packet contained a source route */
2134 	if (ip_source_route_included(ipha)) {
2135 		return (B_FALSE);
2136 	}
2137 	/*
2138 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2139 	 * header.
2140 	 */
2141 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2142 	    mp->b_wptr) {
2143 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2144 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2145 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2146 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2147 			return (B_FALSE);
2148 		}
2149 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2150 		ipha = (ipha_t *)&icmph[1];
2151 	}
2152 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2153 	if (nexthop_addr != INADDR_ANY) {
2154 		/* nexthop set */
2155 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2156 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2157 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2158 	} else {
2159 		/* nexthop not set */
2160 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2161 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2162 	}
2163 
2164 	if (!first_ire) {
2165 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2166 		    ntohl(ipha->ipha_dst)));
2167 		return (B_FALSE);
2168 	}
2169 
2170 	/* Check for MTU discovery advice as described in RFC 1191 */
2171 	mtu = ntohs(icmph->icmph_du_mtu);
2172 	orig_mtu = mtu;
2173 	disable_pmtud = B_FALSE;
2174 
2175 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2176 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2177 	    ire = ire->ire_next) {
2178 		/*
2179 		 * Look for the connection to which this ICMP message is
2180 		 * directed. If it has the IP_NEXTHOP option set, then the
2181 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2182 		 * option. Else the search is limited to regular IREs.
2183 		 */
2184 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2185 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2186 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2187 		    (nexthop_addr != INADDR_ANY)))
2188 			continue;
2189 
2190 		mutex_enter(&ire->ire_lock);
2191 		if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
2192 			uint32_t length;
2193 			int	i;
2194 
2195 			/*
2196 			 * Use the table from RFC 1191 to figure out
2197 			 * the next "plateau" based on the length in
2198 			 * the original IP packet.
2199 			 */
2200 			length = ntohs(ipha->ipha_length);
2201 			DTRACE_PROBE2(ip4__pmtu__guess, ire_t *, ire,
2202 			    uint32_t, length);
2203 			if (ire->ire_max_frag <= length &&
2204 			    ire->ire_max_frag >= length - hdr_length) {
2205 				/*
2206 				 * Handle broken BSD 4.2 systems that
2207 				 * return the wrong iph_length in ICMP
2208 				 * errors.
2209 				 */
2210 				length -= hdr_length;
2211 			}
2212 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2213 				if (length > icmp_frag_size_table[i])
2214 					break;
2215 			}
2216 			if (i == A_CNT(icmp_frag_size_table)) {
2217 				/* Smaller than 68! */
2218 				disable_pmtud = B_TRUE;
2219 				mtu = ipst->ips_ip_pmtu_min;
2220 			} else {
2221 				mtu = icmp_frag_size_table[i];
2222 				if (mtu < ipst->ips_ip_pmtu_min) {
2223 					mtu = ipst->ips_ip_pmtu_min;
2224 					disable_pmtud = B_TRUE;
2225 				}
2226 			}
2227 			/* Fool the ULP into believing our guessed PMTU. */
2228 			icmph->icmph_du_zero = 0;
2229 			icmph->icmph_du_mtu = htons(mtu);
2230 		}
2231 		if (disable_pmtud)
2232 			ire->ire_frag_flag = 0;
2233 		/* Reduce the IRE max frag value as advised. */
2234 		ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2235 		mutex_exit(&ire->ire_lock);
2236 		DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, ire_t *,
2237 		    ire, int, orig_mtu, int, mtu);
2238 	}
2239 	rw_exit(&first_ire->ire_bucket->irb_lock);
2240 	ire_refrele(first_ire);
2241 	return (B_TRUE);
2242 }
2243 
2244 /*
2245  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2246  * calls this function.
2247  */
2248 static mblk_t *
2249 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2250 {
2251 	ipha_t *ipha;
2252 	icmph_t *icmph;
2253 	ipha_t *in_ipha;
2254 	int length;
2255 
2256 	ASSERT(mp->b_datap->db_type == M_DATA);
2257 
2258 	/*
2259 	 * For Self-encapsulated packets, we added an extra IP header
2260 	 * without the options. Inner IP header is the one from which
2261 	 * the outer IP header was formed. Thus, we need to remove the
2262 	 * outer IP header. To do this, we pullup the whole message
2263 	 * and overlay whatever follows the outer IP header over the
2264 	 * outer IP header.
2265 	 */
2266 
2267 	if (!pullupmsg(mp, -1))
2268 		return (NULL);
2269 
2270 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2271 	ipha = (ipha_t *)&icmph[1];
2272 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2273 
2274 	/*
2275 	 * The length that we want to overlay is following the inner
2276 	 * IP header. Subtracting the IP header + icmp header + outer
2277 	 * IP header's length should give us the length that we want to
2278 	 * overlay.
2279 	 */
2280 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2281 	    hdr_length;
2282 	/*
2283 	 * Overlay whatever follows the inner header over the
2284 	 * outer header.
2285 	 */
2286 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2287 
2288 	/* Set the wptr to account for the outer header */
2289 	mp->b_wptr -= hdr_length;
2290 	return (mp);
2291 }
2292 
2293 /*
2294  * Try to pass the ICMP message upstream in case the ULP cares.
2295  *
2296  * If the packet that caused the ICMP error is secure, we send
2297  * it to AH/ESP to make sure that the attached packet has a
2298  * valid association. ipha in the code below points to the
2299  * IP header of the packet that caused the error.
2300  *
2301  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2302  * in the context of IPsec. Normally we tell the upper layer
2303  * whenever we send the ire (including ip_bind), the IPsec header
2304  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2305  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2306  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2307  * same thing. As TCP has the IPsec options size that needs to be
2308  * adjusted, we just pass the MTU unchanged.
2309  *
2310  * IFN could have been generated locally or by some router.
2311  *
2312  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2313  *	    This happens because IP adjusted its value of MTU on an
2314  *	    earlier IFN message and could not tell the upper layer,
2315  *	    the new adjusted value of MTU e.g. Packet was encrypted
2316  *	    or there was not enough information to fanout to upper
2317  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2318  *	    generates the IFN, where IPsec processing has *not* been
2319  *	    done.
2320  *
2321  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2322  *	    could have generated this. This happens because ire_max_frag
2323  *	    value in IP was set to a new value, while the IPsec processing
2324  *	    was being done and after we made the fragmentation check in
2325  *	    ip_wput_ire. Thus on return from IPsec processing,
2326  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2327  *	    and generates the IFN. As IPsec processing is over, we fanout
2328  *	    to AH/ESP to remove the header.
2329  *
2330  *	    In both these cases, ipsec_in_loopback will be set indicating
2331  *	    that IFN was generated locally.
2332  *
2333  * ROUTER : IFN could be secure or non-secure.
2334  *
2335  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2336  *	      packet in error has AH/ESP headers to validate the AH/ESP
2337  *	      headers. AH/ESP will verify whether there is a valid SA or
2338  *	      not and send it back. We will fanout again if we have more
2339  *	      data in the packet.
2340  *
2341  *	      If the packet in error does not have AH/ESP, we handle it
2342  *	      like any other case.
2343  *
2344  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2345  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2346  *	      for validation. AH/ESP will verify whether there is a
2347  *	      valid SA or not and send it back. We will fanout again if
2348  *	      we have more data in the packet.
2349  *
2350  *	      If the packet in error does not have AH/ESP, we handle it
2351  *	      like any other case.
2352  */
2353 static void
2354 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2355     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2356     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2357     zoneid_t zoneid)
2358 {
2359 	uint16_t *up;	/* Pointer to ports in ULP header */
2360 	uint32_t ports;	/* reversed ports for fanout */
2361 	ipha_t ripha;	/* With reversed addresses */
2362 	mblk_t *first_mp;
2363 	ipsec_in_t *ii;
2364 	tcph_t	*tcph;
2365 	conn_t	*connp;
2366 	ip_stack_t *ipst;
2367 
2368 	ASSERT(ill != NULL);
2369 
2370 	ASSERT(recv_ill != NULL);
2371 	ipst = recv_ill->ill_ipst;
2372 
2373 	first_mp = mp;
2374 	if (mctl_present) {
2375 		mp = first_mp->b_cont;
2376 		ASSERT(mp != NULL);
2377 
2378 		ii = (ipsec_in_t *)first_mp->b_rptr;
2379 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2380 	} else {
2381 		ii = NULL;
2382 	}
2383 
2384 	switch (ipha->ipha_protocol) {
2385 	case IPPROTO_UDP:
2386 		/*
2387 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2388 		 * transport header.
2389 		 */
2390 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2391 		    mp->b_wptr) {
2392 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2393 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2394 				goto discard_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 		/*
2402 		 * Attempt to find a client stream based on port.
2403 		 * Note that we do a reverse lookup since the header is
2404 		 * in the form we sent it out.
2405 		 * The ripha header is only used for the IP_UDP_MATCH and we
2406 		 * only set the src and dst addresses and protocol.
2407 		 */
2408 		ripha.ipha_src = ipha->ipha_dst;
2409 		ripha.ipha_dst = ipha->ipha_src;
2410 		ripha.ipha_protocol = ipha->ipha_protocol;
2411 		((uint16_t *)&ports)[0] = up[1];
2412 		((uint16_t *)&ports)[1] = up[0];
2413 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2414 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2415 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2416 		    icmph->icmph_type, icmph->icmph_code));
2417 
2418 		/* Have to change db_type after any pullupmsg */
2419 		DB_TYPE(mp) = M_CTL;
2420 
2421 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2422 		    mctl_present, ip_policy, recv_ill, zoneid);
2423 		return;
2424 
2425 	case IPPROTO_TCP:
2426 		/*
2427 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2428 		 * transport header.
2429 		 */
2430 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2431 		    mp->b_wptr) {
2432 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2433 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2434 				goto discard_pkt;
2435 			}
2436 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2437 			ipha = (ipha_t *)&icmph[1];
2438 		}
2439 		/*
2440 		 * Find a TCP client stream for this packet.
2441 		 * Note that we do a reverse lookup since the header is
2442 		 * in the form we sent it out.
2443 		 */
2444 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2445 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2446 		    ipst);
2447 		if (connp == NULL)
2448 			goto discard_pkt;
2449 
2450 		/* Have to change db_type after any pullupmsg */
2451 		DB_TYPE(mp) = M_CTL;
2452 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, tcp_input, connp,
2453 		    SQ_FILL, SQTAG_TCP_INPUT_ICMP_ERR);
2454 		return;
2455 
2456 	case IPPROTO_SCTP:
2457 		/*
2458 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2459 		 * transport header.
2460 		 */
2461 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2462 		    mp->b_wptr) {
2463 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2464 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2465 				goto discard_pkt;
2466 			}
2467 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2468 			ipha = (ipha_t *)&icmph[1];
2469 		}
2470 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2471 		/*
2472 		 * Find a SCTP client stream for this packet.
2473 		 * Note that we do a reverse lookup since the header is
2474 		 * in the form we sent it out.
2475 		 * The ripha header is only used for the matching and we
2476 		 * only set the src and dst addresses, protocol, and version.
2477 		 */
2478 		ripha.ipha_src = ipha->ipha_dst;
2479 		ripha.ipha_dst = ipha->ipha_src;
2480 		ripha.ipha_protocol = ipha->ipha_protocol;
2481 		ripha.ipha_version_and_hdr_length =
2482 		    ipha->ipha_version_and_hdr_length;
2483 		((uint16_t *)&ports)[0] = up[1];
2484 		((uint16_t *)&ports)[1] = up[0];
2485 
2486 		/* Have to change db_type after any pullupmsg */
2487 		DB_TYPE(mp) = M_CTL;
2488 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2489 		    mctl_present, ip_policy, zoneid);
2490 		return;
2491 
2492 	case IPPROTO_ESP:
2493 	case IPPROTO_AH: {
2494 		int ipsec_rc;
2495 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2496 
2497 		/*
2498 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2499 		 * We will re-use the IPSEC_IN if it is already present as
2500 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2501 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2502 		 * one and attach it in the front.
2503 		 */
2504 		if (ii != NULL) {
2505 			/*
2506 			 * ip_fanout_proto_again converts the ICMP errors
2507 			 * that come back from AH/ESP to M_DATA so that
2508 			 * if it is non-AH/ESP and we do a pullupmsg in
2509 			 * this function, it would work. Convert it back
2510 			 * to M_CTL before we send up as this is a ICMP
2511 			 * error. This could have been generated locally or
2512 			 * by some router. Validate the inner IPsec
2513 			 * headers.
2514 			 *
2515 			 * NOTE : ill_index is used by ip_fanout_proto_again
2516 			 * to locate the ill.
2517 			 */
2518 			ASSERT(ill != NULL);
2519 			ii->ipsec_in_ill_index =
2520 			    ill->ill_phyint->phyint_ifindex;
2521 			ii->ipsec_in_rill_index =
2522 			    recv_ill->ill_phyint->phyint_ifindex;
2523 			DB_TYPE(first_mp->b_cont) = M_CTL;
2524 		} else {
2525 			/*
2526 			 * IPSEC_IN is not present. We attach a ipsec_in
2527 			 * message and send up to IPsec for validating
2528 			 * and removing the IPsec headers. Clear
2529 			 * ipsec_in_secure so that when we return
2530 			 * from IPsec, we don't mistakenly think that this
2531 			 * is a secure packet came from the network.
2532 			 *
2533 			 * NOTE : ill_index is used by ip_fanout_proto_again
2534 			 * to locate the ill.
2535 			 */
2536 			ASSERT(first_mp == mp);
2537 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2538 			if (first_mp == NULL) {
2539 				freemsg(mp);
2540 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2541 				return;
2542 			}
2543 			ii = (ipsec_in_t *)first_mp->b_rptr;
2544 
2545 			/* This is not a secure packet */
2546 			ii->ipsec_in_secure = B_FALSE;
2547 			first_mp->b_cont = mp;
2548 			DB_TYPE(mp) = M_CTL;
2549 			ASSERT(ill != NULL);
2550 			ii->ipsec_in_ill_index =
2551 			    ill->ill_phyint->phyint_ifindex;
2552 			ii->ipsec_in_rill_index =
2553 			    recv_ill->ill_phyint->phyint_ifindex;
2554 		}
2555 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2556 
2557 		if (!ipsec_loaded(ipss)) {
2558 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2559 			return;
2560 		}
2561 
2562 		if (ipha->ipha_protocol == IPPROTO_ESP)
2563 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2564 		else
2565 			ipsec_rc = ipsecah_icmp_error(first_mp);
2566 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2567 			return;
2568 
2569 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2570 		return;
2571 	}
2572 	default:
2573 		/*
2574 		 * The ripha header is only used for the lookup and we
2575 		 * only set the src and dst addresses and protocol.
2576 		 */
2577 		ripha.ipha_src = ipha->ipha_dst;
2578 		ripha.ipha_dst = ipha->ipha_src;
2579 		ripha.ipha_protocol = ipha->ipha_protocol;
2580 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2581 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2582 		    ntohl(ipha->ipha_dst),
2583 		    icmph->icmph_type, icmph->icmph_code));
2584 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2585 			ipha_t *in_ipha;
2586 
2587 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2588 			    mp->b_wptr) {
2589 				if (!pullupmsg(mp, (uchar_t *)ipha +
2590 				    hdr_length + sizeof (ipha_t) -
2591 				    mp->b_rptr)) {
2592 					goto discard_pkt;
2593 				}
2594 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2595 				ipha = (ipha_t *)&icmph[1];
2596 			}
2597 			/*
2598 			 * Caller has verified that length has to be
2599 			 * at least the size of IP header.
2600 			 */
2601 			ASSERT(hdr_length >= sizeof (ipha_t));
2602 			/*
2603 			 * Check the sanity of the inner IP header like
2604 			 * we did for the outer header.
2605 			 */
2606 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2607 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2608 				goto discard_pkt;
2609 			}
2610 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2611 				goto discard_pkt;
2612 			}
2613 			/* Check for Self-encapsulated tunnels */
2614 			if (in_ipha->ipha_src == ipha->ipha_src &&
2615 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2616 
2617 				mp = icmp_inbound_self_encap_error(mp,
2618 				    iph_hdr_length, hdr_length);
2619 				if (mp == NULL)
2620 					goto discard_pkt;
2621 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2622 				ipha = (ipha_t *)&icmph[1];
2623 				hdr_length = IPH_HDR_LENGTH(ipha);
2624 				/*
2625 				 * The packet in error is self-encapsualted.
2626 				 * And we are finding it further encapsulated
2627 				 * which we could not have possibly generated.
2628 				 */
2629 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2630 					goto discard_pkt;
2631 				}
2632 				icmp_inbound_error_fanout(q, ill, first_mp,
2633 				    icmph, ipha, iph_hdr_length, hdr_length,
2634 				    mctl_present, ip_policy, recv_ill, zoneid);
2635 				return;
2636 			}
2637 		}
2638 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2639 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2640 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2641 		    ii != NULL &&
2642 		    ii->ipsec_in_loopback &&
2643 		    ii->ipsec_in_secure) {
2644 			/*
2645 			 * For IP tunnels that get a looped-back
2646 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2647 			 * reported new MTU to take into account the IPsec
2648 			 * headers protecting this configured tunnel.
2649 			 *
2650 			 * This allows the tunnel module (tun.c) to blindly
2651 			 * accept the MTU reported in an ICMP "too big"
2652 			 * message.
2653 			 *
2654 			 * Non-looped back ICMP messages will just be
2655 			 * handled by the security protocols (if needed),
2656 			 * and the first subsequent packet will hit this
2657 			 * path.
2658 			 */
2659 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2660 			    ipsec_in_extra_length(first_mp));
2661 		}
2662 		/* Have to change db_type after any pullupmsg */
2663 		DB_TYPE(mp) = M_CTL;
2664 
2665 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2666 		    ip_policy, recv_ill, zoneid);
2667 		return;
2668 	}
2669 	/* NOTREACHED */
2670 discard_pkt:
2671 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2672 drop_pkt:;
2673 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2674 	freemsg(first_mp);
2675 }
2676 
2677 /*
2678  * Common IP options parser.
2679  *
2680  * Setup routine: fill in *optp with options-parsing state, then
2681  * tail-call ipoptp_next to return the first option.
2682  */
2683 uint8_t
2684 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2685 {
2686 	uint32_t totallen; /* total length of all options */
2687 
2688 	totallen = ipha->ipha_version_and_hdr_length -
2689 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2690 	totallen <<= 2;
2691 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2692 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2693 	optp->ipoptp_flags = 0;
2694 	return (ipoptp_next(optp));
2695 }
2696 
2697 /*
2698  * Common IP options parser: extract next option.
2699  */
2700 uint8_t
2701 ipoptp_next(ipoptp_t *optp)
2702 {
2703 	uint8_t *end = optp->ipoptp_end;
2704 	uint8_t *cur = optp->ipoptp_next;
2705 	uint8_t opt, len, pointer;
2706 
2707 	/*
2708 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2709 	 * has been corrupted.
2710 	 */
2711 	ASSERT(cur <= end);
2712 
2713 	if (cur == end)
2714 		return (IPOPT_EOL);
2715 
2716 	opt = cur[IPOPT_OPTVAL];
2717 
2718 	/*
2719 	 * Skip any NOP options.
2720 	 */
2721 	while (opt == IPOPT_NOP) {
2722 		cur++;
2723 		if (cur == end)
2724 			return (IPOPT_EOL);
2725 		opt = cur[IPOPT_OPTVAL];
2726 	}
2727 
2728 	if (opt == IPOPT_EOL)
2729 		return (IPOPT_EOL);
2730 
2731 	/*
2732 	 * Option requiring a length.
2733 	 */
2734 	if ((cur + 1) >= end) {
2735 		optp->ipoptp_flags |= IPOPTP_ERROR;
2736 		return (IPOPT_EOL);
2737 	}
2738 	len = cur[IPOPT_OLEN];
2739 	if (len < 2) {
2740 		optp->ipoptp_flags |= IPOPTP_ERROR;
2741 		return (IPOPT_EOL);
2742 	}
2743 	optp->ipoptp_cur = cur;
2744 	optp->ipoptp_len = len;
2745 	optp->ipoptp_next = cur + len;
2746 	if (cur + len > end) {
2747 		optp->ipoptp_flags |= IPOPTP_ERROR;
2748 		return (IPOPT_EOL);
2749 	}
2750 
2751 	/*
2752 	 * For the options which require a pointer field, make sure
2753 	 * its there, and make sure it points to either something
2754 	 * inside this option, or the end of the option.
2755 	 */
2756 	switch (opt) {
2757 	case IPOPT_RR:
2758 	case IPOPT_TS:
2759 	case IPOPT_LSRR:
2760 	case IPOPT_SSRR:
2761 		if (len <= IPOPT_OFFSET) {
2762 			optp->ipoptp_flags |= IPOPTP_ERROR;
2763 			return (opt);
2764 		}
2765 		pointer = cur[IPOPT_OFFSET];
2766 		if (pointer - 1 > len) {
2767 			optp->ipoptp_flags |= IPOPTP_ERROR;
2768 			return (opt);
2769 		}
2770 		break;
2771 	}
2772 
2773 	/*
2774 	 * Sanity check the pointer field based on the type of the
2775 	 * option.
2776 	 */
2777 	switch (opt) {
2778 	case IPOPT_RR:
2779 	case IPOPT_SSRR:
2780 	case IPOPT_LSRR:
2781 		if (pointer < IPOPT_MINOFF_SR)
2782 			optp->ipoptp_flags |= IPOPTP_ERROR;
2783 		break;
2784 	case IPOPT_TS:
2785 		if (pointer < IPOPT_MINOFF_IT)
2786 			optp->ipoptp_flags |= IPOPTP_ERROR;
2787 		/*
2788 		 * Note that the Internet Timestamp option also
2789 		 * contains two four bit fields (the Overflow field,
2790 		 * and the Flag field), which follow the pointer
2791 		 * field.  We don't need to check that these fields
2792 		 * fall within the length of the option because this
2793 		 * was implicitely done above.  We've checked that the
2794 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2795 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2796 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2797 		 */
2798 		ASSERT(len > IPOPT_POS_OV_FLG);
2799 		break;
2800 	}
2801 
2802 	return (opt);
2803 }
2804 
2805 /*
2806  * Use the outgoing IP header to create an IP_OPTIONS option the way
2807  * it was passed down from the application.
2808  */
2809 int
2810 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2811 {
2812 	ipoptp_t	opts;
2813 	const uchar_t	*opt;
2814 	uint8_t		optval;
2815 	uint8_t		optlen;
2816 	uint32_t	len = 0;
2817 	uchar_t	*buf1 = buf;
2818 
2819 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2820 	len += IP_ADDR_LEN;
2821 	bzero(buf1, IP_ADDR_LEN);
2822 
2823 	/*
2824 	 * OK to cast away const here, as we don't store through the returned
2825 	 * opts.ipoptp_cur pointer.
2826 	 */
2827 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2828 	    optval != IPOPT_EOL;
2829 	    optval = ipoptp_next(&opts)) {
2830 		int	off;
2831 
2832 		opt = opts.ipoptp_cur;
2833 		optlen = opts.ipoptp_len;
2834 		switch (optval) {
2835 		case IPOPT_SSRR:
2836 		case IPOPT_LSRR:
2837 
2838 			/*
2839 			 * Insert ipha_dst as the first entry in the source
2840 			 * route and move down the entries on step.
2841 			 * The last entry gets placed at buf1.
2842 			 */
2843 			buf[IPOPT_OPTVAL] = optval;
2844 			buf[IPOPT_OLEN] = optlen;
2845 			buf[IPOPT_OFFSET] = optlen;
2846 
2847 			off = optlen - IP_ADDR_LEN;
2848 			if (off < 0) {
2849 				/* No entries in source route */
2850 				break;
2851 			}
2852 			/* Last entry in source route */
2853 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2854 			off -= IP_ADDR_LEN;
2855 
2856 			while (off > 0) {
2857 				bcopy(opt + off,
2858 				    buf + off + IP_ADDR_LEN,
2859 				    IP_ADDR_LEN);
2860 				off -= IP_ADDR_LEN;
2861 			}
2862 			/* ipha_dst into first slot */
2863 			bcopy(&ipha->ipha_dst,
2864 			    buf + off + IP_ADDR_LEN,
2865 			    IP_ADDR_LEN);
2866 			buf += optlen;
2867 			len += optlen;
2868 			break;
2869 
2870 		case IPOPT_COMSEC:
2871 		case IPOPT_SECURITY:
2872 			/* if passing up a label is not ok, then remove */
2873 			if (is_system_labeled())
2874 				break;
2875 			/* FALLTHROUGH */
2876 		default:
2877 			bcopy(opt, buf, optlen);
2878 			buf += optlen;
2879 			len += optlen;
2880 			break;
2881 		}
2882 	}
2883 done:
2884 	/* Pad the resulting options */
2885 	while (len & 0x3) {
2886 		*buf++ = IPOPT_EOL;
2887 		len++;
2888 	}
2889 	return (len);
2890 }
2891 
2892 /*
2893  * Update any record route or timestamp options to include this host.
2894  * Reverse any source route option.
2895  * This routine assumes that the options are well formed i.e. that they
2896  * have already been checked.
2897  */
2898 static void
2899 icmp_options_update(ipha_t *ipha)
2900 {
2901 	ipoptp_t	opts;
2902 	uchar_t		*opt;
2903 	uint8_t		optval;
2904 	ipaddr_t	src;		/* Our local address */
2905 	ipaddr_t	dst;
2906 
2907 	ip2dbg(("icmp_options_update\n"));
2908 	src = ipha->ipha_src;
2909 	dst = ipha->ipha_dst;
2910 
2911 	for (optval = ipoptp_first(&opts, ipha);
2912 	    optval != IPOPT_EOL;
2913 	    optval = ipoptp_next(&opts)) {
2914 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2915 		opt = opts.ipoptp_cur;
2916 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2917 		    optval, opts.ipoptp_len));
2918 		switch (optval) {
2919 			int off1, off2;
2920 		case IPOPT_SSRR:
2921 		case IPOPT_LSRR:
2922 			/*
2923 			 * Reverse the source route.  The first entry
2924 			 * should be the next to last one in the current
2925 			 * source route (the last entry is our address).
2926 			 * The last entry should be the final destination.
2927 			 */
2928 			off1 = IPOPT_MINOFF_SR - 1;
2929 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2930 			if (off2 < 0) {
2931 				/* No entries in source route */
2932 				ip1dbg((
2933 				    "icmp_options_update: bad src route\n"));
2934 				break;
2935 			}
2936 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
2937 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
2938 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
2939 			off2 -= IP_ADDR_LEN;
2940 
2941 			while (off1 < off2) {
2942 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
2943 				bcopy((char *)opt + off2, (char *)opt + off1,
2944 				    IP_ADDR_LEN);
2945 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
2946 				off1 += IP_ADDR_LEN;
2947 				off2 -= IP_ADDR_LEN;
2948 			}
2949 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
2950 			break;
2951 		}
2952 	}
2953 }
2954 
2955 /*
2956  * Process received ICMP Redirect messages.
2957  */
2958 static void
2959 icmp_redirect(ill_t *ill, mblk_t *mp)
2960 {
2961 	ipha_t	*ipha;
2962 	int	iph_hdr_length;
2963 	icmph_t	*icmph;
2964 	ipha_t	*ipha_err;
2965 	ire_t	*ire;
2966 	ire_t	*prev_ire;
2967 	ire_t	*save_ire;
2968 	ipaddr_t  src, dst, gateway;
2969 	iulp_t	ulp_info = { 0 };
2970 	int	error;
2971 	ip_stack_t *ipst;
2972 
2973 	ASSERT(ill != NULL);
2974 	ipst = ill->ill_ipst;
2975 
2976 	ipha = (ipha_t *)mp->b_rptr;
2977 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
2978 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
2979 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
2980 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
2981 		freemsg(mp);
2982 		return;
2983 	}
2984 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2985 	ipha_err = (ipha_t *)&icmph[1];
2986 	src = ipha->ipha_src;
2987 	dst = ipha_err->ipha_dst;
2988 	gateway = icmph->icmph_rd_gateway;
2989 	/* Make sure the new gateway is reachable somehow. */
2990 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
2991 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2992 	/*
2993 	 * Make sure we had a route for the dest in question and that
2994 	 * that route was pointing to the old gateway (the source of the
2995 	 * redirect packet.)
2996 	 */
2997 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
2998 	    NULL, MATCH_IRE_GW, ipst);
2999 	/*
3000 	 * Check that
3001 	 *	the redirect was not from ourselves
3002 	 *	the new gateway and the old gateway are directly reachable
3003 	 */
3004 	if (!prev_ire ||
3005 	    !ire ||
3006 	    ire->ire_type == IRE_LOCAL) {
3007 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3008 		freemsg(mp);
3009 		if (ire != NULL)
3010 			ire_refrele(ire);
3011 		if (prev_ire != NULL)
3012 			ire_refrele(prev_ire);
3013 		return;
3014 	}
3015 
3016 	/*
3017 	 * Should we use the old ULP info to create the new gateway?  From
3018 	 * a user's perspective, we should inherit the info so that it
3019 	 * is a "smooth" transition.  If we do not do that, then new
3020 	 * connections going thru the new gateway will have no route metrics,
3021 	 * which is counter-intuitive to user.  From a network point of
3022 	 * view, this may or may not make sense even though the new gateway
3023 	 * is still directly connected to us so the route metrics should not
3024 	 * change much.
3025 	 *
3026 	 * But if the old ire_uinfo is not initialized, we do another
3027 	 * recursive lookup on the dest using the new gateway.  There may
3028 	 * be a route to that.  If so, use it to initialize the redirect
3029 	 * route.
3030 	 */
3031 	if (prev_ire->ire_uinfo.iulp_set) {
3032 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3033 	} else {
3034 		ire_t *tmp_ire;
3035 		ire_t *sire;
3036 
3037 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3038 		    ALL_ZONES, 0, NULL,
3039 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3040 		    ipst);
3041 		if (sire != NULL) {
3042 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3043 			/*
3044 			 * If sire != NULL, ire_ftable_lookup() should not
3045 			 * return a NULL value.
3046 			 */
3047 			ASSERT(tmp_ire != NULL);
3048 			ire_refrele(tmp_ire);
3049 			ire_refrele(sire);
3050 		} else if (tmp_ire != NULL) {
3051 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3052 			    sizeof (iulp_t));
3053 			ire_refrele(tmp_ire);
3054 		}
3055 	}
3056 	if (prev_ire->ire_type == IRE_CACHE)
3057 		ire_delete(prev_ire);
3058 	ire_refrele(prev_ire);
3059 	/*
3060 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3061 	 * require TOS routing
3062 	 */
3063 	switch (icmph->icmph_code) {
3064 	case 0:
3065 	case 1:
3066 		/* TODO: TOS specificity for cases 2 and 3 */
3067 	case 2:
3068 	case 3:
3069 		break;
3070 	default:
3071 		freemsg(mp);
3072 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3073 		ire_refrele(ire);
3074 		return;
3075 	}
3076 	/*
3077 	 * Create a Route Association.  This will allow us to remember that
3078 	 * someone we believe told us to use the particular gateway.
3079 	 */
3080 	save_ire = ire;
3081 	ire = ire_create(
3082 	    (uchar_t *)&dst,			/* dest addr */
3083 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3084 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3085 	    (uchar_t *)&gateway,		/* gateway addr */
3086 	    &save_ire->ire_max_frag,		/* max frag */
3087 	    NULL,				/* no src nce */
3088 	    NULL,				/* no rfq */
3089 	    NULL,				/* no stq */
3090 	    IRE_HOST,
3091 	    NULL,				/* ipif */
3092 	    0,					/* cmask */
3093 	    0,					/* phandle */
3094 	    0,					/* ihandle */
3095 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3096 	    &ulp_info,
3097 	    NULL,				/* tsol_gc_t */
3098 	    NULL,				/* gcgrp */
3099 	    ipst);
3100 
3101 	if (ire == NULL) {
3102 		freemsg(mp);
3103 		ire_refrele(save_ire);
3104 		return;
3105 	}
3106 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3107 	ire_refrele(save_ire);
3108 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3109 
3110 	if (error == 0) {
3111 		ire_refrele(ire);		/* Held in ire_add_v4 */
3112 		/* tell routing sockets that we received a redirect */
3113 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3114 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3115 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3116 	}
3117 
3118 	/*
3119 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3120 	 * This together with the added IRE has the effect of
3121 	 * modifying an existing redirect.
3122 	 */
3123 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3124 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3125 	if (prev_ire != NULL) {
3126 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3127 			ire_delete(prev_ire);
3128 		ire_refrele(prev_ire);
3129 	}
3130 
3131 	freemsg(mp);
3132 }
3133 
3134 /*
3135  * Generate an ICMP parameter problem message.
3136  */
3137 static void
3138 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3139 	ip_stack_t *ipst)
3140 {
3141 	icmph_t	icmph;
3142 	boolean_t mctl_present;
3143 	mblk_t *first_mp;
3144 
3145 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3146 
3147 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3148 		if (mctl_present)
3149 			freeb(first_mp);
3150 		return;
3151 	}
3152 
3153 	bzero(&icmph, sizeof (icmph_t));
3154 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3155 	icmph.icmph_pp_ptr = ptr;
3156 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3157 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3158 	    ipst);
3159 }
3160 
3161 /*
3162  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3163  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3164  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3165  * an icmp error packet can be sent.
3166  * Assigns an appropriate source address to the packet. If ipha_dst is
3167  * one of our addresses use it for source. Otherwise pick a source based
3168  * on a route lookup back to ipha_src.
3169  * Note that ipha_src must be set here since the
3170  * packet is likely to arrive on an ill queue in ip_wput() which will
3171  * not set a source address.
3172  */
3173 static void
3174 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3175     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3176 {
3177 	ipaddr_t dst;
3178 	icmph_t	*icmph;
3179 	ipha_t	*ipha;
3180 	uint_t	len_needed;
3181 	size_t	msg_len;
3182 	mblk_t	*mp1;
3183 	ipaddr_t src;
3184 	ire_t	*ire;
3185 	mblk_t *ipsec_mp;
3186 	ipsec_out_t	*io = NULL;
3187 
3188 	if (mctl_present) {
3189 		/*
3190 		 * If it is :
3191 		 *
3192 		 * 1) a IPSEC_OUT, then this is caused by outbound
3193 		 *    datagram originating on this host. IPsec processing
3194 		 *    may or may not have been done. Refer to comments above
3195 		 *    icmp_inbound_error_fanout for details.
3196 		 *
3197 		 * 2) a IPSEC_IN if we are generating a icmp_message
3198 		 *    for an incoming datagram destined for us i.e called
3199 		 *    from ip_fanout_send_icmp.
3200 		 */
3201 		ipsec_info_t *in;
3202 		ipsec_mp = mp;
3203 		mp = ipsec_mp->b_cont;
3204 
3205 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3206 		ipha = (ipha_t *)mp->b_rptr;
3207 
3208 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3209 		    in->ipsec_info_type == IPSEC_IN);
3210 
3211 		if (in->ipsec_info_type == IPSEC_IN) {
3212 			/*
3213 			 * Convert the IPSEC_IN to IPSEC_OUT.
3214 			 */
3215 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3216 				BUMP_MIB(&ipst->ips_ip_mib,
3217 				    ipIfStatsOutDiscards);
3218 				return;
3219 			}
3220 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3221 		} else {
3222 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3223 			io = (ipsec_out_t *)in;
3224 			/*
3225 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3226 			 * ire lookup.
3227 			 */
3228 			io->ipsec_out_proc_begin = B_FALSE;
3229 		}
3230 		ASSERT(zoneid == io->ipsec_out_zoneid);
3231 		ASSERT(zoneid != ALL_ZONES);
3232 	} else {
3233 		/*
3234 		 * This is in clear. The icmp message we are building
3235 		 * here should go out in clear.
3236 		 *
3237 		 * Pardon the convolution of it all, but it's easier to
3238 		 * allocate a "use cleartext" IPSEC_IN message and convert
3239 		 * it than it is to allocate a new one.
3240 		 */
3241 		ipsec_in_t *ii;
3242 		ASSERT(DB_TYPE(mp) == M_DATA);
3243 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3244 		if (ipsec_mp == NULL) {
3245 			freemsg(mp);
3246 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3247 			return;
3248 		}
3249 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3250 
3251 		/* This is not a secure packet */
3252 		ii->ipsec_in_secure = B_FALSE;
3253 		/*
3254 		 * For trusted extensions using a shared IP address we can
3255 		 * send using any zoneid.
3256 		 */
3257 		if (zoneid == ALL_ZONES)
3258 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3259 		else
3260 			ii->ipsec_in_zoneid = zoneid;
3261 		ipsec_mp->b_cont = mp;
3262 		ipha = (ipha_t *)mp->b_rptr;
3263 		/*
3264 		 * Convert the IPSEC_IN to IPSEC_OUT.
3265 		 */
3266 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3267 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3268 			return;
3269 		}
3270 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3271 	}
3272 
3273 	/* Remember our eventual destination */
3274 	dst = ipha->ipha_src;
3275 
3276 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3277 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3278 	if (ire != NULL &&
3279 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3280 		src = ipha->ipha_dst;
3281 	} else {
3282 		if (ire != NULL)
3283 			ire_refrele(ire);
3284 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3285 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3286 		    ipst);
3287 		if (ire == NULL) {
3288 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3289 			freemsg(ipsec_mp);
3290 			return;
3291 		}
3292 		src = ire->ire_src_addr;
3293 	}
3294 
3295 	if (ire != NULL)
3296 		ire_refrele(ire);
3297 
3298 	/*
3299 	 * Check if we can send back more then 8 bytes in addition to
3300 	 * the IP header.  We try to send 64 bytes of data and the internal
3301 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3302 	 */
3303 	len_needed = IPH_HDR_LENGTH(ipha);
3304 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3305 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3306 
3307 		if (!pullupmsg(mp, -1)) {
3308 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3309 			freemsg(ipsec_mp);
3310 			return;
3311 		}
3312 		ipha = (ipha_t *)mp->b_rptr;
3313 
3314 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3315 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3316 			    len_needed));
3317 		} else {
3318 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3319 
3320 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3321 			len_needed += ip_hdr_length_v6(mp, ip6h);
3322 		}
3323 	}
3324 	len_needed += ipst->ips_ip_icmp_return;
3325 	msg_len = msgdsize(mp);
3326 	if (msg_len > len_needed) {
3327 		(void) adjmsg(mp, len_needed - msg_len);
3328 		msg_len = len_needed;
3329 	}
3330 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3331 	if (mp1 == NULL) {
3332 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3333 		freemsg(ipsec_mp);
3334 		return;
3335 	}
3336 	mp1->b_cont = mp;
3337 	mp = mp1;
3338 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3339 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3340 	    io->ipsec_out_type == IPSEC_OUT);
3341 	ipsec_mp->b_cont = mp;
3342 
3343 	/*
3344 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3345 	 * node generates be accepted in peace by all on-host destinations.
3346 	 * If we do NOT assume that all on-host destinations trust
3347 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3348 	 * (Look for ipsec_out_icmp_loopback).
3349 	 */
3350 	io->ipsec_out_icmp_loopback = B_TRUE;
3351 
3352 	ipha = (ipha_t *)mp->b_rptr;
3353 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3354 	*ipha = icmp_ipha;
3355 	ipha->ipha_src = src;
3356 	ipha->ipha_dst = dst;
3357 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3358 	msg_len += sizeof (icmp_ipha) + len;
3359 	if (msg_len > IP_MAXPACKET) {
3360 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3361 		msg_len = IP_MAXPACKET;
3362 	}
3363 	ipha->ipha_length = htons((uint16_t)msg_len);
3364 	icmph = (icmph_t *)&ipha[1];
3365 	bcopy(stuff, icmph, len);
3366 	icmph->icmph_checksum = 0;
3367 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3368 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3369 	put(q, ipsec_mp);
3370 }
3371 
3372 /*
3373  * Determine if an ICMP error packet can be sent given the rate limit.
3374  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3375  * in milliseconds) and a burst size. Burst size number of packets can
3376  * be sent arbitrarely closely spaced.
3377  * The state is tracked using two variables to implement an approximate
3378  * token bucket filter:
3379  *	icmp_pkt_err_last - lbolt value when the last burst started
3380  *	icmp_pkt_err_sent - number of packets sent in current burst
3381  */
3382 boolean_t
3383 icmp_err_rate_limit(ip_stack_t *ipst)
3384 {
3385 	clock_t now = TICK_TO_MSEC(lbolt);
3386 	uint_t refilled; /* Number of packets refilled in tbf since last */
3387 	/* Guard against changes by loading into local variable */
3388 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3389 
3390 	if (err_interval == 0)
3391 		return (B_FALSE);
3392 
3393 	if (ipst->ips_icmp_pkt_err_last > now) {
3394 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3395 		ipst->ips_icmp_pkt_err_last = 0;
3396 		ipst->ips_icmp_pkt_err_sent = 0;
3397 	}
3398 	/*
3399 	 * If we are in a burst update the token bucket filter.
3400 	 * Update the "last" time to be close to "now" but make sure
3401 	 * we don't loose precision.
3402 	 */
3403 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3404 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3405 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3406 			ipst->ips_icmp_pkt_err_sent = 0;
3407 		} else {
3408 			ipst->ips_icmp_pkt_err_sent -= refilled;
3409 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3410 		}
3411 	}
3412 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3413 		/* Start of new burst */
3414 		ipst->ips_icmp_pkt_err_last = now;
3415 	}
3416 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3417 		ipst->ips_icmp_pkt_err_sent++;
3418 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3419 		    ipst->ips_icmp_pkt_err_sent));
3420 		return (B_FALSE);
3421 	}
3422 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3423 	return (B_TRUE);
3424 }
3425 
3426 /*
3427  * Check if it is ok to send an IPv4 ICMP error packet in
3428  * response to the IPv4 packet in mp.
3429  * Free the message and return null if no
3430  * ICMP error packet should be sent.
3431  */
3432 static mblk_t *
3433 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3434 {
3435 	icmph_t	*icmph;
3436 	ipha_t	*ipha;
3437 	uint_t	len_needed;
3438 	ire_t	*src_ire;
3439 	ire_t	*dst_ire;
3440 
3441 	if (!mp)
3442 		return (NULL);
3443 	ipha = (ipha_t *)mp->b_rptr;
3444 	if (ip_csum_hdr(ipha)) {
3445 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3446 		freemsg(mp);
3447 		return (NULL);
3448 	}
3449 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3450 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3451 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3452 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3453 	if (src_ire != NULL || dst_ire != NULL ||
3454 	    CLASSD(ipha->ipha_dst) ||
3455 	    CLASSD(ipha->ipha_src) ||
3456 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3457 		/* Note: only errors to the fragment with offset 0 */
3458 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3459 		freemsg(mp);
3460 		if (src_ire != NULL)
3461 			ire_refrele(src_ire);
3462 		if (dst_ire != NULL)
3463 			ire_refrele(dst_ire);
3464 		return (NULL);
3465 	}
3466 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3467 		/*
3468 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3469 		 * errors in response to any ICMP errors.
3470 		 */
3471 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3472 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3473 			if (!pullupmsg(mp, len_needed)) {
3474 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3475 				freemsg(mp);
3476 				return (NULL);
3477 			}
3478 			ipha = (ipha_t *)mp->b_rptr;
3479 		}
3480 		icmph = (icmph_t *)
3481 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3482 		switch (icmph->icmph_type) {
3483 		case ICMP_DEST_UNREACHABLE:
3484 		case ICMP_SOURCE_QUENCH:
3485 		case ICMP_TIME_EXCEEDED:
3486 		case ICMP_PARAM_PROBLEM:
3487 		case ICMP_REDIRECT:
3488 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3489 			freemsg(mp);
3490 			return (NULL);
3491 		default:
3492 			break;
3493 		}
3494 	}
3495 	/*
3496 	 * If this is a labeled system, then check to see if we're allowed to
3497 	 * send a response to this particular sender.  If not, then just drop.
3498 	 */
3499 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3500 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3501 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3502 		freemsg(mp);
3503 		return (NULL);
3504 	}
3505 	if (icmp_err_rate_limit(ipst)) {
3506 		/*
3507 		 * Only send ICMP error packets every so often.
3508 		 * This should be done on a per port/source basis,
3509 		 * but for now this will suffice.
3510 		 */
3511 		freemsg(mp);
3512 		return (NULL);
3513 	}
3514 	return (mp);
3515 }
3516 
3517 /*
3518  * Generate an ICMP redirect message.
3519  */
3520 static void
3521 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3522 {
3523 	icmph_t	icmph;
3524 
3525 	/*
3526 	 * We are called from ip_rput where we could
3527 	 * not have attached an IPSEC_IN.
3528 	 */
3529 	ASSERT(mp->b_datap->db_type == M_DATA);
3530 
3531 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3532 		return;
3533 	}
3534 
3535 	bzero(&icmph, sizeof (icmph_t));
3536 	icmph.icmph_type = ICMP_REDIRECT;
3537 	icmph.icmph_code = 1;
3538 	icmph.icmph_rd_gateway = gateway;
3539 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3540 	/* Redirects sent by router, and router is global zone */
3541 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3542 }
3543 
3544 /*
3545  * Generate an ICMP time exceeded message.
3546  */
3547 void
3548 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3549     ip_stack_t *ipst)
3550 {
3551 	icmph_t	icmph;
3552 	boolean_t mctl_present;
3553 	mblk_t *first_mp;
3554 
3555 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3556 
3557 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3558 		if (mctl_present)
3559 			freeb(first_mp);
3560 		return;
3561 	}
3562 
3563 	bzero(&icmph, sizeof (icmph_t));
3564 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3565 	icmph.icmph_code = code;
3566 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3567 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3568 	    ipst);
3569 }
3570 
3571 /*
3572  * Generate an ICMP unreachable message.
3573  */
3574 void
3575 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3576     ip_stack_t *ipst)
3577 {
3578 	icmph_t	icmph;
3579 	mblk_t *first_mp;
3580 	boolean_t mctl_present;
3581 
3582 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3583 
3584 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3585 		if (mctl_present)
3586 			freeb(first_mp);
3587 		return;
3588 	}
3589 
3590 	bzero(&icmph, sizeof (icmph_t));
3591 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3592 	icmph.icmph_code = code;
3593 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3594 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3595 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3596 	    zoneid, ipst);
3597 }
3598 
3599 /*
3600  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3601  * duplicate.  As long as someone else holds the address, the interface will
3602  * stay down.  When that conflict goes away, the interface is brought back up.
3603  * This is done so that accidental shutdowns of addresses aren't made
3604  * permanent.  Your server will recover from a failure.
3605  *
3606  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3607  * user space process (dhcpagent).
3608  *
3609  * Recovery completes if ARP reports that the address is now ours (via
3610  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3611  *
3612  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3613  */
3614 static void
3615 ipif_dup_recovery(void *arg)
3616 {
3617 	ipif_t *ipif = arg;
3618 	ill_t *ill = ipif->ipif_ill;
3619 	mblk_t *arp_add_mp;
3620 	mblk_t *arp_del_mp;
3621 	ip_stack_t *ipst = ill->ill_ipst;
3622 
3623 	ipif->ipif_recovery_id = 0;
3624 
3625 	/*
3626 	 * No lock needed for moving or condemned check, as this is just an
3627 	 * optimization.
3628 	 */
3629 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3630 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3631 	    (ipif->ipif_state_flags & (IPIF_CONDEMNED))) {
3632 		/* No reason to try to bring this address back. */
3633 		return;
3634 	}
3635 
3636 	/* ACE_F_UNVERIFIED restarts DAD */
3637 	if ((arp_add_mp = ipif_area_alloc(ipif, ACE_F_UNVERIFIED)) == NULL)
3638 		goto alloc_fail;
3639 
3640 	if (ipif->ipif_arp_del_mp == NULL) {
3641 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3642 			goto alloc_fail;
3643 		ipif->ipif_arp_del_mp = arp_del_mp;
3644 	}
3645 
3646 	putnext(ill->ill_rq, arp_add_mp);
3647 	return;
3648 
3649 alloc_fail:
3650 	/*
3651 	 * On allocation failure, just restart the timer.  Note that the ipif
3652 	 * is down here, so no other thread could be trying to start a recovery
3653 	 * timer.  The ill_lock protects the condemned flag and the recovery
3654 	 * timer ID.
3655 	 */
3656 	freemsg(arp_add_mp);
3657 	mutex_enter(&ill->ill_lock);
3658 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3659 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3660 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3661 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3662 	}
3663 	mutex_exit(&ill->ill_lock);
3664 }
3665 
3666 /*
3667  * This is for exclusive changes due to ARP.  Either tear down an interface due
3668  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3669  */
3670 /* ARGSUSED */
3671 static void
3672 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3673 {
3674 	ill_t	*ill = rq->q_ptr;
3675 	arh_t *arh;
3676 	ipaddr_t src;
3677 	ipif_t	*ipif;
3678 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3679 	char hbuf[MAC_STR_LEN];
3680 	char sbuf[INET_ADDRSTRLEN];
3681 	const char *failtype;
3682 	boolean_t bring_up;
3683 	ip_stack_t *ipst = ill->ill_ipst;
3684 
3685 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3686 	case AR_CN_READY:
3687 		failtype = NULL;
3688 		bring_up = B_TRUE;
3689 		break;
3690 	case AR_CN_FAILED:
3691 		failtype = "in use";
3692 		bring_up = B_FALSE;
3693 		break;
3694 	default:
3695 		failtype = "claimed";
3696 		bring_up = B_FALSE;
3697 		break;
3698 	}
3699 
3700 	arh = (arh_t *)mp->b_cont->b_rptr;
3701 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3702 
3703 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3704 	    sizeof (hbuf));
3705 	(void) ip_dot_addr(src, sbuf);
3706 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3707 
3708 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3709 		    ipif->ipif_lcl_addr != src) {
3710 			continue;
3711 		}
3712 
3713 		/*
3714 		 * If we failed on a recovery probe, then restart the timer to
3715 		 * try again later.
3716 		 */
3717 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3718 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3719 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3720 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3721 		    ipst->ips_ip_dup_recovery > 0 &&
3722 		    ipif->ipif_recovery_id == 0) {
3723 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3724 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3725 			continue;
3726 		}
3727 
3728 		/*
3729 		 * If what we're trying to do has already been done, then do
3730 		 * nothing.
3731 		 */
3732 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3733 			continue;
3734 
3735 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3736 
3737 		if (failtype == NULL) {
3738 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3739 			    ibuf);
3740 		} else {
3741 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3742 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3743 		}
3744 
3745 		if (bring_up) {
3746 			ASSERT(ill->ill_dl_up);
3747 			/*
3748 			 * Free up the ARP delete message so we can allocate
3749 			 * a fresh one through the normal path.
3750 			 */
3751 			freemsg(ipif->ipif_arp_del_mp);
3752 			ipif->ipif_arp_del_mp = NULL;
3753 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3754 			    EINPROGRESS) {
3755 				ipif->ipif_addr_ready = 1;
3756 				(void) ipif_up_done(ipif);
3757 				ASSERT(ill->ill_move_ipif == NULL);
3758 			}
3759 			continue;
3760 		}
3761 
3762 		mutex_enter(&ill->ill_lock);
3763 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3764 		ipif->ipif_flags |= IPIF_DUPLICATE;
3765 		ill->ill_ipif_dup_count++;
3766 		mutex_exit(&ill->ill_lock);
3767 		/*
3768 		 * Already exclusive on the ill; no need to handle deferred
3769 		 * processing here.
3770 		 */
3771 		(void) ipif_down(ipif, NULL, NULL);
3772 		ipif_down_tail(ipif);
3773 		mutex_enter(&ill->ill_lock);
3774 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3775 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3776 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3777 		    ipst->ips_ip_dup_recovery > 0) {
3778 			ASSERT(ipif->ipif_recovery_id == 0);
3779 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3780 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3781 		}
3782 		mutex_exit(&ill->ill_lock);
3783 	}
3784 	freemsg(mp);
3785 }
3786 
3787 /* ARGSUSED */
3788 static void
3789 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3790 {
3791 	ill_t	*ill = rq->q_ptr;
3792 	arh_t *arh;
3793 	ipaddr_t src;
3794 	ipif_t	*ipif;
3795 
3796 	arh = (arh_t *)mp->b_cont->b_rptr;
3797 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3798 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3799 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3800 			(void) ipif_resolver_up(ipif, Res_act_defend);
3801 	}
3802 	freemsg(mp);
3803 }
3804 
3805 /*
3806  * News from ARP.  ARP sends notification of interesting events down
3807  * to its clients using M_CTL messages with the interesting ARP packet
3808  * attached via b_cont.
3809  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3810  * queue as opposed to ARP sending the message to all the clients, i.e. all
3811  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3812  * table if a cache IRE is found to delete all the entries for the address in
3813  * the packet.
3814  */
3815 static void
3816 ip_arp_news(queue_t *q, mblk_t *mp)
3817 {
3818 	arcn_t		*arcn;
3819 	arh_t		*arh;
3820 	ire_t		*ire = NULL;
3821 	char		hbuf[MAC_STR_LEN];
3822 	char		sbuf[INET_ADDRSTRLEN];
3823 	ipaddr_t	src;
3824 	in6_addr_t	v6src;
3825 	boolean_t	isv6 = B_FALSE;
3826 	ipif_t		*ipif;
3827 	ill_t		*ill;
3828 	ip_stack_t	*ipst;
3829 
3830 	if (CONN_Q(q)) {
3831 		conn_t *connp = Q_TO_CONN(q);
3832 
3833 		ipst = connp->conn_netstack->netstack_ip;
3834 	} else {
3835 		ill_t *ill = (ill_t *)q->q_ptr;
3836 
3837 		ipst = ill->ill_ipst;
3838 	}
3839 
3840 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3841 		if (q->q_next) {
3842 			putnext(q, mp);
3843 		} else
3844 			freemsg(mp);
3845 		return;
3846 	}
3847 	arh = (arh_t *)mp->b_cont->b_rptr;
3848 	/* Is it one we are interested in? */
3849 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3850 		isv6 = B_TRUE;
3851 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3852 		    IPV6_ADDR_LEN);
3853 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3854 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3855 		    IP_ADDR_LEN);
3856 	} else {
3857 		freemsg(mp);
3858 		return;
3859 	}
3860 
3861 	ill = q->q_ptr;
3862 
3863 	arcn = (arcn_t *)mp->b_rptr;
3864 	switch (arcn->arcn_code) {
3865 	case AR_CN_BOGON:
3866 		/*
3867 		 * Someone is sending ARP packets with a source protocol
3868 		 * address that we have published and for which we believe our
3869 		 * entry is authoritative and (when ill_arp_extend is set)
3870 		 * verified to be unique on the network.
3871 		 *
3872 		 * The ARP module internally handles the cases where the sender
3873 		 * is just probing (for DAD) and where the hardware address of
3874 		 * a non-authoritative entry has changed.  Thus, these are the
3875 		 * real conflicts, and we have to do resolution.
3876 		 *
3877 		 * We back away quickly from the address if it's from DHCP or
3878 		 * otherwise temporary and hasn't been used recently (or at
3879 		 * all).  We'd like to include "deprecated" addresses here as
3880 		 * well (as there's no real reason to defend something we're
3881 		 * discarding), but IPMP "reuses" this flag to mean something
3882 		 * other than the standard meaning.
3883 		 *
3884 		 * If the ARP module above is not extended (meaning that it
3885 		 * doesn't know how to defend the address), then we just log
3886 		 * the problem as we always did and continue on.  It's not
3887 		 * right, but there's little else we can do, and those old ATM
3888 		 * users are going away anyway.
3889 		 */
3890 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3891 		    hbuf, sizeof (hbuf));
3892 		(void) ip_dot_addr(src, sbuf);
3893 		if (isv6) {
3894 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3895 			    ipst);
3896 		} else {
3897 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3898 		}
3899 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3900 			uint32_t now;
3901 			uint32_t maxage;
3902 			clock_t lused;
3903 			uint_t maxdefense;
3904 			uint_t defs;
3905 
3906 			/*
3907 			 * First, figure out if this address hasn't been used
3908 			 * in a while.  If it hasn't, then it's a better
3909 			 * candidate for abandoning.
3910 			 */
3911 			ipif = ire->ire_ipif;
3912 			ASSERT(ipif != NULL);
3913 			now = gethrestime_sec();
3914 			maxage = now - ire->ire_create_time;
3915 			if (maxage > ipst->ips_ip_max_temp_idle)
3916 				maxage = ipst->ips_ip_max_temp_idle;
3917 			lused = drv_hztousec(ddi_get_lbolt() -
3918 			    ire->ire_last_used_time) / MICROSEC + 1;
3919 			if (lused >= maxage && (ipif->ipif_flags &
3920 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
3921 				maxdefense = ipst->ips_ip_max_temp_defend;
3922 			else
3923 				maxdefense = ipst->ips_ip_max_defend;
3924 
3925 			/*
3926 			 * Now figure out how many times we've defended
3927 			 * ourselves.  Ignore defenses that happened long in
3928 			 * the past.
3929 			 */
3930 			mutex_enter(&ire->ire_lock);
3931 			if ((defs = ire->ire_defense_count) > 0 &&
3932 			    now - ire->ire_defense_time >
3933 			    ipst->ips_ip_defend_interval) {
3934 				ire->ire_defense_count = defs = 0;
3935 			}
3936 			ire->ire_defense_count++;
3937 			ire->ire_defense_time = now;
3938 			mutex_exit(&ire->ire_lock);
3939 			ill_refhold(ill);
3940 			ire_refrele(ire);
3941 
3942 			/*
3943 			 * If we've defended ourselves too many times already,
3944 			 * then give up and tear down the interface(s) using
3945 			 * this address.  Otherwise, defend by sending out a
3946 			 * gratuitous ARP.
3947 			 */
3948 			if (defs >= maxdefense && ill->ill_arp_extend) {
3949 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
3950 				    B_FALSE);
3951 			} else {
3952 				cmn_err(CE_WARN,
3953 				    "node %s is using our IP address %s on %s",
3954 				    hbuf, sbuf, ill->ill_name);
3955 				/*
3956 				 * If this is an old (ATM) ARP module, then
3957 				 * don't try to defend the address.  Remain
3958 				 * compatible with the old behavior.  Defend
3959 				 * only with new ARP.
3960 				 */
3961 				if (ill->ill_arp_extend) {
3962 					qwriter_ip(ill, q, mp, ip_arp_defend,
3963 					    NEW_OP, B_FALSE);
3964 				} else {
3965 					ill_refrele(ill);
3966 				}
3967 			}
3968 			return;
3969 		}
3970 		cmn_err(CE_WARN,
3971 		    "proxy ARP problem?  Node '%s' is using %s on %s",
3972 		    hbuf, sbuf, ill->ill_name);
3973 		if (ire != NULL)
3974 			ire_refrele(ire);
3975 		break;
3976 	case AR_CN_ANNOUNCE:
3977 		if (isv6) {
3978 			/*
3979 			 * For XRESOLV interfaces.
3980 			 * Delete the IRE cache entry and NCE for this
3981 			 * v6 address
3982 			 */
3983 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
3984 			/*
3985 			 * If v6src is a non-zero, it's a router address
3986 			 * as below. Do the same sort of thing to clean
3987 			 * out off-net IRE_CACHE entries that go through
3988 			 * the router.
3989 			 */
3990 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
3991 				ire_walk_v6(ire_delete_cache_gw_v6,
3992 				    (char *)&v6src, ALL_ZONES, ipst);
3993 			}
3994 		} else {
3995 			nce_hw_map_t hwm;
3996 
3997 			/*
3998 			 * ARP gives us a copy of any packet where it thinks
3999 			 * the address has changed, so that we can update our
4000 			 * caches.  We're responsible for caching known answers
4001 			 * in the current design.  We check whether the
4002 			 * hardware address really has changed in all of our
4003 			 * entries that have cached this mapping, and if so, we
4004 			 * blow them away.  This way we will immediately pick
4005 			 * up the rare case of a host changing hardware
4006 			 * address.
4007 			 */
4008 			if (src == 0)
4009 				break;
4010 			hwm.hwm_addr = src;
4011 			hwm.hwm_hwlen = arh->arh_hlen;
4012 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4013 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4014 			ndp_walk_common(ipst->ips_ndp4, NULL,
4015 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4016 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4017 		}
4018 		break;
4019 	case AR_CN_READY:
4020 		/* No external v6 resolver has a contract to use this */
4021 		if (isv6)
4022 			break;
4023 		/* If the link is down, we'll retry this later */
4024 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4025 			break;
4026 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4027 		    NULL, NULL, ipst);
4028 		if (ipif != NULL) {
4029 			/*
4030 			 * If this is a duplicate recovery, then we now need to
4031 			 * go exclusive to bring this thing back up.
4032 			 */
4033 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4034 			    IPIF_DUPLICATE) {
4035 				ipif_refrele(ipif);
4036 				ill_refhold(ill);
4037 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4038 				    B_FALSE);
4039 				return;
4040 			}
4041 			/*
4042 			 * If this is the first notice that this address is
4043 			 * ready, then let the user know now.
4044 			 */
4045 			if ((ipif->ipif_flags & IPIF_UP) &&
4046 			    !ipif->ipif_addr_ready) {
4047 				ipif_mask_reply(ipif);
4048 				ipif_up_notify(ipif);
4049 			}
4050 			ipif->ipif_addr_ready = 1;
4051 			ipif_refrele(ipif);
4052 		}
4053 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4054 		if (ire != NULL) {
4055 			ire->ire_defense_count = 0;
4056 			ire_refrele(ire);
4057 		}
4058 		break;
4059 	case AR_CN_FAILED:
4060 		/* No external v6 resolver has a contract to use this */
4061 		if (isv6)
4062 			break;
4063 		ill_refhold(ill);
4064 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4065 		return;
4066 	}
4067 	freemsg(mp);
4068 }
4069 
4070 /*
4071  * Create a mblk suitable for carrying the interface index and/or source link
4072  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4073  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4074  * application.
4075  */
4076 mblk_t *
4077 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4078     ip_stack_t *ipst)
4079 {
4080 	mblk_t		*mp;
4081 	ip_pktinfo_t	*pinfo;
4082 	ipha_t 		*ipha;
4083 	struct ether_header *pether;
4084 	boolean_t	ipmp_ill_held = B_FALSE;
4085 
4086 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4087 	if (mp == NULL) {
4088 		ip1dbg(("ip_add_info: allocation failure.\n"));
4089 		return (data_mp);
4090 	}
4091 
4092 	ipha = (ipha_t *)data_mp->b_rptr;
4093 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4094 	bzero(pinfo, sizeof (ip_pktinfo_t));
4095 	pinfo->ip_pkt_flags = (uchar_t)flags;
4096 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4097 
4098 	pether = (struct ether_header *)((char *)ipha
4099 	    - sizeof (struct ether_header));
4100 
4101 	/*
4102 	 * Make sure the interface is an ethernet type, since this option
4103 	 * is currently supported only on this type of interface. Also make
4104 	 * sure we are pointing correctly above db_base.
4105 	 */
4106 	if ((flags & IPF_RECVSLLA) &&
4107 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4108 	    (ill->ill_type == IFT_ETHER) &&
4109 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4110 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4111 		bcopy(pether->ether_shost.ether_addr_octet,
4112 		    pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4113 	} else {
4114 		/*
4115 		 * Clear the bit. Indicate to upper layer that IP is not
4116 		 * sending this ancillary info.
4117 		 */
4118 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4119 	}
4120 
4121 	/*
4122 	 * If `ill' is in an IPMP group, use the IPMP ill to determine
4123 	 * IPF_RECVIF and IPF_RECVADDR.  (This currently assumes that
4124 	 * IPF_RECVADDR support on test addresses is not needed.)
4125 	 *
4126 	 * Note that `ill' may already be an IPMP ill if e.g. we're
4127 	 * processing a packet looped back to an IPMP data address
4128 	 * (since those IRE_LOCALs are tied to IPMP ills).
4129 	 */
4130 	if (IS_UNDER_IPMP(ill)) {
4131 		if ((ill = ipmp_ill_hold_ipmp_ill(ill)) == NULL) {
4132 			ip1dbg(("ip_add_info: cannot hold IPMP ill.\n"));
4133 			freemsg(mp);
4134 			return (data_mp);
4135 		}
4136 		ipmp_ill_held = B_TRUE;
4137 	}
4138 
4139 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4140 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4141 	if (flags & IPF_RECVADDR) {
4142 		ipif_t	*ipif;
4143 		ire_t	*ire;
4144 
4145 		/*
4146 		 * Only valid for V4
4147 		 */
4148 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4149 		    (IPV4_VERSION << 4));
4150 
4151 		ipif = ipif_get_next_ipif(NULL, ill);
4152 		if (ipif != NULL) {
4153 			/*
4154 			 * Since a decision has already been made to deliver the
4155 			 * packet, there is no need to test for SECATTR and
4156 			 * ZONEONLY.
4157 			 * When a multicast packet is transmitted
4158 			 * a cache entry is created for the multicast address.
4159 			 * When delivering a copy of the packet or when new
4160 			 * packets are received we do not want to match on the
4161 			 * cached entry so explicitly match on
4162 			 * IRE_LOCAL and IRE_LOOPBACK
4163 			 */
4164 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4165 			    IRE_LOCAL | IRE_LOOPBACK,
4166 			    ipif, zoneid, NULL,
4167 			    MATCH_IRE_TYPE | MATCH_IRE_ILL, ipst);
4168 			if (ire == NULL) {
4169 				/*
4170 				 * packet must have come on a different
4171 				 * interface.
4172 				 * Since a decision has already been made to
4173 				 * deliver the packet, there is no need to test
4174 				 * for SECATTR and ZONEONLY.
4175 				 * Only match on local and broadcast ire's.
4176 				 * See detailed comment above.
4177 				 */
4178 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4179 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4180 				    NULL, MATCH_IRE_TYPE, ipst);
4181 			}
4182 
4183 			if (ire == NULL) {
4184 				/*
4185 				 * This is either a multicast packet or
4186 				 * the address has been removed since
4187 				 * the packet was received.
4188 				 * Return INADDR_ANY so that normal source
4189 				 * selection occurs for the response.
4190 				 */
4191 
4192 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4193 			} else {
4194 				pinfo->ip_pkt_match_addr.s_addr =
4195 				    ire->ire_src_addr;
4196 				ire_refrele(ire);
4197 			}
4198 			ipif_refrele(ipif);
4199 		} else {
4200 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4201 		}
4202 	}
4203 
4204 	if (ipmp_ill_held)
4205 		ill_refrele(ill);
4206 
4207 	mp->b_datap->db_type = M_CTL;
4208 	mp->b_wptr += sizeof (ip_pktinfo_t);
4209 	mp->b_cont = data_mp;
4210 
4211 	return (mp);
4212 }
4213 
4214 /*
4215  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4216  * part of the bind request.
4217  */
4218 
4219 boolean_t
4220 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4221 {
4222 	ipsec_in_t *ii;
4223 
4224 	ASSERT(policy_mp != NULL);
4225 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4226 
4227 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4228 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4229 
4230 	connp->conn_policy = ii->ipsec_in_policy;
4231 	ii->ipsec_in_policy = NULL;
4232 
4233 	if (ii->ipsec_in_action != NULL) {
4234 		if (connp->conn_latch == NULL) {
4235 			connp->conn_latch = iplatch_create();
4236 			if (connp->conn_latch == NULL)
4237 				return (B_FALSE);
4238 		}
4239 		ipsec_latch_inbound(connp->conn_latch, ii);
4240 	}
4241 	return (B_TRUE);
4242 }
4243 
4244 static void
4245 ip_bind_post_handling(conn_t *connp, mblk_t *mp, boolean_t ire_requested)
4246 {
4247 	/*
4248 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4249 	 * We can't do this in ip_bind_get_ire because the policy
4250 	 * may not have been inherited at that point in time and hence
4251 	 * conn_out_enforce_policy may not be set.
4252 	 */
4253 	if (ire_requested && connp->conn_out_enforce_policy &&
4254 	    mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE) {
4255 		ire_t *ire = (ire_t *)mp->b_rptr;
4256 		ASSERT(MBLKL(mp) >= sizeof (ire_t));
4257 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4258 	}
4259 }
4260 
4261 /*
4262  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4263  * and to arrange for power-fanout assist.  The ULP is identified by
4264  * adding a single byte at the end of the original bind message.
4265  * A ULP other than UDP or TCP that wishes to be recognized passes
4266  * down a bind with a zero length address.
4267  *
4268  * The binding works as follows:
4269  * - A zero byte address means just bind to the protocol.
4270  * - A four byte address is treated as a request to validate
4271  *   that the address is a valid local address, appropriate for
4272  *   an application to bind to. This does not affect any fanout
4273  *   information in IP.
4274  * - A sizeof sin_t byte address is used to bind to only the local address
4275  *   and port.
4276  * - A sizeof ipa_conn_t byte address contains complete fanout information
4277  *   consisting of local and remote addresses and ports.  In
4278  *   this case, the addresses are both validated as appropriate
4279  *   for this operation, and, if so, the information is retained
4280  *   for use in the inbound fanout.
4281  *
4282  * The ULP (except in the zero-length bind) can append an
4283  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4284  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4285  * a copy of the source or destination IRE (source for local bind;
4286  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4287  * policy information contained should be copied on to the conn.
4288  *
4289  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4290  */
4291 mblk_t *
4292 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4293 {
4294 	ssize_t		len;
4295 	struct T_bind_req	*tbr;
4296 	sin_t		*sin;
4297 	ipa_conn_t	*ac;
4298 	uchar_t		*ucp;
4299 	mblk_t		*mp1;
4300 	boolean_t	ire_requested;
4301 	int		error = 0;
4302 	int		protocol;
4303 	ipa_conn_x_t	*acx;
4304 
4305 	ASSERT(!connp->conn_af_isv6);
4306 	connp->conn_pkt_isv6 = B_FALSE;
4307 
4308 	len = MBLKL(mp);
4309 	if (len < (sizeof (*tbr) + 1)) {
4310 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4311 		    "ip_bind: bogus msg, len %ld", len);
4312 		/* XXX: Need to return something better */
4313 		goto bad_addr;
4314 	}
4315 	/* Back up and extract the protocol identifier. */
4316 	mp->b_wptr--;
4317 	protocol = *mp->b_wptr & 0xFF;
4318 	tbr = (struct T_bind_req *)mp->b_rptr;
4319 	/* Reset the message type in preparation for shipping it back. */
4320 	DB_TYPE(mp) = M_PCPROTO;
4321 
4322 	connp->conn_ulp = (uint8_t)protocol;
4323 
4324 	/*
4325 	 * Check for a zero length address.  This is from a protocol that
4326 	 * wants to register to receive all packets of its type.
4327 	 */
4328 	if (tbr->ADDR_length == 0) {
4329 		/*
4330 		 * These protocols are now intercepted in ip_bind_v6().
4331 		 * Reject protocol-level binds here for now.
4332 		 *
4333 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4334 		 * so that the protocol type cannot be SCTP.
4335 		 */
4336 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4337 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4338 			goto bad_addr;
4339 		}
4340 
4341 		/*
4342 		 *
4343 		 * The udp module never sends down a zero-length address,
4344 		 * and allowing this on a labeled system will break MLP
4345 		 * functionality.
4346 		 */
4347 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4348 			goto bad_addr;
4349 
4350 		if (connp->conn_mac_exempt)
4351 			goto bad_addr;
4352 
4353 		/* No hash here really.  The table is big enough. */
4354 		connp->conn_srcv6 = ipv6_all_zeros;
4355 
4356 		ipcl_proto_insert(connp, protocol);
4357 
4358 		tbr->PRIM_type = T_BIND_ACK;
4359 		return (mp);
4360 	}
4361 
4362 	/* Extract the address pointer from the message. */
4363 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4364 	    tbr->ADDR_length);
4365 	if (ucp == NULL) {
4366 		ip1dbg(("ip_bind: no address\n"));
4367 		goto bad_addr;
4368 	}
4369 	if (!OK_32PTR(ucp)) {
4370 		ip1dbg(("ip_bind: unaligned address\n"));
4371 		goto bad_addr;
4372 	}
4373 	/*
4374 	 * Check for trailing mps.
4375 	 */
4376 
4377 	mp1 = mp->b_cont;
4378 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4379 
4380 	switch (tbr->ADDR_length) {
4381 	default:
4382 		ip1dbg(("ip_bind: bad address length %d\n",
4383 		    (int)tbr->ADDR_length));
4384 		goto bad_addr;
4385 
4386 	case IP_ADDR_LEN:
4387 		/* Verification of local address only */
4388 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4389 		    *(ipaddr_t *)ucp, 0, B_FALSE);
4390 		break;
4391 
4392 	case sizeof (sin_t):
4393 		sin = (sin_t *)ucp;
4394 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4395 		    sin->sin_addr.s_addr, sin->sin_port, B_TRUE);
4396 		break;
4397 
4398 	case sizeof (ipa_conn_t):
4399 		ac = (ipa_conn_t *)ucp;
4400 		/* For raw socket, the local port is not set. */
4401 		if (ac->ac_lport == 0)
4402 			ac->ac_lport = connp->conn_lport;
4403 		/* Always verify destination reachability. */
4404 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4405 		    &ac->ac_laddr, ac->ac_lport, ac->ac_faddr, ac->ac_fport,
4406 		    B_TRUE, B_TRUE);
4407 		break;
4408 
4409 	case sizeof (ipa_conn_x_t):
4410 		acx = (ipa_conn_x_t *)ucp;
4411 		/*
4412 		 * Whether or not to verify destination reachability depends
4413 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4414 		 */
4415 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4416 		    &acx->acx_conn.ac_laddr, acx->acx_conn.ac_lport,
4417 		    acx->acx_conn.ac_faddr, acx->acx_conn.ac_fport,
4418 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4419 		break;
4420 	}
4421 	ASSERT(error != EINPROGRESS);
4422 	if (error != 0)
4423 		goto bad_addr;
4424 
4425 	ip_bind_post_handling(connp, mp->b_cont, ire_requested);
4426 
4427 	/* Send it home. */
4428 	mp->b_datap->db_type = M_PCPROTO;
4429 	tbr->PRIM_type = T_BIND_ACK;
4430 	return (mp);
4431 
4432 bad_addr:
4433 	/*
4434 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4435 	 * a unix errno.
4436 	 */
4437 	if (error > 0)
4438 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4439 	else
4440 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4441 	return (mp);
4442 }
4443 
4444 /*
4445  * Here address is verified to be a valid local address.
4446  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4447  * address is also considered a valid local address.
4448  * In the case of a broadcast/multicast address, however, the
4449  * upper protocol is expected to reset the src address
4450  * to 0 if it sees a IRE_BROADCAST type returned so that
4451  * no packets are emitted with broadcast/multicast address as
4452  * source address (that violates hosts requirements RFC 1122)
4453  * The addresses valid for bind are:
4454  *	(1) - INADDR_ANY (0)
4455  *	(2) - IP address of an UP interface
4456  *	(3) - IP address of a DOWN interface
4457  *	(4) - valid local IP broadcast addresses. In this case
4458  *	the conn will only receive packets destined to
4459  *	the specified broadcast address.
4460  *	(5) - a multicast address. In this case
4461  *	the conn will only receive packets destined to
4462  *	the specified multicast address. Note: the
4463  *	application still has to issue an
4464  *	IP_ADD_MEMBERSHIP socket option.
4465  *
4466  * On error, return -1 for TBADADDR otherwise pass the
4467  * errno with TSYSERR reply.
4468  *
4469  * In all the above cases, the bound address must be valid in the current zone.
4470  * When the address is loopback, multicast or broadcast, there might be many
4471  * matching IREs so bind has to look up based on the zone.
4472  *
4473  * Note: lport is in network byte order.
4474  *
4475  */
4476 int
4477 ip_bind_laddr_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4478     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4479 {
4480 	int		error = 0;
4481 	ire_t		*src_ire;
4482 	zoneid_t	zoneid;
4483 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4484 	mblk_t		*mp = NULL;
4485 	boolean_t	ire_requested = B_FALSE;
4486 	boolean_t	ipsec_policy_set = B_FALSE;
4487 
4488 	if (mpp)
4489 		mp = *mpp;
4490 
4491 	if (mp != NULL) {
4492 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4493 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4494 	}
4495 
4496 	/*
4497 	 * If it was previously connected, conn_fully_bound would have
4498 	 * been set.
4499 	 */
4500 	connp->conn_fully_bound = B_FALSE;
4501 
4502 	src_ire = NULL;
4503 
4504 	zoneid = IPCL_ZONEID(connp);
4505 
4506 	if (src_addr) {
4507 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4508 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4509 		/*
4510 		 * If an address other than 0.0.0.0 is requested,
4511 		 * we verify that it is a valid address for bind
4512 		 * Note: Following code is in if-else-if form for
4513 		 * readability compared to a condition check.
4514 		 */
4515 		/* LINTED - statement has no consequence */
4516 		if (IRE_IS_LOCAL(src_ire)) {
4517 			/*
4518 			 * (2) Bind to address of local UP interface
4519 			 */
4520 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4521 			/*
4522 			 * (4) Bind to broadcast address
4523 			 * Note: permitted only from transports that
4524 			 * request IRE
4525 			 */
4526 			if (!ire_requested)
4527 				error = EADDRNOTAVAIL;
4528 		} else {
4529 			/*
4530 			 * (3) Bind to address of local DOWN interface
4531 			 * (ipif_lookup_addr() looks up all interfaces
4532 			 * but we do not get here for UP interfaces
4533 			 * - case (2) above)
4534 			 */
4535 			/* LINTED - statement has no consequent */
4536 			if (ip_addr_exists(src_addr, zoneid, ipst)) {
4537 				/* The address exists */
4538 			} else if (CLASSD(src_addr)) {
4539 				error = 0;
4540 				if (src_ire != NULL)
4541 					ire_refrele(src_ire);
4542 				/*
4543 				 * (5) bind to multicast address.
4544 				 * Fake out the IRE returned to upper
4545 				 * layer to be a broadcast IRE.
4546 				 */
4547 				src_ire = ire_ctable_lookup(
4548 				    INADDR_BROADCAST, INADDR_ANY,
4549 				    IRE_BROADCAST, NULL, zoneid, NULL,
4550 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4551 				    ipst);
4552 				if (src_ire == NULL || !ire_requested)
4553 					error = EADDRNOTAVAIL;
4554 			} else {
4555 				/*
4556 				 * Not a valid address for bind
4557 				 */
4558 				error = EADDRNOTAVAIL;
4559 			}
4560 		}
4561 		if (error) {
4562 			/* Red Alert!  Attempting to be a bogon! */
4563 			ip1dbg(("ip_bind_laddr_v4: bad src address 0x%x\n",
4564 			    ntohl(src_addr)));
4565 			goto bad_addr;
4566 		}
4567 	}
4568 
4569 	/*
4570 	 * Allow setting new policies. For example, disconnects come
4571 	 * down as ipa_t bind. As we would have set conn_policy_cached
4572 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4573 	 * can change after the disconnect.
4574 	 */
4575 	connp->conn_policy_cached = B_FALSE;
4576 
4577 	/*
4578 	 * If not fanout_insert this was just an address verification
4579 	 */
4580 	if (fanout_insert) {
4581 		/*
4582 		 * The addresses have been verified. Time to insert in
4583 		 * the correct fanout list.
4584 		 */
4585 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4586 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4587 		connp->conn_lport = lport;
4588 		connp->conn_fport = 0;
4589 		/*
4590 		 * Do we need to add a check to reject Multicast packets
4591 		 */
4592 		error = ipcl_bind_insert(connp, protocol, src_addr, lport);
4593 	}
4594 
4595 	if (error == 0) {
4596 		if (ire_requested) {
4597 			if (!ip_bind_get_ire_v4(mpp, src_ire, NULL, ipst)) {
4598 				error = -1;
4599 				/* Falls through to bad_addr */
4600 			}
4601 		} else if (ipsec_policy_set) {
4602 			if (!ip_bind_ipsec_policy_set(connp, mp)) {
4603 				error = -1;
4604 				/* Falls through to bad_addr */
4605 			}
4606 		}
4607 	}
4608 bad_addr:
4609 	if (error != 0) {
4610 		if (connp->conn_anon_port) {
4611 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4612 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4613 			    B_FALSE);
4614 		}
4615 		connp->conn_mlp_type = mlptSingle;
4616 	}
4617 	if (src_ire != NULL)
4618 		IRE_REFRELE(src_ire);
4619 	return (error);
4620 }
4621 
4622 int
4623 ip_proto_bind_laddr_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
4624     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4625 {
4626 	int error;
4627 	mblk_t	*mp = NULL;
4628 	boolean_t ire_requested;
4629 
4630 	if (ire_mpp)
4631 		mp = *ire_mpp;
4632 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4633 
4634 	ASSERT(!connp->conn_af_isv6);
4635 	connp->conn_pkt_isv6 = B_FALSE;
4636 	connp->conn_ulp = protocol;
4637 
4638 	error = ip_bind_laddr_v4(connp, ire_mpp, protocol, src_addr, lport,
4639 	    fanout_insert);
4640 	if (error == 0) {
4641 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
4642 		    ire_requested);
4643 	} else if (error < 0) {
4644 		error = -TBADADDR;
4645 	}
4646 	return (error);
4647 }
4648 
4649 /*
4650  * Verify that both the source and destination addresses
4651  * are valid.  If verify_dst is false, then the destination address may be
4652  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4653  * destination reachability, while tunnels do not.
4654  * Note that we allow connect to broadcast and multicast
4655  * addresses when ire_requested is set. Thus the ULP
4656  * has to check for IRE_BROADCAST and multicast.
4657  *
4658  * Returns zero if ok.
4659  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4660  * (for use with TSYSERR reply).
4661  *
4662  * Note: lport and fport are in network byte order.
4663  */
4664 int
4665 ip_bind_connected_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4666     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4667     boolean_t fanout_insert, boolean_t verify_dst)
4668 {
4669 
4670 	ire_t		*src_ire;
4671 	ire_t		*dst_ire;
4672 	int		error = 0;
4673 	ire_t		*sire = NULL;
4674 	ire_t		*md_dst_ire = NULL;
4675 	ire_t		*lso_dst_ire = NULL;
4676 	ill_t		*ill = NULL;
4677 	zoneid_t	zoneid;
4678 	ipaddr_t	src_addr = *src_addrp;
4679 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4680 	mblk_t		*mp = NULL;
4681 	boolean_t	ire_requested = B_FALSE;
4682 	boolean_t	ipsec_policy_set = B_FALSE;
4683 	ts_label_t	*tsl = NULL;
4684 
4685 	if (mpp)
4686 		mp = *mpp;
4687 
4688 	if (mp != NULL) {
4689 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4690 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4691 		tsl = MBLK_GETLABEL(mp);
4692 	}
4693 
4694 	src_ire = dst_ire = NULL;
4695 
4696 	/*
4697 	 * If we never got a disconnect before, clear it now.
4698 	 */
4699 	connp->conn_fully_bound = B_FALSE;
4700 
4701 	zoneid = IPCL_ZONEID(connp);
4702 
4703 	if (CLASSD(dst_addr)) {
4704 		/* Pick up an IRE_BROADCAST */
4705 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4706 		    NULL, zoneid, tsl,
4707 		    (MATCH_IRE_RECURSIVE |
4708 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4709 		    MATCH_IRE_SECATTR), ipst);
4710 	} else {
4711 		/*
4712 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4713 		 * and onlink ipif is not found set ENETUNREACH error.
4714 		 */
4715 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4716 			ipif_t *ipif;
4717 
4718 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4719 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4720 			if (ipif == NULL) {
4721 				error = ENETUNREACH;
4722 				goto bad_addr;
4723 			}
4724 			ipif_refrele(ipif);
4725 		}
4726 
4727 		if (connp->conn_nexthop_set) {
4728 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4729 			    0, 0, NULL, NULL, zoneid, tsl,
4730 			    MATCH_IRE_SECATTR, ipst);
4731 		} else {
4732 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4733 			    &sire, zoneid, tsl,
4734 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4735 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4736 			    MATCH_IRE_SECATTR), ipst);
4737 		}
4738 	}
4739 	/*
4740 	 * dst_ire can't be a broadcast when not ire_requested.
4741 	 * We also prevent ire's with src address INADDR_ANY to
4742 	 * be used, which are created temporarily for
4743 	 * sending out packets from endpoints that have
4744 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4745 	 * reachable.  If verify_dst is false, the destination needn't be
4746 	 * reachable.
4747 	 *
4748 	 * If we match on a reject or black hole, then we've got a
4749 	 * local failure.  May as well fail out the connect() attempt,
4750 	 * since it's never going to succeed.
4751 	 */
4752 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4753 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4754 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4755 		/*
4756 		 * If we're verifying destination reachability, we always want
4757 		 * to complain here.
4758 		 *
4759 		 * If we're not verifying destination reachability but the
4760 		 * destination has a route, we still want to fail on the
4761 		 * temporary address and broadcast address tests.
4762 		 */
4763 		if (verify_dst || (dst_ire != NULL)) {
4764 			if (ip_debug > 2) {
4765 				pr_addr_dbg("ip_bind_connected_v4:"
4766 				    "bad connected dst %s\n",
4767 				    AF_INET, &dst_addr);
4768 			}
4769 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4770 				error = ENETUNREACH;
4771 			else
4772 				error = EHOSTUNREACH;
4773 			goto bad_addr;
4774 		}
4775 	}
4776 
4777 	/*
4778 	 * We now know that routing will allow us to reach the destination.
4779 	 * Check whether Trusted Solaris policy allows communication with this
4780 	 * host, and pretend that the destination is unreachable if not.
4781 	 *
4782 	 * This is never a problem for TCP, since that transport is known to
4783 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4784 	 * handling.  If the remote is unreachable, it will be detected at that
4785 	 * point, so there's no reason to check it here.
4786 	 *
4787 	 * Note that for sendto (and other datagram-oriented friends), this
4788 	 * check is done as part of the data path label computation instead.
4789 	 * The check here is just to make non-TCP connect() report the right
4790 	 * error.
4791 	 */
4792 	if (dst_ire != NULL && is_system_labeled() &&
4793 	    !IPCL_IS_TCP(connp) &&
4794 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4795 	    connp->conn_mac_exempt, ipst) != 0) {
4796 		error = EHOSTUNREACH;
4797 		if (ip_debug > 2) {
4798 			pr_addr_dbg("ip_bind_connected_v4:"
4799 			    " no label for dst %s\n",
4800 			    AF_INET, &dst_addr);
4801 		}
4802 		goto bad_addr;
4803 	}
4804 
4805 	/*
4806 	 * If the app does a connect(), it means that it will most likely
4807 	 * send more than 1 packet to the destination.  It makes sense
4808 	 * to clear the temporary flag.
4809 	 */
4810 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4811 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4812 		irb_t *irb = dst_ire->ire_bucket;
4813 
4814 		rw_enter(&irb->irb_lock, RW_WRITER);
4815 		/*
4816 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4817 		 * the lock to guarantee irb_tmp_ire_cnt.
4818 		 */
4819 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4820 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4821 			irb->irb_tmp_ire_cnt--;
4822 		}
4823 		rw_exit(&irb->irb_lock);
4824 	}
4825 
4826 	/*
4827 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4828 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4829 	 * eligibility tests for passive connects are handled separately
4830 	 * through tcp_adapt_ire().  We do this before the source address
4831 	 * selection, because dst_ire may change after a call to
4832 	 * ipif_select_source().  This is a best-effort check, as the
4833 	 * packet for this connection may not actually go through
4834 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4835 	 * calling ip_newroute().  This is why we further check on the
4836 	 * IRE during LSO/Multidata packet transmission in
4837 	 * tcp_lsosend()/tcp_multisend().
4838 	 */
4839 	if (!ipsec_policy_set && dst_ire != NULL &&
4840 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4841 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4842 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4843 			lso_dst_ire = dst_ire;
4844 			IRE_REFHOLD(lso_dst_ire);
4845 		} else if (ipst->ips_ip_multidata_outbound &&
4846 		    ILL_MDT_CAPABLE(ill)) {
4847 			md_dst_ire = dst_ire;
4848 			IRE_REFHOLD(md_dst_ire);
4849 		}
4850 	}
4851 
4852 	if (dst_ire != NULL && dst_ire->ire_type == IRE_LOCAL &&
4853 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4854 		/*
4855 		 * If the IRE belongs to a different zone, look for a matching
4856 		 * route in the forwarding table and use the source address from
4857 		 * that route.
4858 		 */
4859 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4860 		    zoneid, 0, NULL,
4861 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4862 		    MATCH_IRE_RJ_BHOLE, ipst);
4863 		if (src_ire == NULL) {
4864 			error = EHOSTUNREACH;
4865 			goto bad_addr;
4866 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4867 			if (!(src_ire->ire_type & IRE_HOST))
4868 				error = ENETUNREACH;
4869 			else
4870 				error = EHOSTUNREACH;
4871 			goto bad_addr;
4872 		}
4873 		if (src_addr == INADDR_ANY)
4874 			src_addr = src_ire->ire_src_addr;
4875 		ire_refrele(src_ire);
4876 		src_ire = NULL;
4877 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4878 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4879 			src_addr = sire->ire_src_addr;
4880 			ire_refrele(dst_ire);
4881 			dst_ire = sire;
4882 			sire = NULL;
4883 		} else {
4884 			/*
4885 			 * Pick a source address so that a proper inbound
4886 			 * load spreading would happen.
4887 			 */
4888 			ill_t *ire_ill = dst_ire->ire_ipif->ipif_ill;
4889 			ipif_t *src_ipif = NULL;
4890 			ire_t *ipif_ire;
4891 
4892 			/*
4893 			 * Supply a local source address such that inbound
4894 			 * load spreading happens.
4895 			 *
4896 			 * Determine the best source address on this ill for
4897 			 * the destination.
4898 			 *
4899 			 * 1) For broadcast, we should return a broadcast ire
4900 			 *    found above so that upper layers know that the
4901 			 *    destination address is a broadcast address.
4902 			 *
4903 			 * 2) If the ipif is DEPRECATED, select a better
4904 			 *    source address.  Similarly, if the ipif is on
4905 			 *    the IPMP meta-interface, pick a source address
4906 			 *    at random to improve inbound load spreading.
4907 			 *
4908 			 * 3) If the outgoing interface is part of a usesrc
4909 			 *    group, then try selecting a source address from
4910 			 *    the usesrc ILL.
4911 			 */
4912 			if ((dst_ire->ire_zoneid != zoneid &&
4913 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4914 			    (!(dst_ire->ire_flags & RTF_SETSRC)) &&
4915 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4916 			    (IS_IPMP(ire_ill) ||
4917 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4918 			    (ire_ill->ill_usesrc_ifindex != 0)))) {
4919 				/*
4920 				 * If the destination is reachable via a
4921 				 * given gateway, the selected source address
4922 				 * should be in the same subnet as the gateway.
4923 				 * Otherwise, the destination is not reachable.
4924 				 *
4925 				 * If there are no interfaces on the same subnet
4926 				 * as the destination, ipif_select_source gives
4927 				 * first non-deprecated interface which might be
4928 				 * on a different subnet than the gateway.
4929 				 * This is not desirable. Hence pass the dst_ire
4930 				 * source address to ipif_select_source.
4931 				 * It is sure that the destination is reachable
4932 				 * with the dst_ire source address subnet.
4933 				 * So passing dst_ire source address to
4934 				 * ipif_select_source will make sure that the
4935 				 * selected source will be on the same subnet
4936 				 * as dst_ire source address.
4937 				 */
4938 				ipaddr_t saddr =
4939 				    dst_ire->ire_ipif->ipif_src_addr;
4940 				src_ipif = ipif_select_source(ire_ill,
4941 				    saddr, zoneid);
4942 				if (src_ipif != NULL) {
4943 					if (IS_VNI(src_ipif->ipif_ill)) {
4944 						/*
4945 						 * For VNI there is no
4946 						 * interface route
4947 						 */
4948 						src_addr =
4949 						    src_ipif->ipif_src_addr;
4950 					} else {
4951 						ipif_ire =
4952 						    ipif_to_ire(src_ipif);
4953 						if (ipif_ire != NULL) {
4954 							IRE_REFRELE(dst_ire);
4955 							dst_ire = ipif_ire;
4956 						}
4957 						src_addr =
4958 						    dst_ire->ire_src_addr;
4959 					}
4960 					ipif_refrele(src_ipif);
4961 				} else {
4962 					src_addr = dst_ire->ire_src_addr;
4963 				}
4964 			} else {
4965 				src_addr = dst_ire->ire_src_addr;
4966 			}
4967 		}
4968 	}
4969 
4970 	/*
4971 	 * We do ire_route_lookup() here (and not
4972 	 * interface lookup as we assert that
4973 	 * src_addr should only come from an
4974 	 * UP interface for hard binding.
4975 	 */
4976 	ASSERT(src_ire == NULL);
4977 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
4978 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4979 	/* src_ire must be a local|loopback */
4980 	if (!IRE_IS_LOCAL(src_ire)) {
4981 		if (ip_debug > 2) {
4982 			pr_addr_dbg("ip_bind_connected_v4: bad connected "
4983 			    "src %s\n", AF_INET, &src_addr);
4984 		}
4985 		error = EADDRNOTAVAIL;
4986 		goto bad_addr;
4987 	}
4988 
4989 	/*
4990 	 * If the source address is a loopback address, the
4991 	 * destination had best be local or multicast.
4992 	 * The transports that can't handle multicast will reject
4993 	 * those addresses.
4994 	 */
4995 	if (src_ire->ire_type == IRE_LOOPBACK &&
4996 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
4997 		ip1dbg(("ip_bind_connected_v4: bad connected loopback\n"));
4998 		error = -1;
4999 		goto bad_addr;
5000 	}
5001 
5002 	/*
5003 	 * Allow setting new policies. For example, disconnects come
5004 	 * down as ipa_t bind. As we would have set conn_policy_cached
5005 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5006 	 * can change after the disconnect.
5007 	 */
5008 	connp->conn_policy_cached = B_FALSE;
5009 
5010 	/*
5011 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5012 	 * can handle their passed-in conn's.
5013 	 */
5014 
5015 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5016 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5017 	connp->conn_lport = lport;
5018 	connp->conn_fport = fport;
5019 	*src_addrp = src_addr;
5020 
5021 	ASSERT(!(ipsec_policy_set && ire_requested));
5022 	if (ire_requested) {
5023 		iulp_t *ulp_info = NULL;
5024 
5025 		/*
5026 		 * Note that sire will not be NULL if this is an off-link
5027 		 * connection and there is not cache for that dest yet.
5028 		 *
5029 		 * XXX Because of an existing bug, if there are multiple
5030 		 * default routes, the IRE returned now may not be the actual
5031 		 * default route used (default routes are chosen in a
5032 		 * round robin fashion).  So if the metrics for different
5033 		 * default routes are different, we may return the wrong
5034 		 * metrics.  This will not be a problem if the existing
5035 		 * bug is fixed.
5036 		 */
5037 		if (sire != NULL) {
5038 			ulp_info = &(sire->ire_uinfo);
5039 		}
5040 		if (!ip_bind_get_ire_v4(mpp, dst_ire, ulp_info, ipst)) {
5041 			error = -1;
5042 			goto bad_addr;
5043 		}
5044 		mp = *mpp;
5045 	} else if (ipsec_policy_set) {
5046 		if (!ip_bind_ipsec_policy_set(connp, mp)) {
5047 			error = -1;
5048 			goto bad_addr;
5049 		}
5050 	}
5051 
5052 	/*
5053 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5054 	 * we'll cache that.  If we don't, we'll inherit global policy.
5055 	 *
5056 	 * We can't insert until the conn reflects the policy. Note that
5057 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5058 	 * connections where we don't have a policy. This is to prevent
5059 	 * global policy lookups in the inbound path.
5060 	 *
5061 	 * If we insert before we set conn_policy_cached,
5062 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5063 	 * because global policy cound be non-empty. We normally call
5064 	 * ipsec_check_policy() for conn_policy_cached connections only if
5065 	 * ipc_in_enforce_policy is set. But in this case,
5066 	 * conn_policy_cached can get set anytime since we made the
5067 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5068 	 * called, which will make the above assumption false.  Thus, we
5069 	 * need to insert after we set conn_policy_cached.
5070 	 */
5071 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5072 		goto bad_addr;
5073 
5074 	if (fanout_insert) {
5075 		/*
5076 		 * The addresses have been verified. Time to insert in
5077 		 * the correct fanout list.
5078 		 */
5079 		error = ipcl_conn_insert(connp, protocol, src_addr,
5080 		    dst_addr, connp->conn_ports);
5081 	}
5082 
5083 	if (error == 0) {
5084 		connp->conn_fully_bound = B_TRUE;
5085 		/*
5086 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5087 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5088 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5089 		 * ip_xxinfo_return(), which performs further checks
5090 		 * against them and upon success, returns the LSO/MDT info
5091 		 * mblk which we will attach to the bind acknowledgment.
5092 		 */
5093 		if (lso_dst_ire != NULL) {
5094 			mblk_t *lsoinfo_mp;
5095 
5096 			ASSERT(ill->ill_lso_capab != NULL);
5097 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5098 			    ill->ill_name, ill->ill_lso_capab)) != NULL) {
5099 				if (mp == NULL) {
5100 					*mpp = lsoinfo_mp;
5101 				} else {
5102 					linkb(mp, lsoinfo_mp);
5103 				}
5104 			}
5105 		} else if (md_dst_ire != NULL) {
5106 			mblk_t *mdinfo_mp;
5107 
5108 			ASSERT(ill->ill_mdt_capab != NULL);
5109 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5110 			    ill->ill_name, ill->ill_mdt_capab)) != NULL) {
5111 				if (mp == NULL) {
5112 					*mpp = mdinfo_mp;
5113 				} else {
5114 					linkb(mp, mdinfo_mp);
5115 				}
5116 			}
5117 		}
5118 	}
5119 bad_addr:
5120 	if (ipsec_policy_set) {
5121 		ASSERT(mp != NULL);
5122 		freeb(mp);
5123 		/*
5124 		 * As of now assume that nothing else accompanies
5125 		 * IPSEC_POLICY_SET.
5126 		 */
5127 		*mpp = NULL;
5128 	}
5129 	if (src_ire != NULL)
5130 		IRE_REFRELE(src_ire);
5131 	if (dst_ire != NULL)
5132 		IRE_REFRELE(dst_ire);
5133 	if (sire != NULL)
5134 		IRE_REFRELE(sire);
5135 	if (md_dst_ire != NULL)
5136 		IRE_REFRELE(md_dst_ire);
5137 	if (lso_dst_ire != NULL)
5138 		IRE_REFRELE(lso_dst_ire);
5139 	return (error);
5140 }
5141 
5142 int
5143 ip_proto_bind_connected_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
5144     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
5145     boolean_t fanout_insert, boolean_t verify_dst)
5146 {
5147 	int error;
5148 	mblk_t	*mp = NULL;
5149 	boolean_t ire_requested;
5150 
5151 	if (ire_mpp)
5152 		mp = *ire_mpp;
5153 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
5154 
5155 	ASSERT(!connp->conn_af_isv6);
5156 	connp->conn_pkt_isv6 = B_FALSE;
5157 	connp->conn_ulp = protocol;
5158 
5159 	/* For raw socket, the local port is not set. */
5160 	if (lport == 0)
5161 		lport = connp->conn_lport;
5162 	error = ip_bind_connected_v4(connp, ire_mpp, protocol,
5163 	    src_addrp, lport, dst_addr, fport, fanout_insert, verify_dst);
5164 	if (error == 0) {
5165 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
5166 		    ire_requested);
5167 	} else if (error < 0) {
5168 		error = -TBADADDR;
5169 	}
5170 	return (error);
5171 }
5172 
5173 /*
5174  * Get the ire in *mpp. Returns false if it fails (due to lack of space).
5175  * Prefers dst_ire over src_ire.
5176  */
5177 static boolean_t
5178 ip_bind_get_ire_v4(mblk_t **mpp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5179 {
5180 	mblk_t	*mp = *mpp;
5181 	ire_t	*ret_ire;
5182 
5183 	ASSERT(mp != NULL);
5184 
5185 	if (ire != NULL) {
5186 		/*
5187 		 * mp initialized above to IRE_DB_REQ_TYPE
5188 		 * appended mblk. Its <upper protocol>'s
5189 		 * job to make sure there is room.
5190 		 */
5191 		if ((mp->b_datap->db_lim - mp->b_rptr) < sizeof (ire_t))
5192 			return (B_FALSE);
5193 
5194 		mp->b_datap->db_type = IRE_DB_TYPE;
5195 		mp->b_wptr = mp->b_rptr + sizeof (ire_t);
5196 		bcopy(ire, mp->b_rptr, sizeof (ire_t));
5197 		ret_ire = (ire_t *)mp->b_rptr;
5198 		/*
5199 		 * Pass the latest setting of the ip_path_mtu_discovery and
5200 		 * copy the ulp info if any.
5201 		 */
5202 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5203 		    IPH_DF : 0;
5204 		if (ulp_info != NULL) {
5205 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5206 			    sizeof (iulp_t));
5207 		}
5208 		ret_ire->ire_mp = mp;
5209 	} else {
5210 		/*
5211 		 * No IRE was found. Remove IRE mblk.
5212 		 */
5213 		*mpp = mp->b_cont;
5214 		freeb(mp);
5215 	}
5216 	return (B_TRUE);
5217 }
5218 
5219 /*
5220  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5221  * the final piece where we don't.  Return a pointer to the first mblk in the
5222  * result, and update the pointer to the next mblk to chew on.  If anything
5223  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5224  * NULL pointer.
5225  */
5226 mblk_t *
5227 ip_carve_mp(mblk_t **mpp, ssize_t len)
5228 {
5229 	mblk_t	*mp0;
5230 	mblk_t	*mp1;
5231 	mblk_t	*mp2;
5232 
5233 	if (!len || !mpp || !(mp0 = *mpp))
5234 		return (NULL);
5235 	/* If we aren't going to consume the first mblk, we need a dup. */
5236 	if (mp0->b_wptr - mp0->b_rptr > len) {
5237 		mp1 = dupb(mp0);
5238 		if (mp1) {
5239 			/* Partition the data between the two mblks. */
5240 			mp1->b_wptr = mp1->b_rptr + len;
5241 			mp0->b_rptr = mp1->b_wptr;
5242 			/*
5243 			 * after adjustments if mblk not consumed is now
5244 			 * unaligned, try to align it. If this fails free
5245 			 * all messages and let upper layer recover.
5246 			 */
5247 			if (!OK_32PTR(mp0->b_rptr)) {
5248 				if (!pullupmsg(mp0, -1)) {
5249 					freemsg(mp0);
5250 					freemsg(mp1);
5251 					*mpp = NULL;
5252 					return (NULL);
5253 				}
5254 			}
5255 		}
5256 		return (mp1);
5257 	}
5258 	/* Eat through as many mblks as we need to get len bytes. */
5259 	len -= mp0->b_wptr - mp0->b_rptr;
5260 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5261 		if (mp2->b_wptr - mp2->b_rptr > len) {
5262 			/*
5263 			 * We won't consume the entire last mblk.  Like
5264 			 * above, dup and partition it.
5265 			 */
5266 			mp1->b_cont = dupb(mp2);
5267 			mp1 = mp1->b_cont;
5268 			if (!mp1) {
5269 				/*
5270 				 * Trouble.  Rather than go to a lot of
5271 				 * trouble to clean up, we free the messages.
5272 				 * This won't be any worse than losing it on
5273 				 * the wire.
5274 				 */
5275 				freemsg(mp0);
5276 				freemsg(mp2);
5277 				*mpp = NULL;
5278 				return (NULL);
5279 			}
5280 			mp1->b_wptr = mp1->b_rptr + len;
5281 			mp2->b_rptr = mp1->b_wptr;
5282 			/*
5283 			 * after adjustments if mblk not consumed is now
5284 			 * unaligned, try to align it. If this fails free
5285 			 * all messages and let upper layer recover.
5286 			 */
5287 			if (!OK_32PTR(mp2->b_rptr)) {
5288 				if (!pullupmsg(mp2, -1)) {
5289 					freemsg(mp0);
5290 					freemsg(mp2);
5291 					*mpp = NULL;
5292 					return (NULL);
5293 				}
5294 			}
5295 			*mpp = mp2;
5296 			return (mp0);
5297 		}
5298 		/* Decrement len by the amount we just got. */
5299 		len -= mp2->b_wptr - mp2->b_rptr;
5300 	}
5301 	/*
5302 	 * len should be reduced to zero now.  If not our caller has
5303 	 * screwed up.
5304 	 */
5305 	if (len) {
5306 		/* Shouldn't happen! */
5307 		freemsg(mp0);
5308 		*mpp = NULL;
5309 		return (NULL);
5310 	}
5311 	/*
5312 	 * We consumed up to exactly the end of an mblk.  Detach the part
5313 	 * we are returning from the rest of the chain.
5314 	 */
5315 	mp1->b_cont = NULL;
5316 	*mpp = mp2;
5317 	return (mp0);
5318 }
5319 
5320 /* The ill stream is being unplumbed. Called from ip_close */
5321 int
5322 ip_modclose(ill_t *ill)
5323 {
5324 	boolean_t success;
5325 	ipsq_t	*ipsq;
5326 	ipif_t	*ipif;
5327 	queue_t	*q = ill->ill_rq;
5328 	ip_stack_t	*ipst = ill->ill_ipst;
5329 
5330 	/*
5331 	 * The punlink prior to this may have initiated a capability
5332 	 * negotiation. But ipsq_enter will block until that finishes or
5333 	 * times out.
5334 	 */
5335 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
5336 
5337 	/*
5338 	 * Open/close/push/pop is guaranteed to be single threaded
5339 	 * per stream by STREAMS. FS guarantees that all references
5340 	 * from top are gone before close is called. So there can't
5341 	 * be another close thread that has set CONDEMNED on this ill.
5342 	 * and cause ipsq_enter to return failure.
5343 	 */
5344 	ASSERT(success);
5345 	ipsq = ill->ill_phyint->phyint_ipsq;
5346 
5347 	/*
5348 	 * Mark it condemned. No new reference will be made to this ill.
5349 	 * Lookup functions will return an error. Threads that try to
5350 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5351 	 * that the refcnt will drop down to zero.
5352 	 */
5353 	mutex_enter(&ill->ill_lock);
5354 	ill->ill_state_flags |= ILL_CONDEMNED;
5355 	for (ipif = ill->ill_ipif; ipif != NULL;
5356 	    ipif = ipif->ipif_next) {
5357 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5358 	}
5359 	/*
5360 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5361 	 * returns  error if ILL_CONDEMNED is set
5362 	 */
5363 	cv_broadcast(&ill->ill_cv);
5364 	mutex_exit(&ill->ill_lock);
5365 
5366 	/*
5367 	 * Send all the deferred DLPI messages downstream which came in
5368 	 * during the small window right before ipsq_enter(). We do this
5369 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5370 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5371 	 */
5372 	ill_dlpi_send_deferred(ill);
5373 
5374 	/*
5375 	 * Shut down fragmentation reassembly.
5376 	 * ill_frag_timer won't start a timer again.
5377 	 * Now cancel any existing timer
5378 	 */
5379 	(void) untimeout(ill->ill_frag_timer_id);
5380 	(void) ill_frag_timeout(ill, 0);
5381 
5382 	/*
5383 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5384 	 * this ill. Then wait for the refcnts to drop to zero.
5385 	 * ill_is_freeable checks whether the ill is really quiescent.
5386 	 * Then make sure that threads that are waiting to enter the
5387 	 * ipsq have seen the error returned by ipsq_enter and have
5388 	 * gone away. Then we call ill_delete_tail which does the
5389 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5390 	 */
5391 	ill_delete(ill);
5392 	mutex_enter(&ill->ill_lock);
5393 	while (!ill_is_freeable(ill))
5394 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5395 	while (ill->ill_waiters)
5396 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5397 
5398 	mutex_exit(&ill->ill_lock);
5399 
5400 	/*
5401 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5402 	 * it held until the end of the function since the cleanup
5403 	 * below needs to be able to use the ip_stack_t.
5404 	 */
5405 	netstack_hold(ipst->ips_netstack);
5406 
5407 	/* qprocsoff is done via ill_delete_tail */
5408 	ill_delete_tail(ill);
5409 	ASSERT(ill->ill_ipst == NULL);
5410 
5411 	/*
5412 	 * Walk through all upper (conn) streams and qenable
5413 	 * those that have queued data.
5414 	 * close synchronization needs this to
5415 	 * be done to ensure that all upper layers blocked
5416 	 * due to flow control to the closing device
5417 	 * get unblocked.
5418 	 */
5419 	ip1dbg(("ip_wsrv: walking\n"));
5420 	conn_walk_drain(ipst);
5421 
5422 	mutex_enter(&ipst->ips_ip_mi_lock);
5423 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5424 	mutex_exit(&ipst->ips_ip_mi_lock);
5425 
5426 	/*
5427 	 * credp could be null if the open didn't succeed and ip_modopen
5428 	 * itself calls ip_close.
5429 	 */
5430 	if (ill->ill_credp != NULL)
5431 		crfree(ill->ill_credp);
5432 
5433 	/*
5434 	 * Now we are done with the module close pieces that
5435 	 * need the netstack_t.
5436 	 */
5437 	netstack_rele(ipst->ips_netstack);
5438 
5439 	mi_close_free((IDP)ill);
5440 	q->q_ptr = WR(q)->q_ptr = NULL;
5441 
5442 	ipsq_exit(ipsq);
5443 
5444 	return (0);
5445 }
5446 
5447 /*
5448  * This is called as part of close() for IP, UDP, ICMP, and RTS
5449  * in order to quiesce the conn.
5450  */
5451 void
5452 ip_quiesce_conn(conn_t *connp)
5453 {
5454 	boolean_t	drain_cleanup_reqd = B_FALSE;
5455 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5456 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5457 	ip_stack_t	*ipst;
5458 
5459 	ASSERT(!IPCL_IS_TCP(connp));
5460 	ipst = connp->conn_netstack->netstack_ip;
5461 
5462 	/*
5463 	 * Mark the conn as closing, and this conn must not be
5464 	 * inserted in future into any list. Eg. conn_drain_insert(),
5465 	 * won't insert this conn into the conn_drain_list.
5466 	 * Similarly ill_pending_mp_add() will not add any mp to
5467 	 * the pending mp list, after this conn has started closing.
5468 	 *
5469 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5470 	 * cannot get set henceforth.
5471 	 */
5472 	mutex_enter(&connp->conn_lock);
5473 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5474 	connp->conn_state_flags |= CONN_CLOSING;
5475 	if (connp->conn_idl != NULL)
5476 		drain_cleanup_reqd = B_TRUE;
5477 	if (connp->conn_oper_pending_ill != NULL)
5478 		conn_ioctl_cleanup_reqd = B_TRUE;
5479 	if (connp->conn_dhcpinit_ill != NULL) {
5480 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5481 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5482 		connp->conn_dhcpinit_ill = NULL;
5483 	}
5484 	if (connp->conn_ilg_inuse != 0)
5485 		ilg_cleanup_reqd = B_TRUE;
5486 	mutex_exit(&connp->conn_lock);
5487 
5488 	if (conn_ioctl_cleanup_reqd)
5489 		conn_ioctl_cleanup(connp);
5490 
5491 	if (is_system_labeled() && connp->conn_anon_port) {
5492 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5493 		    connp->conn_mlp_type, connp->conn_ulp,
5494 		    ntohs(connp->conn_lport), B_FALSE);
5495 		connp->conn_anon_port = 0;
5496 	}
5497 	connp->conn_mlp_type = mlptSingle;
5498 
5499 	/*
5500 	 * Remove this conn from any fanout list it is on.
5501 	 * and then wait for any threads currently operating
5502 	 * on this endpoint to finish
5503 	 */
5504 	ipcl_hash_remove(connp);
5505 
5506 	/*
5507 	 * Remove this conn from the drain list, and do
5508 	 * any other cleanup that may be required.
5509 	 * (Only non-tcp streams may have a non-null conn_idl.
5510 	 * TCP streams are never flow controlled, and
5511 	 * conn_idl will be null)
5512 	 */
5513 	if (drain_cleanup_reqd)
5514 		conn_drain_tail(connp, B_TRUE);
5515 
5516 	if (connp == ipst->ips_ip_g_mrouter)
5517 		(void) ip_mrouter_done(NULL, ipst);
5518 
5519 	if (ilg_cleanup_reqd)
5520 		ilg_delete_all(connp);
5521 
5522 	conn_delete_ire(connp, NULL);
5523 
5524 	/*
5525 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5526 	 * callers from write side can't be there now because close
5527 	 * is in progress. The only other caller is ipcl_walk
5528 	 * which checks for the condemned flag.
5529 	 */
5530 	mutex_enter(&connp->conn_lock);
5531 	connp->conn_state_flags |= CONN_CONDEMNED;
5532 	while (connp->conn_ref != 1)
5533 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5534 	connp->conn_state_flags |= CONN_QUIESCED;
5535 	mutex_exit(&connp->conn_lock);
5536 }
5537 
5538 /* ARGSUSED */
5539 int
5540 ip_close(queue_t *q, int flags)
5541 {
5542 	conn_t		*connp;
5543 
5544 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5545 
5546 	/*
5547 	 * Call the appropriate delete routine depending on whether this is
5548 	 * a module or device.
5549 	 */
5550 	if (WR(q)->q_next != NULL) {
5551 		/* This is a module close */
5552 		return (ip_modclose((ill_t *)q->q_ptr));
5553 	}
5554 
5555 	connp = q->q_ptr;
5556 	ip_quiesce_conn(connp);
5557 
5558 	qprocsoff(q);
5559 
5560 	/*
5561 	 * Now we are truly single threaded on this stream, and can
5562 	 * delete the things hanging off the connp, and finally the connp.
5563 	 * We removed this connp from the fanout list, it cannot be
5564 	 * accessed thru the fanouts, and we already waited for the
5565 	 * conn_ref to drop to 0. We are already in close, so
5566 	 * there cannot be any other thread from the top. qprocsoff
5567 	 * has completed, and service has completed or won't run in
5568 	 * future.
5569 	 */
5570 	ASSERT(connp->conn_ref == 1);
5571 
5572 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5573 
5574 	connp->conn_ref--;
5575 	ipcl_conn_destroy(connp);
5576 
5577 	q->q_ptr = WR(q)->q_ptr = NULL;
5578 	return (0);
5579 }
5580 
5581 /*
5582  * Wapper around putnext() so that ip_rts_request can merely use
5583  * conn_recv.
5584  */
5585 /*ARGSUSED2*/
5586 static void
5587 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5588 {
5589 	conn_t *connp = (conn_t *)arg1;
5590 
5591 	putnext(connp->conn_rq, mp);
5592 }
5593 
5594 /*
5595  * Called when the module is about to be unloaded
5596  */
5597 void
5598 ip_ddi_destroy(void)
5599 {
5600 	tnet_fini();
5601 
5602 	icmp_ddi_g_destroy();
5603 	rts_ddi_g_destroy();
5604 	udp_ddi_g_destroy();
5605 	sctp_ddi_g_destroy();
5606 	tcp_ddi_g_destroy();
5607 	ipsec_policy_g_destroy();
5608 	ipcl_g_destroy();
5609 	ip_net_g_destroy();
5610 	ip_ire_g_fini();
5611 	inet_minor_destroy(ip_minor_arena_sa);
5612 #if defined(_LP64)
5613 	inet_minor_destroy(ip_minor_arena_la);
5614 #endif
5615 
5616 #ifdef DEBUG
5617 	list_destroy(&ip_thread_list);
5618 	rw_destroy(&ip_thread_rwlock);
5619 	tsd_destroy(&ip_thread_data);
5620 #endif
5621 
5622 	netstack_unregister(NS_IP);
5623 }
5624 
5625 /*
5626  * First step in cleanup.
5627  */
5628 /* ARGSUSED */
5629 static void
5630 ip_stack_shutdown(netstackid_t stackid, void *arg)
5631 {
5632 	ip_stack_t *ipst = (ip_stack_t *)arg;
5633 
5634 #ifdef NS_DEBUG
5635 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5636 #endif
5637 
5638 	/* Get rid of loopback interfaces and their IREs */
5639 	ip_loopback_cleanup(ipst);
5640 
5641 	/*
5642 	 * The *_hook_shutdown()s start the process of notifying any
5643 	 * consumers that things are going away.... nothing is destroyed.
5644 	 */
5645 	ipv4_hook_shutdown(ipst);
5646 	ipv6_hook_shutdown(ipst);
5647 
5648 	mutex_enter(&ipst->ips_capab_taskq_lock);
5649 	ipst->ips_capab_taskq_quit = B_TRUE;
5650 	cv_signal(&ipst->ips_capab_taskq_cv);
5651 	mutex_exit(&ipst->ips_capab_taskq_lock);
5652 
5653 	mutex_enter(&ipst->ips_mrt_lock);
5654 	ipst->ips_mrt_flags |= IP_MRT_STOP;
5655 	cv_signal(&ipst->ips_mrt_cv);
5656 	mutex_exit(&ipst->ips_mrt_lock);
5657 }
5658 
5659 /*
5660  * Free the IP stack instance.
5661  */
5662 static void
5663 ip_stack_fini(netstackid_t stackid, void *arg)
5664 {
5665 	ip_stack_t *ipst = (ip_stack_t *)arg;
5666 	int ret;
5667 
5668 #ifdef NS_DEBUG
5669 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5670 #endif
5671 	/*
5672 	 * At this point, all of the notifications that the events and
5673 	 * protocols are going away have been run, meaning that we can
5674 	 * now set about starting to clean things up.
5675 	 */
5676 	ipv4_hook_destroy(ipst);
5677 	ipv6_hook_destroy(ipst);
5678 	ip_net_destroy(ipst);
5679 
5680 	mutex_destroy(&ipst->ips_capab_taskq_lock);
5681 	cv_destroy(&ipst->ips_capab_taskq_cv);
5682 	list_destroy(&ipst->ips_capab_taskq_list);
5683 
5684 	mutex_enter(&ipst->ips_mrt_lock);
5685 	while (!(ipst->ips_mrt_flags & IP_MRT_DONE))
5686 		cv_wait(&ipst->ips_mrt_done_cv, &ipst->ips_mrt_lock);
5687 	mutex_destroy(&ipst->ips_mrt_lock);
5688 	cv_destroy(&ipst->ips_mrt_cv);
5689 	cv_destroy(&ipst->ips_mrt_done_cv);
5690 
5691 	ipmp_destroy(ipst);
5692 	rw_destroy(&ipst->ips_srcid_lock);
5693 
5694 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5695 	ipst->ips_ip_mibkp = NULL;
5696 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5697 	ipst->ips_icmp_mibkp = NULL;
5698 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5699 	ipst->ips_ip_kstat = NULL;
5700 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5701 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5702 	ipst->ips_ip6_kstat = NULL;
5703 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5704 
5705 	nd_free(&ipst->ips_ip_g_nd);
5706 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5707 	ipst->ips_param_arr = NULL;
5708 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5709 	ipst->ips_ndp_arr = NULL;
5710 
5711 	ip_mrouter_stack_destroy(ipst);
5712 
5713 	mutex_destroy(&ipst->ips_ip_mi_lock);
5714 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5715 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5716 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5717 
5718 	ret = untimeout(ipst->ips_igmp_timeout_id);
5719 	if (ret == -1) {
5720 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5721 	} else {
5722 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5723 		ipst->ips_igmp_timeout_id = 0;
5724 	}
5725 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5726 	if (ret == -1) {
5727 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5728 	} else {
5729 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5730 		ipst->ips_igmp_slowtimeout_id = 0;
5731 	}
5732 	ret = untimeout(ipst->ips_mld_timeout_id);
5733 	if (ret == -1) {
5734 		ASSERT(ipst->ips_mld_timeout_id == 0);
5735 	} else {
5736 		ASSERT(ipst->ips_mld_timeout_id != 0);
5737 		ipst->ips_mld_timeout_id = 0;
5738 	}
5739 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5740 	if (ret == -1) {
5741 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5742 	} else {
5743 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5744 		ipst->ips_mld_slowtimeout_id = 0;
5745 	}
5746 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5747 	if (ret == -1) {
5748 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5749 	} else {
5750 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5751 		ipst->ips_ip_ire_expire_id = 0;
5752 	}
5753 
5754 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5755 	mutex_destroy(&ipst->ips_mld_timer_lock);
5756 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5757 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5758 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5759 	rw_destroy(&ipst->ips_ill_g_lock);
5760 
5761 	ipobs_fini(ipst);
5762 	ip_ire_fini(ipst);
5763 	ip6_asp_free(ipst);
5764 	conn_drain_fini(ipst);
5765 	ipcl_destroy(ipst);
5766 
5767 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5768 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5769 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5770 	ipst->ips_ndp4 = NULL;
5771 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5772 	ipst->ips_ndp6 = NULL;
5773 
5774 	if (ipst->ips_loopback_ksp != NULL) {
5775 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5776 		ipst->ips_loopback_ksp = NULL;
5777 	}
5778 
5779 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5780 	ipst->ips_phyint_g_list = NULL;
5781 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5782 	ipst->ips_ill_g_heads = NULL;
5783 
5784 	ldi_ident_release(ipst->ips_ldi_ident);
5785 	kmem_free(ipst, sizeof (*ipst));
5786 }
5787 
5788 /*
5789  * This function is called from the TSD destructor, and is used to debug
5790  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5791  * details.
5792  */
5793 static void
5794 ip_thread_exit(void *phash)
5795 {
5796 	th_hash_t *thh = phash;
5797 
5798 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5799 	list_remove(&ip_thread_list, thh);
5800 	rw_exit(&ip_thread_rwlock);
5801 	mod_hash_destroy_hash(thh->thh_hash);
5802 	kmem_free(thh, sizeof (*thh));
5803 }
5804 
5805 /*
5806  * Called when the IP kernel module is loaded into the kernel
5807  */
5808 void
5809 ip_ddi_init(void)
5810 {
5811 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
5812 
5813 	/*
5814 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5815 	 * initial devices: ip, ip6, tcp, tcp6.
5816 	 */
5817 	/*
5818 	 * If this is a 64-bit kernel, then create two separate arenas -
5819 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5820 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5821 	 */
5822 	ip_minor_arena_la = NULL;
5823 	ip_minor_arena_sa = NULL;
5824 #if defined(_LP64)
5825 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5826 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5827 		cmn_err(CE_PANIC,
5828 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5829 	}
5830 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5831 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5832 		cmn_err(CE_PANIC,
5833 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5834 	}
5835 #else
5836 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5837 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5838 		cmn_err(CE_PANIC,
5839 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5840 	}
5841 #endif
5842 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5843 
5844 	ipcl_g_init();
5845 	ip_ire_g_init();
5846 	ip_net_g_init();
5847 
5848 #ifdef DEBUG
5849 	tsd_create(&ip_thread_data, ip_thread_exit);
5850 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5851 	list_create(&ip_thread_list, sizeof (th_hash_t),
5852 	    offsetof(th_hash_t, thh_link));
5853 #endif
5854 
5855 	/*
5856 	 * We want to be informed each time a stack is created or
5857 	 * destroyed in the kernel, so we can maintain the
5858 	 * set of udp_stack_t's.
5859 	 */
5860 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5861 	    ip_stack_fini);
5862 
5863 	ipsec_policy_g_init();
5864 	tcp_ddi_g_init();
5865 	sctp_ddi_g_init();
5866 
5867 	tnet_init();
5868 
5869 	udp_ddi_g_init();
5870 	rts_ddi_g_init();
5871 	icmp_ddi_g_init();
5872 }
5873 
5874 /*
5875  * Initialize the IP stack instance.
5876  */
5877 static void *
5878 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5879 {
5880 	ip_stack_t	*ipst;
5881 	ipparam_t	*pa;
5882 	ipndp_t		*na;
5883 	major_t		major;
5884 
5885 #ifdef NS_DEBUG
5886 	printf("ip_stack_init(stack %d)\n", stackid);
5887 #endif
5888 
5889 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5890 	ipst->ips_netstack = ns;
5891 
5892 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5893 	    KM_SLEEP);
5894 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5895 	    KM_SLEEP);
5896 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5897 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5898 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5899 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5900 
5901 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5902 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5903 	ipst->ips_igmp_deferred_next = INFINITY;
5904 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5905 	ipst->ips_mld_deferred_next = INFINITY;
5906 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5907 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5908 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5909 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5910 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5911 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5912 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5913 
5914 	ipcl_init(ipst);
5915 	ip_ire_init(ipst);
5916 	ip6_asp_init(ipst);
5917 	ipif_init(ipst);
5918 	conn_drain_init(ipst);
5919 	ip_mrouter_stack_init(ipst);
5920 
5921 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
5922 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
5923 
5924 	ipst->ips_ip_multirt_log_interval = 1000;
5925 
5926 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
5927 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
5928 	ipst->ips_ill_index = 1;
5929 
5930 	ipst->ips_saved_ip_g_forward = -1;
5931 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
5932 
5933 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
5934 	ipst->ips_param_arr = pa;
5935 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
5936 
5937 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
5938 	ipst->ips_ndp_arr = na;
5939 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5940 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
5941 	    (caddr_t)&ipst->ips_ip_g_forward;
5942 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
5943 	    (caddr_t)&ipst->ips_ipv6_forward;
5944 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
5945 	    "ip_cgtp_filter") == 0);
5946 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
5947 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
5948 
5949 	(void) ip_param_register(&ipst->ips_ip_g_nd,
5950 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
5951 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
5952 
5953 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
5954 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
5955 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
5956 	ipst->ips_ip6_kstat =
5957 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
5958 
5959 	ipst->ips_ip_src_id = 1;
5960 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
5961 
5962 	ipobs_init(ipst);
5963 	ip_net_init(ipst, ns);
5964 	ipv4_hook_init(ipst);
5965 	ipv6_hook_init(ipst);
5966 	ipmp_init(ipst);
5967 
5968 	/*
5969 	 * Create the taskq dispatcher thread and initialize related stuff.
5970 	 */
5971 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
5972 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
5973 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
5974 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
5975 	list_create(&ipst->ips_capab_taskq_list, sizeof (mblk_t),
5976 	    offsetof(mblk_t, b_next));
5977 
5978 	/*
5979 	 * Create the mcast_restart_timers_thread() worker thread.
5980 	 */
5981 	mutex_init(&ipst->ips_mrt_lock, NULL, MUTEX_DEFAULT, NULL);
5982 	cv_init(&ipst->ips_mrt_cv, NULL, CV_DEFAULT, NULL);
5983 	cv_init(&ipst->ips_mrt_done_cv, NULL, CV_DEFAULT, NULL);
5984 	ipst->ips_mrt_thread = thread_create(NULL, 0,
5985 	    mcast_restart_timers_thread, ipst, 0, &p0, TS_RUN, minclsyspri);
5986 
5987 	major = mod_name_to_major(INET_NAME);
5988 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
5989 	return (ipst);
5990 }
5991 
5992 /*
5993  * Allocate and initialize a DLPI template of the specified length.  (May be
5994  * called as writer.)
5995  */
5996 mblk_t *
5997 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
5998 {
5999 	mblk_t	*mp;
6000 
6001 	mp = allocb(len, BPRI_MED);
6002 	if (!mp)
6003 		return (NULL);
6004 
6005 	/*
6006 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6007 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6008 	 * that other DLPI are M_PROTO.
6009 	 */
6010 	if (prim == DL_INFO_REQ) {
6011 		mp->b_datap->db_type = M_PCPROTO;
6012 	} else {
6013 		mp->b_datap->db_type = M_PROTO;
6014 	}
6015 
6016 	mp->b_wptr = mp->b_rptr + len;
6017 	bzero(mp->b_rptr, len);
6018 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6019 	return (mp);
6020 }
6021 
6022 /*
6023  * Allocate and initialize a DLPI notification.  (May be called as writer.)
6024  */
6025 mblk_t *
6026 ip_dlnotify_alloc(uint_t notification, uint_t data)
6027 {
6028 	dl_notify_ind_t	*notifyp;
6029 	mblk_t		*mp;
6030 
6031 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
6032 		return (NULL);
6033 
6034 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
6035 	notifyp->dl_notification = notification;
6036 	notifyp->dl_data = data;
6037 	return (mp);
6038 }
6039 
6040 /*
6041  * Debug formatting routine.  Returns a character string representation of the
6042  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6043  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6044  *
6045  * Once the ndd table-printing interfaces are removed, this can be changed to
6046  * standard dotted-decimal form.
6047  */
6048 char *
6049 ip_dot_addr(ipaddr_t addr, char *buf)
6050 {
6051 	uint8_t *ap = (uint8_t *)&addr;
6052 
6053 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6054 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6055 	return (buf);
6056 }
6057 
6058 /*
6059  * Write the given MAC address as a printable string in the usual colon-
6060  * separated format.
6061  */
6062 const char *
6063 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6064 {
6065 	char *bp;
6066 
6067 	if (alen == 0 || buflen < 4)
6068 		return ("?");
6069 	bp = buf;
6070 	for (;;) {
6071 		/*
6072 		 * If there are more MAC address bytes available, but we won't
6073 		 * have any room to print them, then add "..." to the string
6074 		 * instead.  See below for the 'magic number' explanation.
6075 		 */
6076 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6077 			(void) strcpy(bp, "...");
6078 			break;
6079 		}
6080 		(void) sprintf(bp, "%02x", *addr++);
6081 		bp += 2;
6082 		if (--alen == 0)
6083 			break;
6084 		*bp++ = ':';
6085 		buflen -= 3;
6086 		/*
6087 		 * At this point, based on the first 'if' statement above,
6088 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6089 		 * buflen >= 4.  The first case leaves room for the final "xx"
6090 		 * number and trailing NUL byte.  The second leaves room for at
6091 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6092 		 * that statement.
6093 		 */
6094 	}
6095 	return (buf);
6096 }
6097 
6098 /*
6099  * Send an ICMP error after patching up the packet appropriately.  Returns
6100  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6101  */
6102 static boolean_t
6103 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6104     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6105     zoneid_t zoneid, ip_stack_t *ipst)
6106 {
6107 	ipha_t *ipha;
6108 	mblk_t *first_mp;
6109 	boolean_t secure;
6110 	unsigned char db_type;
6111 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6112 
6113 	first_mp = mp;
6114 	if (mctl_present) {
6115 		mp = mp->b_cont;
6116 		secure = ipsec_in_is_secure(first_mp);
6117 		ASSERT(mp != NULL);
6118 	} else {
6119 		/*
6120 		 * If this is an ICMP error being reported - which goes
6121 		 * up as M_CTLs, we need to convert them to M_DATA till
6122 		 * we finish checking with global policy because
6123 		 * ipsec_check_global_policy() assumes M_DATA as clear
6124 		 * and M_CTL as secure.
6125 		 */
6126 		db_type = DB_TYPE(mp);
6127 		DB_TYPE(mp) = M_DATA;
6128 		secure = B_FALSE;
6129 	}
6130 	/*
6131 	 * We are generating an icmp error for some inbound packet.
6132 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6133 	 * Before we generate an error, check with global policy
6134 	 * to see whether this is allowed to enter the system. As
6135 	 * there is no "conn", we are checking with global policy.
6136 	 */
6137 	ipha = (ipha_t *)mp->b_rptr;
6138 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6139 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6140 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6141 		if (first_mp == NULL)
6142 			return (B_FALSE);
6143 	}
6144 
6145 	if (!mctl_present)
6146 		DB_TYPE(mp) = db_type;
6147 
6148 	if (flags & IP_FF_SEND_ICMP) {
6149 		if (flags & IP_FF_HDR_COMPLETE) {
6150 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6151 				freemsg(first_mp);
6152 				return (B_TRUE);
6153 			}
6154 		}
6155 		if (flags & IP_FF_CKSUM) {
6156 			/*
6157 			 * Have to correct checksum since
6158 			 * the packet might have been
6159 			 * fragmented and the reassembly code in ip_rput
6160 			 * does not restore the IP checksum.
6161 			 */
6162 			ipha->ipha_hdr_checksum = 0;
6163 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6164 		}
6165 		switch (icmp_type) {
6166 		case ICMP_DEST_UNREACHABLE:
6167 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6168 			    ipst);
6169 			break;
6170 		default:
6171 			freemsg(first_mp);
6172 			break;
6173 		}
6174 	} else {
6175 		freemsg(first_mp);
6176 		return (B_FALSE);
6177 	}
6178 
6179 	return (B_TRUE);
6180 }
6181 
6182 /*
6183  * Used to send an ICMP error message when a packet is received for
6184  * a protocol that is not supported. The mblk passed as argument
6185  * is consumed by this function.
6186  */
6187 void
6188 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6189     ip_stack_t *ipst)
6190 {
6191 	mblk_t *mp;
6192 	ipha_t *ipha;
6193 	ill_t *ill;
6194 	ipsec_in_t *ii;
6195 
6196 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6197 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6198 
6199 	mp = ipsec_mp->b_cont;
6200 	ipsec_mp->b_cont = NULL;
6201 	ipha = (ipha_t *)mp->b_rptr;
6202 	/* Get ill from index in ipsec_in_t. */
6203 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6204 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6205 	    ipst);
6206 	if (ill != NULL) {
6207 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6208 			if (ip_fanout_send_icmp(q, mp, flags,
6209 			    ICMP_DEST_UNREACHABLE,
6210 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6211 				BUMP_MIB(ill->ill_ip_mib,
6212 				    ipIfStatsInUnknownProtos);
6213 			}
6214 		} else {
6215 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6216 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6217 			    0, B_FALSE, zoneid, ipst)) {
6218 				BUMP_MIB(ill->ill_ip_mib,
6219 				    ipIfStatsInUnknownProtos);
6220 			}
6221 		}
6222 		ill_refrele(ill);
6223 	} else { /* re-link for the freemsg() below. */
6224 		ipsec_mp->b_cont = mp;
6225 	}
6226 
6227 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6228 	freemsg(ipsec_mp);
6229 }
6230 
6231 /*
6232  * See if the inbound datagram has had IPsec processing applied to it.
6233  */
6234 boolean_t
6235 ipsec_in_is_secure(mblk_t *ipsec_mp)
6236 {
6237 	ipsec_in_t *ii;
6238 
6239 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6240 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6241 
6242 	if (ii->ipsec_in_loopback) {
6243 		return (ii->ipsec_in_secure);
6244 	} else {
6245 		return (ii->ipsec_in_ah_sa != NULL ||
6246 		    ii->ipsec_in_esp_sa != NULL ||
6247 		    ii->ipsec_in_decaps);
6248 	}
6249 }
6250 
6251 /*
6252  * Handle protocols with which IP is less intimate.  There
6253  * can be more than one stream bound to a particular
6254  * protocol.  When this is the case, normally each one gets a copy
6255  * of any incoming packets.
6256  *
6257  * IPsec NOTE :
6258  *
6259  * Don't allow a secure packet going up a non-secure connection.
6260  * We don't allow this because
6261  *
6262  * 1) Reply might go out in clear which will be dropped at
6263  *    the sending side.
6264  * 2) If the reply goes out in clear it will give the
6265  *    adversary enough information for getting the key in
6266  *    most of the cases.
6267  *
6268  * Moreover getting a secure packet when we expect clear
6269  * implies that SA's were added without checking for
6270  * policy on both ends. This should not happen once ISAKMP
6271  * is used to negotiate SAs as SAs will be added only after
6272  * verifying the policy.
6273  *
6274  * NOTE : If the packet was tunneled and not multicast we only send
6275  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6276  * back to delivering packets to AF_INET6 raw sockets.
6277  *
6278  * IPQoS Notes:
6279  * Once we have determined the client, invoke IPPF processing.
6280  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6281  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6282  * ip_policy will be false.
6283  *
6284  * Zones notes:
6285  * Currently only applications in the global zone can create raw sockets for
6286  * protocols other than ICMP. So unlike the broadcast / multicast case of
6287  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6288  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6289  */
6290 static void
6291 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6292     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6293     zoneid_t zoneid)
6294 {
6295 	queue_t	*rq;
6296 	mblk_t	*mp1, *first_mp1;
6297 	uint_t	protocol = ipha->ipha_protocol;
6298 	ipaddr_t dst;
6299 	boolean_t one_only;
6300 	mblk_t *first_mp = mp;
6301 	boolean_t secure;
6302 	uint32_t ill_index;
6303 	conn_t	*connp, *first_connp, *next_connp;
6304 	connf_t	*connfp;
6305 	boolean_t shared_addr;
6306 	mib2_ipIfStatsEntry_t *mibptr;
6307 	ip_stack_t *ipst = recv_ill->ill_ipst;
6308 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6309 
6310 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6311 	if (mctl_present) {
6312 		mp = first_mp->b_cont;
6313 		secure = ipsec_in_is_secure(first_mp);
6314 		ASSERT(mp != NULL);
6315 	} else {
6316 		secure = B_FALSE;
6317 	}
6318 	dst = ipha->ipha_dst;
6319 	/*
6320 	 * If the packet was tunneled and not multicast we only send to it
6321 	 * the first match.
6322 	 */
6323 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6324 	    !CLASSD(dst));
6325 
6326 	shared_addr = (zoneid == ALL_ZONES);
6327 	if (shared_addr) {
6328 		/*
6329 		 * We don't allow multilevel ports for raw IP, so no need to
6330 		 * check for that here.
6331 		 */
6332 		zoneid = tsol_packet_to_zoneid(mp);
6333 	}
6334 
6335 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6336 	mutex_enter(&connfp->connf_lock);
6337 	connp = connfp->connf_head;
6338 	for (connp = connfp->connf_head; connp != NULL;
6339 	    connp = connp->conn_next) {
6340 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6341 		    zoneid) &&
6342 		    (!is_system_labeled() ||
6343 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6344 		    connp))) {
6345 			break;
6346 		}
6347 	}
6348 
6349 	if (connp == NULL) {
6350 		/*
6351 		 * No one bound to these addresses.  Is
6352 		 * there a client that wants all
6353 		 * unclaimed datagrams?
6354 		 */
6355 		mutex_exit(&connfp->connf_lock);
6356 		/*
6357 		 * Check for IPPROTO_ENCAP...
6358 		 */
6359 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6360 			/*
6361 			 * If an IPsec mblk is here on a multicast
6362 			 * tunnel (using ip_mroute stuff), check policy here,
6363 			 * THEN ship off to ip_mroute_decap().
6364 			 *
6365 			 * BTW,  If I match a configured IP-in-IP
6366 			 * tunnel, this path will not be reached, and
6367 			 * ip_mroute_decap will never be called.
6368 			 */
6369 			first_mp = ipsec_check_global_policy(first_mp, connp,
6370 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6371 			if (first_mp != NULL) {
6372 				if (mctl_present)
6373 					freeb(first_mp);
6374 				ip_mroute_decap(q, mp, ill);
6375 			} /* Else we already freed everything! */
6376 		} else {
6377 			/*
6378 			 * Otherwise send an ICMP protocol unreachable.
6379 			 */
6380 			if (ip_fanout_send_icmp(q, first_mp, flags,
6381 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6382 			    mctl_present, zoneid, ipst)) {
6383 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6384 			}
6385 		}
6386 		return;
6387 	}
6388 
6389 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
6390 
6391 	CONN_INC_REF(connp);
6392 	first_connp = connp;
6393 
6394 	/*
6395 	 * Only send message to one tunnel driver by immediately
6396 	 * terminating the loop.
6397 	 */
6398 	connp = one_only ? NULL : connp->conn_next;
6399 
6400 	for (;;) {
6401 		while (connp != NULL) {
6402 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6403 			    flags, zoneid) &&
6404 			    (!is_system_labeled() ||
6405 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6406 			    shared_addr, connp)))
6407 				break;
6408 			connp = connp->conn_next;
6409 		}
6410 
6411 		/*
6412 		 * Copy the packet.
6413 		 */
6414 		if (connp == NULL ||
6415 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6416 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6417 			/*
6418 			 * No more interested clients or memory
6419 			 * allocation failed
6420 			 */
6421 			connp = first_connp;
6422 			break;
6423 		}
6424 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
6425 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6426 		CONN_INC_REF(connp);
6427 		mutex_exit(&connfp->connf_lock);
6428 		rq = connp->conn_rq;
6429 
6430 		/*
6431 		 * Check flow control
6432 		 */
6433 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6434 		    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6435 			if (flags & IP_FF_RAWIP) {
6436 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6437 			} else {
6438 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6439 			}
6440 
6441 			freemsg(first_mp1);
6442 		} else {
6443 			/*
6444 			 * Don't enforce here if we're an actual tunnel -
6445 			 * let "tun" do it instead.
6446 			 */
6447 			if (!IPCL_IS_IPTUN(connp) &&
6448 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6449 			    secure)) {
6450 				first_mp1 = ipsec_check_inbound_policy
6451 				    (first_mp1, connp, ipha, NULL,
6452 				    mctl_present);
6453 			}
6454 			if (first_mp1 != NULL) {
6455 				int in_flags = 0;
6456 				/*
6457 				 * ip_fanout_proto also gets called from
6458 				 * icmp_inbound_error_fanout, in which case
6459 				 * the msg type is M_CTL.  Don't add info
6460 				 * in this case for the time being. In future
6461 				 * when there is a need for knowing the
6462 				 * inbound iface index for ICMP error msgs,
6463 				 * then this can be changed.
6464 				 */
6465 				if (connp->conn_recvif)
6466 					in_flags = IPF_RECVIF;
6467 				/*
6468 				 * The ULP may support IP_RECVPKTINFO for both
6469 				 * IP v4 and v6 so pass the appropriate argument
6470 				 * based on conn IP version.
6471 				 */
6472 				if (connp->conn_ip_recvpktinfo) {
6473 					if (connp->conn_af_isv6) {
6474 						/*
6475 						 * V6 only needs index
6476 						 */
6477 						in_flags |= IPF_RECVIF;
6478 					} else {
6479 						/*
6480 						 * V4 needs index +
6481 						 * matching address.
6482 						 */
6483 						in_flags |= IPF_RECVADDR;
6484 					}
6485 				}
6486 				if ((in_flags != 0) &&
6487 				    (mp->b_datap->db_type != M_CTL)) {
6488 					/*
6489 					 * the actual data will be
6490 					 * contained in b_cont upon
6491 					 * successful return of the
6492 					 * following call else
6493 					 * original mblk is returned
6494 					 */
6495 					ASSERT(recv_ill != NULL);
6496 					mp1 = ip_add_info(mp1, recv_ill,
6497 					    in_flags, IPCL_ZONEID(connp), ipst);
6498 				}
6499 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6500 				if (mctl_present)
6501 					freeb(first_mp1);
6502 				(connp->conn_recv)(connp, mp1, NULL);
6503 			}
6504 		}
6505 		mutex_enter(&connfp->connf_lock);
6506 		/* Follow the next pointer before releasing the conn. */
6507 		next_connp = connp->conn_next;
6508 		CONN_DEC_REF(connp);
6509 		connp = next_connp;
6510 	}
6511 
6512 	/* Last one.  Send it upstream. */
6513 	mutex_exit(&connfp->connf_lock);
6514 
6515 	/*
6516 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6517 	 * will be set to false.
6518 	 */
6519 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6520 		ill_index = ill->ill_phyint->phyint_ifindex;
6521 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6522 		if (mp == NULL) {
6523 			CONN_DEC_REF(connp);
6524 			if (mctl_present) {
6525 				freeb(first_mp);
6526 			}
6527 			return;
6528 		}
6529 	}
6530 
6531 	rq = connp->conn_rq;
6532 	/*
6533 	 * Check flow control
6534 	 */
6535 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6536 	    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6537 		if (flags & IP_FF_RAWIP) {
6538 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6539 		} else {
6540 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6541 		}
6542 
6543 		freemsg(first_mp);
6544 	} else {
6545 		if (IPCL_IS_IPTUN(connp)) {
6546 			/*
6547 			 * Tunneled packet.  We enforce policy in the tunnel
6548 			 * module itself.
6549 			 *
6550 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6551 			 * a policy check.
6552 			 * FIXME to use conn_recv for tun later.
6553 			 */
6554 			putnext(rq, first_mp);
6555 			CONN_DEC_REF(connp);
6556 			return;
6557 		}
6558 
6559 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6560 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6561 			    ipha, NULL, mctl_present);
6562 		}
6563 
6564 		if (first_mp != NULL) {
6565 			int in_flags = 0;
6566 
6567 			/*
6568 			 * ip_fanout_proto also gets called
6569 			 * from icmp_inbound_error_fanout, in
6570 			 * which case the msg type is M_CTL.
6571 			 * Don't add info in this case for time
6572 			 * being. In future when there is a
6573 			 * need for knowing the inbound iface
6574 			 * index for ICMP error msgs, then this
6575 			 * can be changed
6576 			 */
6577 			if (connp->conn_recvif)
6578 				in_flags = IPF_RECVIF;
6579 			if (connp->conn_ip_recvpktinfo) {
6580 				if (connp->conn_af_isv6) {
6581 					/*
6582 					 * V6 only needs index
6583 					 */
6584 					in_flags |= IPF_RECVIF;
6585 				} else {
6586 					/*
6587 					 * V4 needs index +
6588 					 * matching address.
6589 					 */
6590 					in_flags |= IPF_RECVADDR;
6591 				}
6592 			}
6593 			if ((in_flags != 0) &&
6594 			    (mp->b_datap->db_type != M_CTL)) {
6595 
6596 				/*
6597 				 * the actual data will be contained in
6598 				 * b_cont upon successful return
6599 				 * of the following call else original
6600 				 * mblk is returned
6601 				 */
6602 				ASSERT(recv_ill != NULL);
6603 				mp = ip_add_info(mp, recv_ill,
6604 				    in_flags, IPCL_ZONEID(connp), ipst);
6605 			}
6606 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6607 			(connp->conn_recv)(connp, mp, NULL);
6608 			if (mctl_present)
6609 				freeb(first_mp);
6610 		}
6611 	}
6612 	CONN_DEC_REF(connp);
6613 }
6614 
6615 /*
6616  * Fanout for TCP packets
6617  * The caller puts <fport, lport> in the ports parameter.
6618  *
6619  * IPQoS Notes
6620  * Before sending it to the client, invoke IPPF processing.
6621  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6622  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6623  * ip_policy is false.
6624  */
6625 static void
6626 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6627     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6628 {
6629 	mblk_t  *first_mp;
6630 	boolean_t secure;
6631 	uint32_t ill_index;
6632 	int	ip_hdr_len;
6633 	tcph_t	*tcph;
6634 	boolean_t syn_present = B_FALSE;
6635 	conn_t	*connp;
6636 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6637 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6638 
6639 	ASSERT(recv_ill != NULL);
6640 
6641 	first_mp = mp;
6642 	if (mctl_present) {
6643 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6644 		mp = first_mp->b_cont;
6645 		secure = ipsec_in_is_secure(first_mp);
6646 		ASSERT(mp != NULL);
6647 	} else {
6648 		secure = B_FALSE;
6649 	}
6650 
6651 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6652 
6653 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6654 	    zoneid, ipst)) == NULL) {
6655 		/*
6656 		 * No connected connection or listener. Send a
6657 		 * TH_RST via tcp_xmit_listeners_reset.
6658 		 */
6659 
6660 		/* Initiate IPPf processing, if needed. */
6661 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6662 			uint32_t ill_index;
6663 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6664 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6665 			if (first_mp == NULL)
6666 				return;
6667 		}
6668 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6669 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6670 		    zoneid));
6671 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6672 		    ipst->ips_netstack->netstack_tcp, NULL);
6673 		return;
6674 	}
6675 
6676 	/*
6677 	 * Allocate the SYN for the TCP connection here itself
6678 	 */
6679 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6680 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6681 		if (IPCL_IS_TCP(connp)) {
6682 			squeue_t *sqp;
6683 
6684 			/*
6685 			 * For fused tcp loopback, assign the eager's
6686 			 * squeue to be that of the active connect's.
6687 			 * Note that we don't check for IP_FF_LOOPBACK
6688 			 * here since this routine gets called only
6689 			 * for loopback (unlike the IPv6 counterpart).
6690 			 */
6691 			ASSERT(Q_TO_CONN(q) != NULL);
6692 			if (do_tcp_fusion &&
6693 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6694 			    !secure &&
6695 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6696 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6697 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6698 				sqp = Q_TO_CONN(q)->conn_sqp;
6699 			} else {
6700 				sqp = IP_SQUEUE_GET(lbolt);
6701 			}
6702 
6703 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6704 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6705 			syn_present = B_TRUE;
6706 		}
6707 	}
6708 
6709 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6710 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6711 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6712 		if ((flags & TH_RST) || (flags & TH_URG)) {
6713 			CONN_DEC_REF(connp);
6714 			freemsg(first_mp);
6715 			return;
6716 		}
6717 		if (flags & TH_ACK) {
6718 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6719 			    ipst->ips_netstack->netstack_tcp, connp);
6720 			CONN_DEC_REF(connp);
6721 			return;
6722 		}
6723 
6724 		CONN_DEC_REF(connp);
6725 		freemsg(first_mp);
6726 		return;
6727 	}
6728 
6729 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6730 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6731 		    NULL, mctl_present);
6732 		if (first_mp == NULL) {
6733 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6734 			CONN_DEC_REF(connp);
6735 			return;
6736 		}
6737 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6738 			ASSERT(syn_present);
6739 			if (mctl_present) {
6740 				ASSERT(first_mp != mp);
6741 				first_mp->b_datap->db_struioflag |=
6742 				    STRUIO_POLICY;
6743 			} else {
6744 				ASSERT(first_mp == mp);
6745 				mp->b_datap->db_struioflag &=
6746 				    ~STRUIO_EAGER;
6747 				mp->b_datap->db_struioflag |=
6748 				    STRUIO_POLICY;
6749 			}
6750 		} else {
6751 			/*
6752 			 * Discard first_mp early since we're dealing with a
6753 			 * fully-connected conn_t and tcp doesn't do policy in
6754 			 * this case.
6755 			 */
6756 			if (mctl_present) {
6757 				freeb(first_mp);
6758 				mctl_present = B_FALSE;
6759 			}
6760 			first_mp = mp;
6761 		}
6762 	}
6763 
6764 	/*
6765 	 * Initiate policy processing here if needed. If we get here from
6766 	 * icmp_inbound_error_fanout, ip_policy is false.
6767 	 */
6768 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6769 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6770 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6771 		if (mp == NULL) {
6772 			CONN_DEC_REF(connp);
6773 			if (mctl_present)
6774 				freeb(first_mp);
6775 			return;
6776 		} else if (mctl_present) {
6777 			ASSERT(first_mp != mp);
6778 			first_mp->b_cont = mp;
6779 		} else {
6780 			first_mp = mp;
6781 		}
6782 	}
6783 
6784 	/* Handle socket options. */
6785 	if (!syn_present &&
6786 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6787 		/* Add header */
6788 		ASSERT(recv_ill != NULL);
6789 		/*
6790 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6791 		 * IPF_RECVIF.
6792 		 */
6793 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6794 		    ipst);
6795 		if (mp == NULL) {
6796 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6797 			CONN_DEC_REF(connp);
6798 			if (mctl_present)
6799 				freeb(first_mp);
6800 			return;
6801 		} else if (mctl_present) {
6802 			/*
6803 			 * ip_add_info might return a new mp.
6804 			 */
6805 			ASSERT(first_mp != mp);
6806 			first_mp->b_cont = mp;
6807 		} else {
6808 			first_mp = mp;
6809 		}
6810 	}
6811 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6812 	if (IPCL_IS_TCP(connp)) {
6813 		/* do not drain, certain use cases can blow the stack */
6814 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, connp->conn_recv,
6815 		    connp, ip_squeue_flag, SQTAG_IP_FANOUT_TCP);
6816 	} else {
6817 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6818 		(connp->conn_recv)(connp, first_mp, NULL);
6819 		CONN_DEC_REF(connp);
6820 	}
6821 }
6822 
6823 /*
6824  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6825  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6826  * is not consumed.
6827  *
6828  * One of four things can happen, all of which affect the passed-in mblk:
6829  *
6830  * 1.) ICMP messages that go through here just get returned TRUE.
6831  *
6832  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6833  *
6834  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6835  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6836  *
6837  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6838  */
6839 static boolean_t
6840 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6841     ipsec_stack_t *ipss)
6842 {
6843 	int shift, plen, iph_len;
6844 	ipha_t *ipha;
6845 	udpha_t *udpha;
6846 	uint32_t *spi;
6847 	uint32_t esp_ports;
6848 	uint8_t *orptr;
6849 	boolean_t free_ire;
6850 
6851 	if (DB_TYPE(mp) == M_CTL) {
6852 		/*
6853 		 * ICMP message with UDP inside.  Don't bother stripping, just
6854 		 * send it up.
6855 		 *
6856 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6857 		 * to ignore errors set by ICMP anyway ('cause they might be
6858 		 * forged), but that's the app's decision, not ours.
6859 		 */
6860 
6861 		/* Bunch of reality checks for DEBUG kernels... */
6862 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6863 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6864 
6865 		return (B_TRUE);
6866 	}
6867 
6868 	ipha = (ipha_t *)mp->b_rptr;
6869 	iph_len = IPH_HDR_LENGTH(ipha);
6870 	plen = ntohs(ipha->ipha_length);
6871 
6872 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6873 		/*
6874 		 * Most likely a keepalive for the benefit of an intervening
6875 		 * NAT.  These aren't for us, per se, so drop it.
6876 		 *
6877 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6878 		 * byte packets (keepalives are 1-byte), but we'll drop them
6879 		 * also.
6880 		 */
6881 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6882 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6883 		return (B_FALSE);
6884 	}
6885 
6886 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6887 		/* might as well pull it all up - it might be ESP. */
6888 		if (!pullupmsg(mp, -1)) {
6889 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6890 			    DROPPER(ipss, ipds_esp_nomem),
6891 			    &ipss->ipsec_dropper);
6892 			return (B_FALSE);
6893 		}
6894 
6895 		ipha = (ipha_t *)mp->b_rptr;
6896 	}
6897 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6898 	if (*spi == 0) {
6899 		/* UDP packet - remove 0-spi. */
6900 		shift = sizeof (uint32_t);
6901 	} else {
6902 		/* ESP-in-UDP packet - reduce to ESP. */
6903 		ipha->ipha_protocol = IPPROTO_ESP;
6904 		shift = sizeof (udpha_t);
6905 	}
6906 
6907 	/* Fix IP header */
6908 	ipha->ipha_length = htons(plen - shift);
6909 	ipha->ipha_hdr_checksum = 0;
6910 
6911 	orptr = mp->b_rptr;
6912 	mp->b_rptr += shift;
6913 
6914 	udpha = (udpha_t *)(orptr + iph_len);
6915 	if (*spi == 0) {
6916 		ASSERT((uint8_t *)ipha == orptr);
6917 		udpha->uha_length = htons(plen - shift - iph_len);
6918 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
6919 		esp_ports = 0;
6920 	} else {
6921 		esp_ports = *((uint32_t *)udpha);
6922 		ASSERT(esp_ports != 0);
6923 	}
6924 	ovbcopy(orptr, orptr + shift, iph_len);
6925 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
6926 		ipha = (ipha_t *)(orptr + shift);
6927 
6928 		free_ire = (ire == NULL);
6929 		if (free_ire) {
6930 			/* Re-acquire ire. */
6931 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
6932 			    ipss->ipsec_netstack->netstack_ip);
6933 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
6934 				if (ire != NULL)
6935 					ire_refrele(ire);
6936 				/*
6937 				 * Do a regular freemsg(), as this is an IP
6938 				 * error (no local route) not an IPsec one.
6939 				 */
6940 				freemsg(mp);
6941 			}
6942 		}
6943 
6944 		ip_proto_input(q, mp, ipha, ire, recv_ill, esp_ports);
6945 		if (free_ire)
6946 			ire_refrele(ire);
6947 	}
6948 
6949 	return (esp_ports == 0);
6950 }
6951 
6952 /*
6953  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6954  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6955  * Caller is responsible for dropping references to the conn, and freeing
6956  * first_mp.
6957  *
6958  * IPQoS Notes
6959  * Before sending it to the client, invoke IPPF processing. Policy processing
6960  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6961  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6962  * ip_wput_local, ip_policy is false.
6963  */
6964 static void
6965 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6966     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6967     boolean_t ip_policy)
6968 {
6969 	boolean_t	mctl_present = (first_mp != NULL);
6970 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6971 	uint32_t	ill_index;
6972 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6973 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6974 
6975 	ASSERT(ill != NULL);
6976 
6977 	if (mctl_present)
6978 		first_mp->b_cont = mp;
6979 	else
6980 		first_mp = mp;
6981 
6982 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6983 	    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
6984 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
6985 		freemsg(first_mp);
6986 		return;
6987 	}
6988 
6989 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6990 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6991 		    NULL, mctl_present);
6992 		/* Freed by ipsec_check_inbound_policy(). */
6993 		if (first_mp == NULL) {
6994 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
6995 			return;
6996 		}
6997 	}
6998 	if (mctl_present)
6999 		freeb(first_mp);
7000 
7001 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7002 	if (connp->conn_udp->udp_nat_t_endpoint) {
7003 		if (mctl_present) {
7004 			/* mctl_present *shouldn't* happen. */
7005 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7006 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7007 			    &ipss->ipsec_dropper);
7008 			return;
7009 		}
7010 
7011 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7012 			return;
7013 	}
7014 
7015 	/* Handle options. */
7016 	if (connp->conn_recvif)
7017 		in_flags = IPF_RECVIF;
7018 	/*
7019 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7020 	 * passed to ip_add_info is based on IP version of connp.
7021 	 */
7022 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7023 		if (connp->conn_af_isv6) {
7024 			/*
7025 			 * V6 only needs index
7026 			 */
7027 			in_flags |= IPF_RECVIF;
7028 		} else {
7029 			/*
7030 			 * V4 needs index + matching address.
7031 			 */
7032 			in_flags |= IPF_RECVADDR;
7033 		}
7034 	}
7035 
7036 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7037 		in_flags |= IPF_RECVSLLA;
7038 
7039 	/*
7040 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7041 	 * freed if the packet is dropped. The caller will do so.
7042 	 */
7043 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7044 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7045 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7046 		if (mp == NULL) {
7047 			return;
7048 		}
7049 	}
7050 	if ((in_flags != 0) &&
7051 	    (mp->b_datap->db_type != M_CTL)) {
7052 		/*
7053 		 * The actual data will be contained in b_cont
7054 		 * upon successful return of the following call
7055 		 * else original mblk is returned
7056 		 */
7057 		ASSERT(recv_ill != NULL);
7058 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7059 		    ipst);
7060 	}
7061 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7062 	/* Send it upstream */
7063 	(connp->conn_recv)(connp, mp, NULL);
7064 }
7065 
7066 /*
7067  * Fanout for UDP packets.
7068  * The caller puts <fport, lport> in the ports parameter.
7069  *
7070  * If SO_REUSEADDR is set all multicast and broadcast packets
7071  * will be delivered to all streams bound to the same port.
7072  *
7073  * Zones notes:
7074  * Multicast and broadcast packets will be distributed to streams in all zones.
7075  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7076  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7077  * packets. To maintain this behavior with multiple zones, the conns are grouped
7078  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7079  * each zone. If unset, all the following conns in the same zone are skipped.
7080  */
7081 static void
7082 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7083     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7084     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7085 {
7086 	uint32_t	dstport, srcport;
7087 	ipaddr_t	dst;
7088 	mblk_t		*first_mp;
7089 	boolean_t	secure;
7090 	in6_addr_t	v6src;
7091 	conn_t		*connp;
7092 	connf_t		*connfp;
7093 	conn_t		*first_connp;
7094 	conn_t		*next_connp;
7095 	mblk_t		*mp1, *first_mp1;
7096 	ipaddr_t	src;
7097 	zoneid_t	last_zoneid;
7098 	boolean_t	reuseaddr;
7099 	boolean_t	shared_addr;
7100 	boolean_t	unlabeled;
7101 	ip_stack_t	*ipst;
7102 
7103 	ASSERT(recv_ill != NULL);
7104 	ipst = recv_ill->ill_ipst;
7105 
7106 	first_mp = mp;
7107 	if (mctl_present) {
7108 		mp = first_mp->b_cont;
7109 		first_mp->b_cont = NULL;
7110 		secure = ipsec_in_is_secure(first_mp);
7111 		ASSERT(mp != NULL);
7112 	} else {
7113 		first_mp = NULL;
7114 		secure = B_FALSE;
7115 	}
7116 
7117 	/* Extract ports in net byte order */
7118 	dstport = htons(ntohl(ports) & 0xFFFF);
7119 	srcport = htons(ntohl(ports) >> 16);
7120 	dst = ipha->ipha_dst;
7121 	src = ipha->ipha_src;
7122 
7123 	unlabeled = B_FALSE;
7124 	if (is_system_labeled())
7125 		/* Cred cannot be null on IPv4 */
7126 		unlabeled = (crgetlabel(DB_CRED(mp))->tsl_flags &
7127 		    TSLF_UNLABELED) != 0;
7128 	shared_addr = (zoneid == ALL_ZONES);
7129 	if (shared_addr) {
7130 		/*
7131 		 * No need to handle exclusive-stack zones since ALL_ZONES
7132 		 * only applies to the shared stack.
7133 		 */
7134 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7135 		/*
7136 		 * If no shared MLP is found, tsol_mlp_findzone returns
7137 		 * ALL_ZONES.  In that case, we assume it's SLP, and
7138 		 * search for the zone based on the packet label.
7139 		 *
7140 		 * If there is such a zone, we prefer to find a
7141 		 * connection in it.  Otherwise, we look for a
7142 		 * MAC-exempt connection in any zone whose label
7143 		 * dominates the default label on the packet.
7144 		 */
7145 		if (zoneid == ALL_ZONES)
7146 			zoneid = tsol_packet_to_zoneid(mp);
7147 		else
7148 			unlabeled = B_FALSE;
7149 	}
7150 
7151 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7152 	mutex_enter(&connfp->connf_lock);
7153 	connp = connfp->connf_head;
7154 	if (!broadcast && !CLASSD(dst)) {
7155 		/*
7156 		 * Not broadcast or multicast. Send to the one (first)
7157 		 * client we find. No need to check conn_wantpacket()
7158 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7159 		 * IPv4 unicast packets.
7160 		 */
7161 		while ((connp != NULL) &&
7162 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7163 		    (!IPCL_ZONE_MATCH(connp, zoneid) &&
7164 		    !(unlabeled && connp->conn_mac_exempt)))) {
7165 			/*
7166 			 * We keep searching since the conn did not match,
7167 			 * or its zone did not match and it is not either
7168 			 * an allzones conn or a mac exempt conn (if the
7169 			 * sender is unlabeled.)
7170 			 */
7171 			connp = connp->conn_next;
7172 		}
7173 
7174 		if (connp == NULL ||
7175 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7176 			goto notfound;
7177 
7178 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7179 
7180 		if (is_system_labeled() &&
7181 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7182 		    connp))
7183 			goto notfound;
7184 
7185 		CONN_INC_REF(connp);
7186 		mutex_exit(&connfp->connf_lock);
7187 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7188 		    flags, recv_ill, ip_policy);
7189 		IP_STAT(ipst, ip_udp_fannorm);
7190 		CONN_DEC_REF(connp);
7191 		return;
7192 	}
7193 
7194 	/*
7195 	 * Broadcast and multicast case
7196 	 *
7197 	 * Need to check conn_wantpacket().
7198 	 * If SO_REUSEADDR has been set on the first we send the
7199 	 * packet to all clients that have joined the group and
7200 	 * match the port.
7201 	 */
7202 
7203 	while (connp != NULL) {
7204 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7205 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7206 		    (!is_system_labeled() ||
7207 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7208 		    connp)))
7209 			break;
7210 		connp = connp->conn_next;
7211 	}
7212 
7213 	if (connp == NULL ||
7214 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7215 		goto notfound;
7216 
7217 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7218 
7219 	first_connp = connp;
7220 	/*
7221 	 * When SO_REUSEADDR is not set, send the packet only to the first
7222 	 * matching connection in its zone by keeping track of the zoneid.
7223 	 */
7224 	reuseaddr = first_connp->conn_reuseaddr;
7225 	last_zoneid = first_connp->conn_zoneid;
7226 
7227 	CONN_INC_REF(connp);
7228 	connp = connp->conn_next;
7229 	for (;;) {
7230 		while (connp != NULL) {
7231 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7232 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7233 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7234 			    (!is_system_labeled() ||
7235 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7236 			    shared_addr, connp)))
7237 				break;
7238 			connp = connp->conn_next;
7239 		}
7240 		/*
7241 		 * Just copy the data part alone. The mctl part is
7242 		 * needed just for verifying policy and it is never
7243 		 * sent up.
7244 		 */
7245 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7246 		    ((mp1 = copymsg(mp)) == NULL))) {
7247 			/*
7248 			 * No more interested clients or memory
7249 			 * allocation failed
7250 			 */
7251 			connp = first_connp;
7252 			break;
7253 		}
7254 		if (connp->conn_zoneid != last_zoneid) {
7255 			/*
7256 			 * Update the zoneid so that the packet isn't sent to
7257 			 * any more conns in the same zone unless SO_REUSEADDR
7258 			 * is set.
7259 			 */
7260 			reuseaddr = connp->conn_reuseaddr;
7261 			last_zoneid = connp->conn_zoneid;
7262 		}
7263 		if (first_mp != NULL) {
7264 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7265 			    ipsec_info_type == IPSEC_IN);
7266 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7267 			    ipst->ips_netstack);
7268 			if (first_mp1 == NULL) {
7269 				freemsg(mp1);
7270 				connp = first_connp;
7271 				break;
7272 			}
7273 		} else {
7274 			first_mp1 = NULL;
7275 		}
7276 		CONN_INC_REF(connp);
7277 		mutex_exit(&connfp->connf_lock);
7278 		/*
7279 		 * IPQoS notes: We don't send the packet for policy
7280 		 * processing here, will do it for the last one (below).
7281 		 * i.e. we do it per-packet now, but if we do policy
7282 		 * processing per-conn, then we would need to do it
7283 		 * here too.
7284 		 */
7285 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7286 		    ipha, flags, recv_ill, B_FALSE);
7287 		mutex_enter(&connfp->connf_lock);
7288 		/* Follow the next pointer before releasing the conn. */
7289 		next_connp = connp->conn_next;
7290 		IP_STAT(ipst, ip_udp_fanmb);
7291 		CONN_DEC_REF(connp);
7292 		connp = next_connp;
7293 	}
7294 
7295 	/* Last one.  Send it upstream. */
7296 	mutex_exit(&connfp->connf_lock);
7297 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7298 	    recv_ill, ip_policy);
7299 	IP_STAT(ipst, ip_udp_fanmb);
7300 	CONN_DEC_REF(connp);
7301 	return;
7302 
7303 notfound:
7304 
7305 	mutex_exit(&connfp->connf_lock);
7306 	IP_STAT(ipst, ip_udp_fanothers);
7307 	/*
7308 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7309 	 * have already been matched above, since they live in the IPv4
7310 	 * fanout tables. This implies we only need to
7311 	 * check for IPv6 in6addr_any endpoints here.
7312 	 * Thus we compare using ipv6_all_zeros instead of the destination
7313 	 * address, except for the multicast group membership lookup which
7314 	 * uses the IPv4 destination.
7315 	 */
7316 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7317 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7318 	mutex_enter(&connfp->connf_lock);
7319 	connp = connfp->connf_head;
7320 	if (!broadcast && !CLASSD(dst)) {
7321 		while (connp != NULL) {
7322 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7323 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7324 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7325 			    !connp->conn_ipv6_v6only)
7326 				break;
7327 			connp = connp->conn_next;
7328 		}
7329 
7330 		if (connp != NULL && is_system_labeled() &&
7331 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7332 		    connp))
7333 			connp = NULL;
7334 
7335 		if (connp == NULL ||
7336 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7337 			/*
7338 			 * No one bound to this port.  Is
7339 			 * there a client that wants all
7340 			 * unclaimed datagrams?
7341 			 */
7342 			mutex_exit(&connfp->connf_lock);
7343 
7344 			if (mctl_present)
7345 				first_mp->b_cont = mp;
7346 			else
7347 				first_mp = mp;
7348 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7349 			    connf_head != NULL) {
7350 				ip_fanout_proto(q, first_mp, ill, ipha,
7351 				    flags | IP_FF_RAWIP, mctl_present,
7352 				    ip_policy, recv_ill, zoneid);
7353 			} else {
7354 				if (ip_fanout_send_icmp(q, first_mp, flags,
7355 				    ICMP_DEST_UNREACHABLE,
7356 				    ICMP_PORT_UNREACHABLE,
7357 				    mctl_present, zoneid, ipst)) {
7358 					BUMP_MIB(ill->ill_ip_mib,
7359 					    udpIfStatsNoPorts);
7360 				}
7361 			}
7362 			return;
7363 		}
7364 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7365 
7366 		CONN_INC_REF(connp);
7367 		mutex_exit(&connfp->connf_lock);
7368 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7369 		    flags, recv_ill, ip_policy);
7370 		CONN_DEC_REF(connp);
7371 		return;
7372 	}
7373 	/*
7374 	 * IPv4 multicast packet being delivered to an AF_INET6
7375 	 * in6addr_any endpoint.
7376 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7377 	 * and not conn_wantpacket_v6() since any multicast membership is
7378 	 * for an IPv4-mapped multicast address.
7379 	 * The packet is sent to all clients in all zones that have joined the
7380 	 * group and match the port.
7381 	 */
7382 	while (connp != NULL) {
7383 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7384 		    srcport, v6src) &&
7385 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7386 		    (!is_system_labeled() ||
7387 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7388 		    connp)))
7389 			break;
7390 		connp = connp->conn_next;
7391 	}
7392 
7393 	if (connp == NULL ||
7394 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7395 		/*
7396 		 * No one bound to this port.  Is
7397 		 * there a client that wants all
7398 		 * unclaimed datagrams?
7399 		 */
7400 		mutex_exit(&connfp->connf_lock);
7401 
7402 		if (mctl_present)
7403 			first_mp->b_cont = mp;
7404 		else
7405 			first_mp = mp;
7406 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7407 		    NULL) {
7408 			ip_fanout_proto(q, first_mp, ill, ipha,
7409 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7410 			    recv_ill, zoneid);
7411 		} else {
7412 			/*
7413 			 * We used to attempt to send an icmp error here, but
7414 			 * since this is known to be a multicast packet
7415 			 * and we don't send icmp errors in response to
7416 			 * multicast, just drop the packet and give up sooner.
7417 			 */
7418 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7419 			freemsg(first_mp);
7420 		}
7421 		return;
7422 	}
7423 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7424 
7425 	first_connp = connp;
7426 
7427 	CONN_INC_REF(connp);
7428 	connp = connp->conn_next;
7429 	for (;;) {
7430 		while (connp != NULL) {
7431 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7432 			    ipv6_all_zeros, srcport, v6src) &&
7433 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7434 			    (!is_system_labeled() ||
7435 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7436 			    shared_addr, connp)))
7437 				break;
7438 			connp = connp->conn_next;
7439 		}
7440 		/*
7441 		 * Just copy the data part alone. The mctl part is
7442 		 * needed just for verifying policy and it is never
7443 		 * sent up.
7444 		 */
7445 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7446 		    ((mp1 = copymsg(mp)) == NULL))) {
7447 			/*
7448 			 * No more intested clients or memory
7449 			 * allocation failed
7450 			 */
7451 			connp = first_connp;
7452 			break;
7453 		}
7454 		if (first_mp != NULL) {
7455 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7456 			    ipsec_info_type == IPSEC_IN);
7457 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7458 			    ipst->ips_netstack);
7459 			if (first_mp1 == NULL) {
7460 				freemsg(mp1);
7461 				connp = first_connp;
7462 				break;
7463 			}
7464 		} else {
7465 			first_mp1 = NULL;
7466 		}
7467 		CONN_INC_REF(connp);
7468 		mutex_exit(&connfp->connf_lock);
7469 		/*
7470 		 * IPQoS notes: We don't send the packet for policy
7471 		 * processing here, will do it for the last one (below).
7472 		 * i.e. we do it per-packet now, but if we do policy
7473 		 * processing per-conn, then we would need to do it
7474 		 * here too.
7475 		 */
7476 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7477 		    ipha, flags, recv_ill, B_FALSE);
7478 		mutex_enter(&connfp->connf_lock);
7479 		/* Follow the next pointer before releasing the conn. */
7480 		next_connp = connp->conn_next;
7481 		CONN_DEC_REF(connp);
7482 		connp = next_connp;
7483 	}
7484 
7485 	/* Last one.  Send it upstream. */
7486 	mutex_exit(&connfp->connf_lock);
7487 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7488 	    recv_ill, ip_policy);
7489 	CONN_DEC_REF(connp);
7490 }
7491 
7492 /*
7493  * Complete the ip_wput header so that it
7494  * is possible to generate ICMP
7495  * errors.
7496  */
7497 int
7498 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7499 {
7500 	ire_t *ire;
7501 
7502 	if (ipha->ipha_src == INADDR_ANY) {
7503 		ire = ire_lookup_local(zoneid, ipst);
7504 		if (ire == NULL) {
7505 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7506 			return (1);
7507 		}
7508 		ipha->ipha_src = ire->ire_addr;
7509 		ire_refrele(ire);
7510 	}
7511 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7512 	ipha->ipha_hdr_checksum = 0;
7513 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7514 	return (0);
7515 }
7516 
7517 /*
7518  * Nobody should be sending
7519  * packets up this stream
7520  */
7521 static void
7522 ip_lrput(queue_t *q, mblk_t *mp)
7523 {
7524 	mblk_t *mp1;
7525 
7526 	switch (mp->b_datap->db_type) {
7527 	case M_FLUSH:
7528 		/* Turn around */
7529 		if (*mp->b_rptr & FLUSHW) {
7530 			*mp->b_rptr &= ~FLUSHR;
7531 			qreply(q, mp);
7532 			return;
7533 		}
7534 		break;
7535 	}
7536 	/* Could receive messages that passed through ar_rput */
7537 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7538 		mp1->b_prev = mp1->b_next = NULL;
7539 	freemsg(mp);
7540 }
7541 
7542 /* Nobody should be sending packets down this stream */
7543 /* ARGSUSED */
7544 void
7545 ip_lwput(queue_t *q, mblk_t *mp)
7546 {
7547 	freemsg(mp);
7548 }
7549 
7550 /*
7551  * Move the first hop in any source route to ipha_dst and remove that part of
7552  * the source route.  Called by other protocols.  Errors in option formatting
7553  * are ignored - will be handled by ip_wput_options Return the final
7554  * destination (either ipha_dst or the last entry in a source route.)
7555  */
7556 ipaddr_t
7557 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7558 {
7559 	ipoptp_t	opts;
7560 	uchar_t		*opt;
7561 	uint8_t		optval;
7562 	uint8_t		optlen;
7563 	ipaddr_t	dst;
7564 	int		i;
7565 	ire_t		*ire;
7566 	ip_stack_t	*ipst = ns->netstack_ip;
7567 
7568 	ip2dbg(("ip_massage_options\n"));
7569 	dst = ipha->ipha_dst;
7570 	for (optval = ipoptp_first(&opts, ipha);
7571 	    optval != IPOPT_EOL;
7572 	    optval = ipoptp_next(&opts)) {
7573 		opt = opts.ipoptp_cur;
7574 		switch (optval) {
7575 			uint8_t off;
7576 		case IPOPT_SSRR:
7577 		case IPOPT_LSRR:
7578 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7579 				ip1dbg(("ip_massage_options: bad src route\n"));
7580 				break;
7581 			}
7582 			optlen = opts.ipoptp_len;
7583 			off = opt[IPOPT_OFFSET];
7584 			off--;
7585 		redo_srr:
7586 			if (optlen < IP_ADDR_LEN ||
7587 			    off > optlen - IP_ADDR_LEN) {
7588 				/* End of source route */
7589 				ip1dbg(("ip_massage_options: end of SR\n"));
7590 				break;
7591 			}
7592 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7593 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7594 			    ntohl(dst)));
7595 			/*
7596 			 * Check if our address is present more than
7597 			 * once as consecutive hops in source route.
7598 			 * XXX verify per-interface ip_forwarding
7599 			 * for source route?
7600 			 */
7601 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7602 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7603 			if (ire != NULL) {
7604 				ire_refrele(ire);
7605 				off += IP_ADDR_LEN;
7606 				goto redo_srr;
7607 			}
7608 			if (dst == htonl(INADDR_LOOPBACK)) {
7609 				ip1dbg(("ip_massage_options: loopback addr in "
7610 				    "source route!\n"));
7611 				break;
7612 			}
7613 			/*
7614 			 * Update ipha_dst to be the first hop and remove the
7615 			 * first hop from the source route (by overwriting
7616 			 * part of the option with NOP options).
7617 			 */
7618 			ipha->ipha_dst = dst;
7619 			/* Put the last entry in dst */
7620 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7621 			    3;
7622 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7623 
7624 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7625 			    ntohl(dst)));
7626 			/* Move down and overwrite */
7627 			opt[IP_ADDR_LEN] = opt[0];
7628 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7629 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7630 			for (i = 0; i < IP_ADDR_LEN; i++)
7631 				opt[i] = IPOPT_NOP;
7632 			break;
7633 		}
7634 	}
7635 	return (dst);
7636 }
7637 
7638 /*
7639  * Return the network mask
7640  * associated with the specified address.
7641  */
7642 ipaddr_t
7643 ip_net_mask(ipaddr_t addr)
7644 {
7645 	uchar_t	*up = (uchar_t *)&addr;
7646 	ipaddr_t mask = 0;
7647 	uchar_t	*maskp = (uchar_t *)&mask;
7648 
7649 #if defined(__i386) || defined(__amd64)
7650 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7651 #endif
7652 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7653 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7654 #endif
7655 	if (CLASSD(addr)) {
7656 		maskp[0] = 0xF0;
7657 		return (mask);
7658 	}
7659 
7660 	/* We assume Class E default netmask to be 32 */
7661 	if (CLASSE(addr))
7662 		return (0xffffffffU);
7663 
7664 	if (addr == 0)
7665 		return (0);
7666 	maskp[0] = 0xFF;
7667 	if ((up[0] & 0x80) == 0)
7668 		return (mask);
7669 
7670 	maskp[1] = 0xFF;
7671 	if ((up[0] & 0xC0) == 0x80)
7672 		return (mask);
7673 
7674 	maskp[2] = 0xFF;
7675 	if ((up[0] & 0xE0) == 0xC0)
7676 		return (mask);
7677 
7678 	/* Otherwise return no mask */
7679 	return ((ipaddr_t)0);
7680 }
7681 
7682 /*
7683  * Helper ill lookup function used by IPsec.
7684  */
7685 ill_t *
7686 ip_grab_ill(mblk_t *first_mp, int ifindex, boolean_t isv6, ip_stack_t *ipst)
7687 {
7688 	ill_t *ret_ill;
7689 
7690 	ASSERT(ifindex != 0);
7691 
7692 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7693 	    ipst);
7694 	if (ret_ill == NULL) {
7695 		if (isv6) {
7696 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
7697 			ip1dbg(("ip_grab_ill (IPv6): bad ifindex %d.\n",
7698 			    ifindex));
7699 		} else {
7700 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
7701 			ip1dbg(("ip_grab_ill (IPv4): bad ifindex %d.\n",
7702 			    ifindex));
7703 		}
7704 		freemsg(first_mp);
7705 		return (NULL);
7706 	}
7707 	return (ret_ill);
7708 }
7709 
7710 /*
7711  * IPv4 -
7712  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7713  * out a packet to a destination address for which we do not have specific
7714  * (or sufficient) routing information.
7715  *
7716  * NOTE : These are the scopes of some of the variables that point at IRE,
7717  *	  which needs to be followed while making any future modifications
7718  *	  to avoid memory leaks.
7719  *
7720  *	- ire and sire are the entries looked up initially by
7721  *	  ire_ftable_lookup.
7722  *	- ipif_ire is used to hold the interface ire associated with
7723  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7724  *	  it before branching out to error paths.
7725  *	- save_ire is initialized before ire_create, so that ire returned
7726  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7727  *	  before breaking out of the switch.
7728  *
7729  *	Thus on failures, we have to REFRELE only ire and sire, if they
7730  *	are not NULL.
7731  */
7732 void
7733 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7734     zoneid_t zoneid, ip_stack_t *ipst)
7735 {
7736 	areq_t	*areq;
7737 	ipaddr_t gw = 0;
7738 	ire_t	*ire = NULL;
7739 	mblk_t	*res_mp;
7740 	ipaddr_t *addrp;
7741 	ipaddr_t nexthop_addr;
7742 	ipif_t  *src_ipif = NULL;
7743 	ill_t	*dst_ill = NULL;
7744 	ipha_t  *ipha;
7745 	ire_t	*sire = NULL;
7746 	mblk_t	*first_mp;
7747 	ire_t	*save_ire;
7748 	ushort_t ire_marks = 0;
7749 	boolean_t mctl_present;
7750 	ipsec_out_t *io;
7751 	mblk_t	*saved_mp;
7752 	ire_t	*first_sire = NULL;
7753 	mblk_t	*copy_mp = NULL;
7754 	mblk_t	*xmit_mp = NULL;
7755 	ipaddr_t save_dst;
7756 	uint32_t multirt_flags =
7757 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7758 	boolean_t multirt_is_resolvable;
7759 	boolean_t multirt_resolve_next;
7760 	boolean_t unspec_src;
7761 	boolean_t ip_nexthop = B_FALSE;
7762 	tsol_ire_gw_secattr_t *attrp = NULL;
7763 	tsol_gcgrp_t *gcgrp = NULL;
7764 	tsol_gcgrp_addr_t ga;
7765 
7766 	if (ip_debug > 2) {
7767 		/* ip1dbg */
7768 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7769 	}
7770 
7771 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7772 	if (mctl_present) {
7773 		io = (ipsec_out_t *)first_mp->b_rptr;
7774 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7775 		ASSERT(zoneid == io->ipsec_out_zoneid);
7776 		ASSERT(zoneid != ALL_ZONES);
7777 	}
7778 
7779 	ipha = (ipha_t *)mp->b_rptr;
7780 
7781 	/* All multicast lookups come through ip_newroute_ipif() */
7782 	if (CLASSD(dst)) {
7783 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7784 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7785 		freemsg(first_mp);
7786 		return;
7787 	}
7788 
7789 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7790 		ip_nexthop = B_TRUE;
7791 		nexthop_addr = io->ipsec_out_nexthop_addr;
7792 	}
7793 	/*
7794 	 * If this IRE is created for forwarding or it is not for
7795 	 * traffic for congestion controlled protocols, mark it as temporary.
7796 	 */
7797 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7798 		ire_marks |= IRE_MARK_TEMPORARY;
7799 
7800 	/*
7801 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7802 	 * chain until it gets the most specific information available.
7803 	 * For example, we know that there is no IRE_CACHE for this dest,
7804 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7805 	 * ire_ftable_lookup will look up the gateway, etc.
7806 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7807 	 * to the destination, of equal netmask length in the forward table,
7808 	 * will be recursively explored. If no information is available
7809 	 * for the final gateway of that route, we force the returned ire
7810 	 * to be equal to sire using MATCH_IRE_PARENT.
7811 	 * At least, in this case we have a starting point (in the buckets)
7812 	 * to look for other routes to the destination in the forward table.
7813 	 * This is actually used only for multirouting, where a list
7814 	 * of routes has to be processed in sequence.
7815 	 *
7816 	 * In the process of coming up with the most specific information,
7817 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7818 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7819 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7820 	 * Two caveats when handling incomplete ire's in ip_newroute:
7821 	 * - we should be careful when accessing its ire_nce (specifically
7822 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7823 	 * - not all legacy code path callers are prepared to handle
7824 	 *   incomplete ire's, so we should not create/add incomplete
7825 	 *   ire_cache entries here. (See discussion about temporary solution
7826 	 *   further below).
7827 	 *
7828 	 * In order to minimize packet dropping, and to preserve existing
7829 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7830 	 * gateway, and instead use the IF_RESOLVER ire to send out
7831 	 * another request to ARP (this is achieved by passing the
7832 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7833 	 * arp response comes back in ip_wput_nondata, we will create
7834 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7835 	 *
7836 	 * Note that this is a temporary solution; the correct solution is
7837 	 * to create an incomplete  per-dst ire_cache entry, and send the
7838 	 * packet out when the gw's nce is resolved. In order to achieve this,
7839 	 * all packet processing must have been completed prior to calling
7840 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7841 	 * to be modified to accomodate this solution.
7842 	 */
7843 	if (ip_nexthop) {
7844 		/*
7845 		 * The first time we come here, we look for an IRE_INTERFACE
7846 		 * entry for the specified nexthop, set the dst to be the
7847 		 * nexthop address and create an IRE_CACHE entry for the
7848 		 * nexthop. The next time around, we are able to find an
7849 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7850 		 * nexthop address and create an IRE_CACHE entry for the
7851 		 * destination address via the specified nexthop.
7852 		 */
7853 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7854 		    MBLK_GETLABEL(mp), ipst);
7855 		if (ire != NULL) {
7856 			gw = nexthop_addr;
7857 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7858 		} else {
7859 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7860 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7861 			    MBLK_GETLABEL(mp),
7862 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7863 			    ipst);
7864 			if (ire != NULL) {
7865 				dst = nexthop_addr;
7866 			}
7867 		}
7868 	} else {
7869 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7870 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7871 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7872 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7873 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7874 		    ipst);
7875 	}
7876 
7877 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7878 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7879 
7880 	/*
7881 	 * This loop is run only once in most cases.
7882 	 * We loop to resolve further routes only when the destination
7883 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7884 	 */
7885 	do {
7886 		/* Clear the previous iteration's values */
7887 		if (src_ipif != NULL) {
7888 			ipif_refrele(src_ipif);
7889 			src_ipif = NULL;
7890 		}
7891 		if (dst_ill != NULL) {
7892 			ill_refrele(dst_ill);
7893 			dst_ill = NULL;
7894 		}
7895 
7896 		multirt_resolve_next = B_FALSE;
7897 		/*
7898 		 * We check if packets have to be multirouted.
7899 		 * In this case, given the current <ire, sire> couple,
7900 		 * we look for the next suitable <ire, sire>.
7901 		 * This check is done in ire_multirt_lookup(),
7902 		 * which applies various criteria to find the next route
7903 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7904 		 * unchanged if it detects it has not been tried yet.
7905 		 */
7906 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7907 			ip3dbg(("ip_newroute: starting next_resolution "
7908 			    "with first_mp %p, tag %d\n",
7909 			    (void *)first_mp,
7910 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7911 
7912 			ASSERT(sire != NULL);
7913 			multirt_is_resolvable =
7914 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7915 			    MBLK_GETLABEL(mp), ipst);
7916 
7917 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7918 			    "ire %p, sire %p\n",
7919 			    multirt_is_resolvable,
7920 			    (void *)ire, (void *)sire));
7921 
7922 			if (!multirt_is_resolvable) {
7923 				/*
7924 				 * No more multirt route to resolve; give up
7925 				 * (all routes resolved or no more
7926 				 * resolvable routes).
7927 				 */
7928 				if (ire != NULL) {
7929 					ire_refrele(ire);
7930 					ire = NULL;
7931 				}
7932 			} else {
7933 				ASSERT(sire != NULL);
7934 				ASSERT(ire != NULL);
7935 				/*
7936 				 * We simply use first_sire as a flag that
7937 				 * indicates if a resolvable multirt route
7938 				 * has already been found.
7939 				 * If it is not the case, we may have to send
7940 				 * an ICMP error to report that the
7941 				 * destination is unreachable.
7942 				 * We do not IRE_REFHOLD first_sire.
7943 				 */
7944 				if (first_sire == NULL) {
7945 					first_sire = sire;
7946 				}
7947 			}
7948 		}
7949 		if (ire == NULL) {
7950 			if (ip_debug > 3) {
7951 				/* ip2dbg */
7952 				pr_addr_dbg("ip_newroute: "
7953 				    "can't resolve %s\n", AF_INET, &dst);
7954 			}
7955 			ip3dbg(("ip_newroute: "
7956 			    "ire %p, sire %p, first_sire %p\n",
7957 			    (void *)ire, (void *)sire, (void *)first_sire));
7958 
7959 			if (sire != NULL) {
7960 				ire_refrele(sire);
7961 				sire = NULL;
7962 			}
7963 
7964 			if (first_sire != NULL) {
7965 				/*
7966 				 * At least one multirt route has been found
7967 				 * in the same call to ip_newroute();
7968 				 * there is no need to report an ICMP error.
7969 				 * first_sire was not IRE_REFHOLDed.
7970 				 */
7971 				MULTIRT_DEBUG_UNTAG(first_mp);
7972 				freemsg(first_mp);
7973 				return;
7974 			}
7975 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
7976 			    RTA_DST, ipst);
7977 			goto icmp_err_ret;
7978 		}
7979 
7980 		/*
7981 		 * Verify that the returned IRE does not have either
7982 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
7983 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
7984 		 */
7985 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
7986 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
7987 			goto icmp_err_ret;
7988 		}
7989 		/*
7990 		 * Increment the ire_ob_pkt_count field for ire if it is an
7991 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
7992 		 * increment the same for the parent IRE, sire, if it is some
7993 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
7994 		 */
7995 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
7996 			UPDATE_OB_PKT_COUNT(ire);
7997 			ire->ire_last_used_time = lbolt;
7998 		}
7999 
8000 		if (sire != NULL) {
8001 			gw = sire->ire_gateway_addr;
8002 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8003 			    IRE_INTERFACE)) == 0);
8004 			UPDATE_OB_PKT_COUNT(sire);
8005 			sire->ire_last_used_time = lbolt;
8006 		}
8007 		/*
8008 		 * We have a route to reach the destination.  Find the
8009 		 * appropriate ill, then get a source address using
8010 		 * ipif_select_source().
8011 		 *
8012 		 * If we are here trying to create an IRE_CACHE for an offlink
8013 		 * destination and have an IRE_CACHE entry for VNI, then use
8014 		 * ire_stq instead since VNI's queue is a black hole.
8015 		 */
8016 		if ((ire->ire_type == IRE_CACHE) &&
8017 		    IS_VNI(ire->ire_ipif->ipif_ill)) {
8018 			dst_ill = ire->ire_stq->q_ptr;
8019 			ill_refhold(dst_ill);
8020 		} else {
8021 			ill_t *ill = ire->ire_ipif->ipif_ill;
8022 
8023 			if (IS_IPMP(ill)) {
8024 				dst_ill =
8025 				    ipmp_illgrp_hold_next_ill(ill->ill_grp);
8026 			} else {
8027 				dst_ill = ill;
8028 				ill_refhold(dst_ill);
8029 			}
8030 		}
8031 
8032 		if (dst_ill == NULL) {
8033 			if (ip_debug > 2) {
8034 				pr_addr_dbg("ip_newroute: no dst "
8035 				    "ill for dst %s\n", AF_INET, &dst);
8036 			}
8037 			goto icmp_err_ret;
8038 		}
8039 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8040 
8041 		/*
8042 		 * Pick the best source address from dst_ill.
8043 		 *
8044 		 * 1) Try to pick the source address from the destination
8045 		 *    route. Clustering assumes that when we have multiple
8046 		 *    prefixes hosted on an interface, the prefix of the
8047 		 *    source address matches the prefix of the destination
8048 		 *    route. We do this only if the address is not
8049 		 *    DEPRECATED.
8050 		 *
8051 		 * 2) If the conn is in a different zone than the ire, we
8052 		 *    need to pick a source address from the right zone.
8053 		 */
8054 		ASSERT(src_ipif == NULL);
8055 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8056 			/*
8057 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8058 			 * Check that the ipif matching the requested source
8059 			 * address still exists.
8060 			 */
8061 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8062 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8063 		}
8064 
8065 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8066 
8067 		if (src_ipif == NULL &&
8068 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8069 			ire_marks |= IRE_MARK_USESRC_CHECK;
8070 			if (!IS_UNDER_IPMP(ire->ire_ipif->ipif_ill) &&
8071 			    IS_IPMP(ire->ire_ipif->ipif_ill) ||
8072 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8073 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8074 			    ire->ire_zoneid != ALL_ZONES) ||
8075 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8076 				/*
8077 				 * If the destination is reachable via a
8078 				 * given gateway, the selected source address
8079 				 * should be in the same subnet as the gateway.
8080 				 * Otherwise, the destination is not reachable.
8081 				 *
8082 				 * If there are no interfaces on the same subnet
8083 				 * as the destination, ipif_select_source gives
8084 				 * first non-deprecated interface which might be
8085 				 * on a different subnet than the gateway.
8086 				 * This is not desirable. Hence pass the dst_ire
8087 				 * source address to ipif_select_source.
8088 				 * It is sure that the destination is reachable
8089 				 * with the dst_ire source address subnet.
8090 				 * So passing dst_ire source address to
8091 				 * ipif_select_source will make sure that the
8092 				 * selected source will be on the same subnet
8093 				 * as dst_ire source address.
8094 				 */
8095 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8096 
8097 				src_ipif = ipif_select_source(dst_ill, saddr,
8098 				    zoneid);
8099 				if (src_ipif == NULL) {
8100 					if (ip_debug > 2) {
8101 						pr_addr_dbg("ip_newroute: "
8102 						    "no src for dst %s ",
8103 						    AF_INET, &dst);
8104 						printf("on interface %s\n",
8105 						    dst_ill->ill_name);
8106 					}
8107 					goto icmp_err_ret;
8108 				}
8109 			} else {
8110 				src_ipif = ire->ire_ipif;
8111 				ASSERT(src_ipif != NULL);
8112 				/* hold src_ipif for uniformity */
8113 				ipif_refhold(src_ipif);
8114 			}
8115 		}
8116 
8117 		/*
8118 		 * Assign a source address while we have the conn.
8119 		 * We can't have ip_wput_ire pick a source address when the
8120 		 * packet returns from arp since we need to look at
8121 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8122 		 * going through arp.
8123 		 *
8124 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8125 		 *	  it uses ip6i to store this information.
8126 		 */
8127 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8128 			ipha->ipha_src = src_ipif->ipif_src_addr;
8129 
8130 		if (ip_debug > 3) {
8131 			/* ip2dbg */
8132 			pr_addr_dbg("ip_newroute: first hop %s\n",
8133 			    AF_INET, &gw);
8134 		}
8135 		ip2dbg(("\tire type %s (%d)\n",
8136 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8137 
8138 		/*
8139 		 * The TTL of multirouted packets is bounded by the
8140 		 * ip_multirt_ttl ndd variable.
8141 		 */
8142 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8143 			/* Force TTL of multirouted packets */
8144 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8145 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8146 				ip2dbg(("ip_newroute: forcing multirt TTL "
8147 				    "to %d (was %d), dst 0x%08x\n",
8148 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8149 				    ntohl(sire->ire_addr)));
8150 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8151 			}
8152 		}
8153 		/*
8154 		 * At this point in ip_newroute(), ire is either the
8155 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8156 		 * destination or an IRE_INTERFACE type that should be used
8157 		 * to resolve an on-subnet destination or an on-subnet
8158 		 * next-hop gateway.
8159 		 *
8160 		 * In the IRE_CACHE case, we have the following :
8161 		 *
8162 		 * 1) src_ipif - used for getting a source address.
8163 		 *
8164 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8165 		 *    means packets using this IRE_CACHE will go out on
8166 		 *    dst_ill.
8167 		 *
8168 		 * 3) The IRE sire will point to the prefix that is the
8169 		 *    longest  matching route for the destination. These
8170 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8171 		 *
8172 		 *    The newly created IRE_CACHE entry for the off-subnet
8173 		 *    destination is tied to both the prefix route and the
8174 		 *    interface route used to resolve the next-hop gateway
8175 		 *    via the ire_phandle and ire_ihandle fields,
8176 		 *    respectively.
8177 		 *
8178 		 * In the IRE_INTERFACE case, we have the following :
8179 		 *
8180 		 * 1) src_ipif - used for getting a source address.
8181 		 *
8182 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8183 		 *    means packets using the IRE_CACHE that we will build
8184 		 *    here will go out on dst_ill.
8185 		 *
8186 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8187 		 *    to be created will only be tied to the IRE_INTERFACE
8188 		 *    that was derived from the ire_ihandle field.
8189 		 *
8190 		 *    If sire is non-NULL, it means the destination is
8191 		 *    off-link and we will first create the IRE_CACHE for the
8192 		 *    gateway. Next time through ip_newroute, we will create
8193 		 *    the IRE_CACHE for the final destination as described
8194 		 *    above.
8195 		 *
8196 		 * In both cases, after the current resolution has been
8197 		 * completed (or possibly initialised, in the IRE_INTERFACE
8198 		 * case), the loop may be re-entered to attempt the resolution
8199 		 * of another RTF_MULTIRT route.
8200 		 *
8201 		 * When an IRE_CACHE entry for the off-subnet destination is
8202 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8203 		 * for further processing in emission loops.
8204 		 */
8205 		save_ire = ire;
8206 		switch (ire->ire_type) {
8207 		case IRE_CACHE: {
8208 			ire_t	*ipif_ire;
8209 
8210 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8211 			if (gw == 0)
8212 				gw = ire->ire_gateway_addr;
8213 			/*
8214 			 * We need 3 ire's to create a new cache ire for an
8215 			 * off-link destination from the cache ire of the
8216 			 * gateway.
8217 			 *
8218 			 *	1. The prefix ire 'sire' (Note that this does
8219 			 *	   not apply to the conn_nexthop_set case)
8220 			 *	2. The cache ire of the gateway 'ire'
8221 			 *	3. The interface ire 'ipif_ire'
8222 			 *
8223 			 * We have (1) and (2). We lookup (3) below.
8224 			 *
8225 			 * If there is no interface route to the gateway,
8226 			 * it is a race condition, where we found the cache
8227 			 * but the interface route has been deleted.
8228 			 */
8229 			if (ip_nexthop) {
8230 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8231 			} else {
8232 				ipif_ire =
8233 				    ire_ihandle_lookup_offlink(ire, sire);
8234 			}
8235 			if (ipif_ire == NULL) {
8236 				ip1dbg(("ip_newroute: "
8237 				    "ire_ihandle_lookup_offlink failed\n"));
8238 				goto icmp_err_ret;
8239 			}
8240 
8241 			/*
8242 			 * Check cached gateway IRE for any security
8243 			 * attributes; if found, associate the gateway
8244 			 * credentials group to the destination IRE.
8245 			 */
8246 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8247 				mutex_enter(&attrp->igsa_lock);
8248 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8249 					GCGRP_REFHOLD(gcgrp);
8250 				mutex_exit(&attrp->igsa_lock);
8251 			}
8252 
8253 			/*
8254 			 * XXX For the source of the resolver mp,
8255 			 * we are using the same DL_UNITDATA_REQ
8256 			 * (from save_ire->ire_nce->nce_res_mp)
8257 			 * though the save_ire is not pointing at the same ill.
8258 			 * This is incorrect. We need to send it up to the
8259 			 * resolver to get the right res_mp. For ethernets
8260 			 * this may be okay (ill_type == DL_ETHER).
8261 			 */
8262 
8263 			ire = ire_create(
8264 			    (uchar_t *)&dst,		/* dest address */
8265 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8266 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8267 			    (uchar_t *)&gw,		/* gateway address */
8268 			    &save_ire->ire_max_frag,
8269 			    save_ire->ire_nce,		/* src nce */
8270 			    dst_ill->ill_rq,		/* recv-from queue */
8271 			    dst_ill->ill_wq,		/* send-to queue */
8272 			    IRE_CACHE,			/* IRE type */
8273 			    src_ipif,
8274 			    (sire != NULL) ?
8275 			    sire->ire_mask : 0, 	/* Parent mask */
8276 			    (sire != NULL) ?
8277 			    sire->ire_phandle : 0,	/* Parent handle */
8278 			    ipif_ire->ire_ihandle,	/* Interface handle */
8279 			    (sire != NULL) ? (sire->ire_flags &
8280 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8281 			    (sire != NULL) ?
8282 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8283 			    NULL,
8284 			    gcgrp,
8285 			    ipst);
8286 
8287 			if (ire == NULL) {
8288 				if (gcgrp != NULL) {
8289 					GCGRP_REFRELE(gcgrp);
8290 					gcgrp = NULL;
8291 				}
8292 				ire_refrele(ipif_ire);
8293 				ire_refrele(save_ire);
8294 				break;
8295 			}
8296 
8297 			/* reference now held by IRE */
8298 			gcgrp = NULL;
8299 
8300 			ire->ire_marks |= ire_marks;
8301 
8302 			/*
8303 			 * Prevent sire and ipif_ire from getting deleted.
8304 			 * The newly created ire is tied to both of them via
8305 			 * the phandle and ihandle respectively.
8306 			 */
8307 			if (sire != NULL) {
8308 				IRB_REFHOLD(sire->ire_bucket);
8309 				/* Has it been removed already ? */
8310 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8311 					IRB_REFRELE(sire->ire_bucket);
8312 					ire_refrele(ipif_ire);
8313 					ire_refrele(save_ire);
8314 					break;
8315 				}
8316 			}
8317 
8318 			IRB_REFHOLD(ipif_ire->ire_bucket);
8319 			/* Has it been removed already ? */
8320 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8321 				IRB_REFRELE(ipif_ire->ire_bucket);
8322 				if (sire != NULL)
8323 					IRB_REFRELE(sire->ire_bucket);
8324 				ire_refrele(ipif_ire);
8325 				ire_refrele(save_ire);
8326 				break;
8327 			}
8328 
8329 			xmit_mp = first_mp;
8330 			/*
8331 			 * In the case of multirouting, a copy
8332 			 * of the packet is done before its sending.
8333 			 * The copy is used to attempt another
8334 			 * route resolution, in a next loop.
8335 			 */
8336 			if (ire->ire_flags & RTF_MULTIRT) {
8337 				copy_mp = copymsg(first_mp);
8338 				if (copy_mp != NULL) {
8339 					xmit_mp = copy_mp;
8340 					MULTIRT_DEBUG_TAG(first_mp);
8341 				}
8342 			}
8343 
8344 			ire_add_then_send(q, ire, xmit_mp);
8345 			ire_refrele(save_ire);
8346 
8347 			/* Assert that sire is not deleted yet. */
8348 			if (sire != NULL) {
8349 				ASSERT(sire->ire_ptpn != NULL);
8350 				IRB_REFRELE(sire->ire_bucket);
8351 			}
8352 
8353 			/* Assert that ipif_ire is not deleted yet. */
8354 			ASSERT(ipif_ire->ire_ptpn != NULL);
8355 			IRB_REFRELE(ipif_ire->ire_bucket);
8356 			ire_refrele(ipif_ire);
8357 
8358 			/*
8359 			 * If copy_mp is not NULL, multirouting was
8360 			 * requested. We loop to initiate a next
8361 			 * route resolution attempt, starting from sire.
8362 			 */
8363 			if (copy_mp != NULL) {
8364 				/*
8365 				 * Search for the next unresolved
8366 				 * multirt route.
8367 				 */
8368 				copy_mp = NULL;
8369 				ipif_ire = NULL;
8370 				ire = NULL;
8371 				multirt_resolve_next = B_TRUE;
8372 				continue;
8373 			}
8374 			if (sire != NULL)
8375 				ire_refrele(sire);
8376 			ipif_refrele(src_ipif);
8377 			ill_refrele(dst_ill);
8378 			return;
8379 		}
8380 		case IRE_IF_NORESOLVER: {
8381 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8382 			    dst_ill->ill_resolver_mp == NULL) {
8383 				ip1dbg(("ip_newroute: dst_ill %p "
8384 				    "for IRE_IF_NORESOLVER ire %p has "
8385 				    "no ill_resolver_mp\n",
8386 				    (void *)dst_ill, (void *)ire));
8387 				break;
8388 			}
8389 
8390 			/*
8391 			 * TSol note: We are creating the ire cache for the
8392 			 * destination 'dst'. If 'dst' is offlink, going
8393 			 * through the first hop 'gw', the security attributes
8394 			 * of 'dst' must be set to point to the gateway
8395 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8396 			 * is possible that 'dst' is a potential gateway that is
8397 			 * referenced by some route that has some security
8398 			 * attributes. Thus in the former case, we need to do a
8399 			 * gcgrp_lookup of 'gw' while in the latter case we
8400 			 * need to do gcgrp_lookup of 'dst' itself.
8401 			 */
8402 			ga.ga_af = AF_INET;
8403 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8404 			    &ga.ga_addr);
8405 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8406 
8407 			ire = ire_create(
8408 			    (uchar_t *)&dst,		/* dest address */
8409 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8410 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8411 			    (uchar_t *)&gw,		/* gateway address */
8412 			    &save_ire->ire_max_frag,
8413 			    NULL,			/* no src nce */
8414 			    dst_ill->ill_rq,		/* recv-from queue */
8415 			    dst_ill->ill_wq,		/* send-to queue */
8416 			    IRE_CACHE,
8417 			    src_ipif,
8418 			    save_ire->ire_mask,		/* Parent mask */
8419 			    (sire != NULL) ?		/* Parent handle */
8420 			    sire->ire_phandle : 0,
8421 			    save_ire->ire_ihandle,	/* Interface handle */
8422 			    (sire != NULL) ? sire->ire_flags &
8423 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8424 			    &(save_ire->ire_uinfo),
8425 			    NULL,
8426 			    gcgrp,
8427 			    ipst);
8428 
8429 			if (ire == NULL) {
8430 				if (gcgrp != NULL) {
8431 					GCGRP_REFRELE(gcgrp);
8432 					gcgrp = NULL;
8433 				}
8434 				ire_refrele(save_ire);
8435 				break;
8436 			}
8437 
8438 			/* reference now held by IRE */
8439 			gcgrp = NULL;
8440 
8441 			ire->ire_marks |= ire_marks;
8442 
8443 			/* Prevent save_ire from getting deleted */
8444 			IRB_REFHOLD(save_ire->ire_bucket);
8445 			/* Has it been removed already ? */
8446 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8447 				IRB_REFRELE(save_ire->ire_bucket);
8448 				ire_refrele(save_ire);
8449 				break;
8450 			}
8451 
8452 			/*
8453 			 * In the case of multirouting, a copy
8454 			 * of the packet is made before it is sent.
8455 			 * The copy is used in the next
8456 			 * loop to attempt another resolution.
8457 			 */
8458 			xmit_mp = first_mp;
8459 			if ((sire != NULL) &&
8460 			    (sire->ire_flags & RTF_MULTIRT)) {
8461 				copy_mp = copymsg(first_mp);
8462 				if (copy_mp != NULL) {
8463 					xmit_mp = copy_mp;
8464 					MULTIRT_DEBUG_TAG(first_mp);
8465 				}
8466 			}
8467 			ire_add_then_send(q, ire, xmit_mp);
8468 
8469 			/* Assert that it is not deleted yet. */
8470 			ASSERT(save_ire->ire_ptpn != NULL);
8471 			IRB_REFRELE(save_ire->ire_bucket);
8472 			ire_refrele(save_ire);
8473 
8474 			if (copy_mp != NULL) {
8475 				/*
8476 				 * If we found a (no)resolver, we ignore any
8477 				 * trailing top priority IRE_CACHE in further
8478 				 * loops. This ensures that we do not omit any
8479 				 * (no)resolver.
8480 				 * This IRE_CACHE, if any, will be processed
8481 				 * by another thread entering ip_newroute().
8482 				 * IRE_CACHE entries, if any, will be processed
8483 				 * by another thread entering ip_newroute(),
8484 				 * (upon resolver response, for instance).
8485 				 * This aims to force parallel multirt
8486 				 * resolutions as soon as a packet must be sent.
8487 				 * In the best case, after the tx of only one
8488 				 * packet, all reachable routes are resolved.
8489 				 * Otherwise, the resolution of all RTF_MULTIRT
8490 				 * routes would require several emissions.
8491 				 */
8492 				multirt_flags &= ~MULTIRT_CACHEGW;
8493 
8494 				/*
8495 				 * Search for the next unresolved multirt
8496 				 * route.
8497 				 */
8498 				copy_mp = NULL;
8499 				save_ire = NULL;
8500 				ire = NULL;
8501 				multirt_resolve_next = B_TRUE;
8502 				continue;
8503 			}
8504 
8505 			/*
8506 			 * Don't need sire anymore
8507 			 */
8508 			if (sire != NULL)
8509 				ire_refrele(sire);
8510 
8511 			ipif_refrele(src_ipif);
8512 			ill_refrele(dst_ill);
8513 			return;
8514 		}
8515 		case IRE_IF_RESOLVER:
8516 			/*
8517 			 * We can't build an IRE_CACHE yet, but at least we
8518 			 * found a resolver that can help.
8519 			 */
8520 			res_mp = dst_ill->ill_resolver_mp;
8521 			if (!OK_RESOLVER_MP(res_mp))
8522 				break;
8523 
8524 			/*
8525 			 * To be at this point in the code with a non-zero gw
8526 			 * means that dst is reachable through a gateway that
8527 			 * we have never resolved.  By changing dst to the gw
8528 			 * addr we resolve the gateway first.
8529 			 * When ire_add_then_send() tries to put the IP dg
8530 			 * to dst, it will reenter ip_newroute() at which
8531 			 * time we will find the IRE_CACHE for the gw and
8532 			 * create another IRE_CACHE in case IRE_CACHE above.
8533 			 */
8534 			if (gw != INADDR_ANY) {
8535 				/*
8536 				 * The source ipif that was determined above was
8537 				 * relative to the destination address, not the
8538 				 * gateway's. If src_ipif was not taken out of
8539 				 * the IRE_IF_RESOLVER entry, we'll need to call
8540 				 * ipif_select_source() again.
8541 				 */
8542 				if (src_ipif != ire->ire_ipif) {
8543 					ipif_refrele(src_ipif);
8544 					src_ipif = ipif_select_source(dst_ill,
8545 					    gw, zoneid);
8546 					if (src_ipif == NULL) {
8547 						if (ip_debug > 2) {
8548 							pr_addr_dbg(
8549 							    "ip_newroute: no "
8550 							    "src for gw %s ",
8551 							    AF_INET, &gw);
8552 							printf("on "
8553 							    "interface %s\n",
8554 							    dst_ill->ill_name);
8555 						}
8556 						goto icmp_err_ret;
8557 					}
8558 				}
8559 				save_dst = dst;
8560 				dst = gw;
8561 				gw = INADDR_ANY;
8562 			}
8563 
8564 			/*
8565 			 * We obtain a partial IRE_CACHE which we will pass
8566 			 * along with the resolver query.  When the response
8567 			 * comes back it will be there ready for us to add.
8568 			 * The ire_max_frag is atomically set under the
8569 			 * irebucket lock in ire_add_v[46].
8570 			 */
8571 
8572 			ire = ire_create_mp(
8573 			    (uchar_t *)&dst,		/* dest address */
8574 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8575 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8576 			    (uchar_t *)&gw,		/* gateway address */
8577 			    NULL,			/* ire_max_frag */
8578 			    NULL,			/* no src nce */
8579 			    dst_ill->ill_rq,		/* recv-from queue */
8580 			    dst_ill->ill_wq,		/* send-to queue */
8581 			    IRE_CACHE,
8582 			    src_ipif,			/* Interface ipif */
8583 			    save_ire->ire_mask,		/* Parent mask */
8584 			    0,
8585 			    save_ire->ire_ihandle,	/* Interface handle */
8586 			    0,				/* flags if any */
8587 			    &(save_ire->ire_uinfo),
8588 			    NULL,
8589 			    NULL,
8590 			    ipst);
8591 
8592 			if (ire == NULL) {
8593 				ire_refrele(save_ire);
8594 				break;
8595 			}
8596 
8597 			if ((sire != NULL) &&
8598 			    (sire->ire_flags & RTF_MULTIRT)) {
8599 				copy_mp = copymsg(first_mp);
8600 				if (copy_mp != NULL)
8601 					MULTIRT_DEBUG_TAG(copy_mp);
8602 			}
8603 
8604 			ire->ire_marks |= ire_marks;
8605 
8606 			/*
8607 			 * Construct message chain for the resolver
8608 			 * of the form:
8609 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8610 			 * Packet could contain a IPSEC_OUT mp.
8611 			 *
8612 			 * NOTE : ire will be added later when the response
8613 			 * comes back from ARP. If the response does not
8614 			 * come back, ARP frees the packet. For this reason,
8615 			 * we can't REFHOLD the bucket of save_ire to prevent
8616 			 * deletions. We may not be able to REFRELE the bucket
8617 			 * if the response never comes back. Thus, before
8618 			 * adding the ire, ire_add_v4 will make sure that the
8619 			 * interface route does not get deleted. This is the
8620 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8621 			 * where we can always prevent deletions because of
8622 			 * the synchronous nature of adding IRES i.e
8623 			 * ire_add_then_send is called after creating the IRE.
8624 			 */
8625 			ASSERT(ire->ire_mp != NULL);
8626 			ire->ire_mp->b_cont = first_mp;
8627 			/* Have saved_mp handy, for cleanup if canput fails */
8628 			saved_mp = mp;
8629 			mp = copyb(res_mp);
8630 			if (mp == NULL) {
8631 				/* Prepare for cleanup */
8632 				mp = saved_mp; /* pkt */
8633 				ire_delete(ire); /* ire_mp */
8634 				ire = NULL;
8635 				ire_refrele(save_ire);
8636 				if (copy_mp != NULL) {
8637 					MULTIRT_DEBUG_UNTAG(copy_mp);
8638 					freemsg(copy_mp);
8639 					copy_mp = NULL;
8640 				}
8641 				break;
8642 			}
8643 			linkb(mp, ire->ire_mp);
8644 
8645 			/*
8646 			 * Fill in the source and dest addrs for the resolver.
8647 			 * NOTE: this depends on memory layouts imposed by
8648 			 * ill_init().
8649 			 */
8650 			areq = (areq_t *)mp->b_rptr;
8651 			addrp = (ipaddr_t *)((char *)areq +
8652 			    areq->areq_sender_addr_offset);
8653 			*addrp = save_ire->ire_src_addr;
8654 
8655 			ire_refrele(save_ire);
8656 			addrp = (ipaddr_t *)((char *)areq +
8657 			    areq->areq_target_addr_offset);
8658 			*addrp = dst;
8659 			/* Up to the resolver. */
8660 			if (canputnext(dst_ill->ill_rq) &&
8661 			    !(dst_ill->ill_arp_closing)) {
8662 				putnext(dst_ill->ill_rq, mp);
8663 				ire = NULL;
8664 				if (copy_mp != NULL) {
8665 					/*
8666 					 * If we found a resolver, we ignore
8667 					 * any trailing top priority IRE_CACHE
8668 					 * in the further loops. This ensures
8669 					 * that we do not omit any resolver.
8670 					 * IRE_CACHE entries, if any, will be
8671 					 * processed next time we enter
8672 					 * ip_newroute().
8673 					 */
8674 					multirt_flags &= ~MULTIRT_CACHEGW;
8675 					/*
8676 					 * Search for the next unresolved
8677 					 * multirt route.
8678 					 */
8679 					first_mp = copy_mp;
8680 					copy_mp = NULL;
8681 					/* Prepare the next resolution loop. */
8682 					mp = first_mp;
8683 					EXTRACT_PKT_MP(mp, first_mp,
8684 					    mctl_present);
8685 					if (mctl_present)
8686 						io = (ipsec_out_t *)
8687 						    first_mp->b_rptr;
8688 					ipha = (ipha_t *)mp->b_rptr;
8689 
8690 					ASSERT(sire != NULL);
8691 
8692 					dst = save_dst;
8693 					multirt_resolve_next = B_TRUE;
8694 					continue;
8695 				}
8696 
8697 				if (sire != NULL)
8698 					ire_refrele(sire);
8699 
8700 				/*
8701 				 * The response will come back in ip_wput
8702 				 * with db_type IRE_DB_TYPE.
8703 				 */
8704 				ipif_refrele(src_ipif);
8705 				ill_refrele(dst_ill);
8706 				return;
8707 			} else {
8708 				/* Prepare for cleanup */
8709 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8710 				    mp);
8711 				mp->b_cont = NULL;
8712 				freeb(mp); /* areq */
8713 				/*
8714 				 * this is an ire that is not added to the
8715 				 * cache. ire_freemblk will handle the release
8716 				 * of any resources associated with the ire.
8717 				 */
8718 				ire_delete(ire); /* ire_mp */
8719 				mp = saved_mp; /* pkt */
8720 				ire = NULL;
8721 				if (copy_mp != NULL) {
8722 					MULTIRT_DEBUG_UNTAG(copy_mp);
8723 					freemsg(copy_mp);
8724 					copy_mp = NULL;
8725 				}
8726 				break;
8727 			}
8728 		default:
8729 			break;
8730 		}
8731 	} while (multirt_resolve_next);
8732 
8733 	ip1dbg(("ip_newroute: dropped\n"));
8734 	/* Did this packet originate externally? */
8735 	if (mp->b_prev) {
8736 		mp->b_next = NULL;
8737 		mp->b_prev = NULL;
8738 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8739 	} else {
8740 		if (dst_ill != NULL) {
8741 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8742 		} else {
8743 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8744 		}
8745 	}
8746 	ASSERT(copy_mp == NULL);
8747 	MULTIRT_DEBUG_UNTAG(first_mp);
8748 	freemsg(first_mp);
8749 	if (ire != NULL)
8750 		ire_refrele(ire);
8751 	if (sire != NULL)
8752 		ire_refrele(sire);
8753 	if (src_ipif != NULL)
8754 		ipif_refrele(src_ipif);
8755 	if (dst_ill != NULL)
8756 		ill_refrele(dst_ill);
8757 	return;
8758 
8759 icmp_err_ret:
8760 	ip1dbg(("ip_newroute: no route\n"));
8761 	if (src_ipif != NULL)
8762 		ipif_refrele(src_ipif);
8763 	if (dst_ill != NULL)
8764 		ill_refrele(dst_ill);
8765 	if (sire != NULL)
8766 		ire_refrele(sire);
8767 	/* Did this packet originate externally? */
8768 	if (mp->b_prev) {
8769 		mp->b_next = NULL;
8770 		mp->b_prev = NULL;
8771 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8772 		q = WR(q);
8773 	} else {
8774 		/*
8775 		 * There is no outgoing ill, so just increment the
8776 		 * system MIB.
8777 		 */
8778 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8779 		/*
8780 		 * Since ip_wput() isn't close to finished, we fill
8781 		 * in enough of the header for credible error reporting.
8782 		 */
8783 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8784 			/* Failed */
8785 			MULTIRT_DEBUG_UNTAG(first_mp);
8786 			freemsg(first_mp);
8787 			if (ire != NULL)
8788 				ire_refrele(ire);
8789 			return;
8790 		}
8791 	}
8792 
8793 	/*
8794 	 * At this point we will have ire only if RTF_BLACKHOLE
8795 	 * or RTF_REJECT flags are set on the IRE. It will not
8796 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8797 	 */
8798 	if (ire != NULL) {
8799 		if (ire->ire_flags & RTF_BLACKHOLE) {
8800 			ire_refrele(ire);
8801 			MULTIRT_DEBUG_UNTAG(first_mp);
8802 			freemsg(first_mp);
8803 			return;
8804 		}
8805 		ire_refrele(ire);
8806 	}
8807 	if (ip_source_routed(ipha, ipst)) {
8808 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8809 		    zoneid, ipst);
8810 		return;
8811 	}
8812 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8813 }
8814 
8815 ip_opt_info_t zero_info;
8816 
8817 /*
8818  * IPv4 -
8819  * ip_newroute_ipif is called by ip_wput_multicast and
8820  * ip_rput_forward_multicast whenever we need to send
8821  * out a packet to a destination address for which we do not have specific
8822  * routing information. It is used when the packet will be sent out
8823  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
8824  * socket option is set or icmp error message wants to go out on a particular
8825  * interface for a unicast packet.
8826  *
8827  * In most cases, the destination address is resolved thanks to the ipif
8828  * intrinsic resolver. However, there are some cases where the call to
8829  * ip_newroute_ipif must take into account the potential presence of
8830  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8831  * that uses the interface. This is specified through flags,
8832  * which can be a combination of:
8833  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8834  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8835  *   and flags. Additionally, the packet source address has to be set to
8836  *   the specified address. The caller is thus expected to set this flag
8837  *   if the packet has no specific source address yet.
8838  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8839  *   flag, the resulting ire will inherit the flag. All unresolved routes
8840  *   to the destination must be explored in the same call to
8841  *   ip_newroute_ipif().
8842  */
8843 static void
8844 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8845     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
8846 {
8847 	areq_t	*areq;
8848 	ire_t	*ire = NULL;
8849 	mblk_t	*res_mp;
8850 	ipaddr_t *addrp;
8851 	mblk_t *first_mp;
8852 	ire_t	*save_ire = NULL;
8853 	ipif_t	*src_ipif = NULL;
8854 	ushort_t ire_marks = 0;
8855 	ill_t	*dst_ill = NULL;
8856 	ipha_t *ipha;
8857 	mblk_t	*saved_mp;
8858 	ire_t   *fire = NULL;
8859 	mblk_t  *copy_mp = NULL;
8860 	boolean_t multirt_resolve_next;
8861 	boolean_t unspec_src;
8862 	ipaddr_t ipha_dst;
8863 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
8864 
8865 	/*
8866 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
8867 	 * here for uniformity
8868 	 */
8869 	ipif_refhold(ipif);
8870 
8871 	/*
8872 	 * This loop is run only once in most cases.
8873 	 * We loop to resolve further routes only when the destination
8874 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8875 	 */
8876 	do {
8877 		if (dst_ill != NULL) {
8878 			ill_refrele(dst_ill);
8879 			dst_ill = NULL;
8880 		}
8881 		if (src_ipif != NULL) {
8882 			ipif_refrele(src_ipif);
8883 			src_ipif = NULL;
8884 		}
8885 		multirt_resolve_next = B_FALSE;
8886 
8887 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
8888 		    ipif->ipif_ill->ill_name));
8889 
8890 		first_mp = mp;
8891 		if (DB_TYPE(mp) == M_CTL)
8892 			mp = mp->b_cont;
8893 		ipha = (ipha_t *)mp->b_rptr;
8894 
8895 		/*
8896 		 * Save the packet destination address, we may need it after
8897 		 * the packet has been consumed.
8898 		 */
8899 		ipha_dst = ipha->ipha_dst;
8900 
8901 		/*
8902 		 * If the interface is a pt-pt interface we look for an
8903 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
8904 		 * local_address and the pt-pt destination address. Otherwise
8905 		 * we just match the local address.
8906 		 * NOTE: dst could be different than ipha->ipha_dst in case
8907 		 * of sending igmp multicast packets over a point-to-point
8908 		 * connection.
8909 		 * Thus we must be careful enough to check ipha_dst to be a
8910 		 * multicast address, otherwise it will take xmit_if path for
8911 		 * multicast packets resulting into kernel stack overflow by
8912 		 * repeated calls to ip_newroute_ipif from ire_send().
8913 		 */
8914 		if (CLASSD(ipha_dst) &&
8915 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
8916 			goto err_ret;
8917 		}
8918 
8919 		/*
8920 		 * We check if an IRE_OFFSUBNET for the addr that goes through
8921 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
8922 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
8923 		 * propagate its flags to the new ire.
8924 		 */
8925 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
8926 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
8927 			ip2dbg(("ip_newroute_ipif: "
8928 			    "ipif_lookup_multi_ire("
8929 			    "ipif %p, dst %08x) = fire %p\n",
8930 			    (void *)ipif, ntohl(dst), (void *)fire));
8931 		}
8932 
8933 		/*
8934 		 * Note: While we pick a dst_ill we are really only
8935 		 * interested in the ill for load spreading. The source
8936 		 * ipif is determined by source address selection below.
8937 		 */
8938 		if (IS_IPMP(ipif->ipif_ill)) {
8939 			ipmp_illgrp_t *illg = ipif->ipif_ill->ill_grp;
8940 
8941 			if (CLASSD(ipha_dst))
8942 				dst_ill = ipmp_illgrp_hold_cast_ill(illg);
8943 			else
8944 				dst_ill = ipmp_illgrp_hold_next_ill(illg);
8945 		} else {
8946 			dst_ill = ipif->ipif_ill;
8947 			ill_refhold(dst_ill);
8948 		}
8949 
8950 		if (dst_ill == NULL) {
8951 			if (ip_debug > 2) {
8952 				pr_addr_dbg("ip_newroute_ipif: no dst ill "
8953 				    "for dst %s\n", AF_INET, &dst);
8954 			}
8955 			goto err_ret;
8956 		}
8957 
8958 		/*
8959 		 * Pick a source address preferring non-deprecated ones.
8960 		 * Unlike ip_newroute, we don't do any source address
8961 		 * selection here since for multicast it really does not help
8962 		 * in inbound load spreading as in the unicast case.
8963 		 */
8964 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
8965 		    (fire->ire_flags & RTF_SETSRC)) {
8966 			/*
8967 			 * As requested by flags, an IRE_OFFSUBNET was looked up
8968 			 * on that interface. This ire has RTF_SETSRC flag, so
8969 			 * the source address of the packet must be changed.
8970 			 * Check that the ipif matching the requested source
8971 			 * address still exists.
8972 			 */
8973 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
8974 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8975 		}
8976 
8977 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8978 
8979 		if (!IS_UNDER_IPMP(ipif->ipif_ill) &&
8980 		    (IS_IPMP(ipif->ipif_ill) ||
8981 		    (!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
8982 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
8983 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
8984 		    ipif->ipif_zoneid != ALL_ZONES)) &&
8985 		    (src_ipif == NULL) &&
8986 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8987 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
8988 			if (src_ipif == NULL) {
8989 				if (ip_debug > 2) {
8990 					/* ip1dbg */
8991 					pr_addr_dbg("ip_newroute_ipif: "
8992 					    "no src for dst %s",
8993 					    AF_INET, &dst);
8994 				}
8995 				ip1dbg((" on interface %s\n",
8996 				    dst_ill->ill_name));
8997 				goto err_ret;
8998 			}
8999 			ipif_refrele(ipif);
9000 			ipif = src_ipif;
9001 			ipif_refhold(ipif);
9002 		}
9003 		if (src_ipif == NULL) {
9004 			src_ipif = ipif;
9005 			ipif_refhold(src_ipif);
9006 		}
9007 
9008 		/*
9009 		 * Assign a source address while we have the conn.
9010 		 * We can't have ip_wput_ire pick a source address when the
9011 		 * packet returns from arp since conn_unspec_src might be set
9012 		 * and we lose the conn when going through arp.
9013 		 */
9014 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9015 			ipha->ipha_src = src_ipif->ipif_src_addr;
9016 
9017 		/*
9018 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9019 		 * that the outgoing interface does not have an interface ire.
9020 		 */
9021 		if (CLASSD(ipha_dst) && (connp == NULL ||
9022 		    connp->conn_outgoing_ill == NULL) &&
9023 		    infop->ip_opt_ill_index == 0) {
9024 			/* ipif_to_ire returns an held ire */
9025 			ire = ipif_to_ire(ipif);
9026 			if (ire == NULL)
9027 				goto err_ret;
9028 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9029 				goto err_ret;
9030 			save_ire = ire;
9031 
9032 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9033 			    "flags %04x\n",
9034 			    (void *)ire, (void *)ipif, flags));
9035 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9036 			    (fire->ire_flags & RTF_MULTIRT)) {
9037 				/*
9038 				 * As requested by flags, an IRE_OFFSUBNET was
9039 				 * looked up on that interface. This ire has
9040 				 * RTF_MULTIRT flag, so the resolution loop will
9041 				 * be re-entered to resolve additional routes on
9042 				 * other interfaces. For that purpose, a copy of
9043 				 * the packet is performed at this point.
9044 				 */
9045 				fire->ire_last_used_time = lbolt;
9046 				copy_mp = copymsg(first_mp);
9047 				if (copy_mp) {
9048 					MULTIRT_DEBUG_TAG(copy_mp);
9049 				}
9050 			}
9051 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9052 			    (fire->ire_flags & RTF_SETSRC)) {
9053 				/*
9054 				 * As requested by flags, an IRE_OFFSUBET was
9055 				 * looked up on that interface. This ire has
9056 				 * RTF_SETSRC flag, so the source address of the
9057 				 * packet must be changed.
9058 				 */
9059 				ipha->ipha_src = fire->ire_src_addr;
9060 			}
9061 		} else {
9062 			/*
9063 			 * The only ways we can come here are:
9064 			 * 1) IP_BOUND_IF socket option is set
9065 			 * 2) SO_DONTROUTE socket option is set
9066 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9067 			 * In all cases, the new ire will not be added
9068 			 * into cache table.
9069 			 */
9070 			ASSERT(connp == NULL || connp->conn_dontroute ||
9071 			    connp->conn_outgoing_ill != NULL ||
9072 			    infop->ip_opt_ill_index != 0);
9073 			ire_marks |= IRE_MARK_NOADD;
9074 		}
9075 
9076 		switch (ipif->ipif_net_type) {
9077 		case IRE_IF_NORESOLVER: {
9078 			/* We have what we need to build an IRE_CACHE. */
9079 
9080 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9081 			    (dst_ill->ill_resolver_mp == NULL)) {
9082 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9083 				    "for IRE_IF_NORESOLVER ire %p has "
9084 				    "no ill_resolver_mp\n",
9085 				    (void *)dst_ill, (void *)ire));
9086 				break;
9087 			}
9088 
9089 			/*
9090 			 * The new ire inherits the IRE_OFFSUBNET flags
9091 			 * and source address, if this was requested.
9092 			 */
9093 			ire = ire_create(
9094 			    (uchar_t *)&dst,		/* dest address */
9095 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9096 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9097 			    NULL,			/* gateway address */
9098 			    &ipif->ipif_mtu,
9099 			    NULL,			/* no src nce */
9100 			    dst_ill->ill_rq,		/* recv-from queue */
9101 			    dst_ill->ill_wq,		/* send-to queue */
9102 			    IRE_CACHE,
9103 			    src_ipif,
9104 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9105 			    (fire != NULL) ?		/* Parent handle */
9106 			    fire->ire_phandle : 0,
9107 			    (save_ire != NULL) ?	/* Interface handle */
9108 			    save_ire->ire_ihandle : 0,
9109 			    (fire != NULL) ?
9110 			    (fire->ire_flags &
9111 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9112 			    (save_ire == NULL ? &ire_uinfo_null :
9113 			    &save_ire->ire_uinfo),
9114 			    NULL,
9115 			    NULL,
9116 			    ipst);
9117 
9118 			if (ire == NULL) {
9119 				if (save_ire != NULL)
9120 					ire_refrele(save_ire);
9121 				break;
9122 			}
9123 
9124 			ire->ire_marks |= ire_marks;
9125 
9126 			/*
9127 			 * If IRE_MARK_NOADD is set then we need to convert
9128 			 * the max_fragp to a useable value now. This is
9129 			 * normally done in ire_add_v[46]. We also need to
9130 			 * associate the ire with an nce (normally would be
9131 			 * done in ip_wput_nondata()).
9132 			 *
9133 			 * Note that IRE_MARK_NOADD packets created here
9134 			 * do not have a non-null ire_mp pointer. The null
9135 			 * value of ire_bucket indicates that they were
9136 			 * never added.
9137 			 */
9138 			if (ire->ire_marks & IRE_MARK_NOADD) {
9139 				uint_t  max_frag;
9140 
9141 				max_frag = *ire->ire_max_fragp;
9142 				ire->ire_max_fragp = NULL;
9143 				ire->ire_max_frag = max_frag;
9144 
9145 				if ((ire->ire_nce = ndp_lookup_v4(
9146 				    ire_to_ill(ire),
9147 				    (ire->ire_gateway_addr != INADDR_ANY ?
9148 				    &ire->ire_gateway_addr : &ire->ire_addr),
9149 				    B_FALSE)) == NULL) {
9150 					if (save_ire != NULL)
9151 						ire_refrele(save_ire);
9152 					break;
9153 				}
9154 				ASSERT(ire->ire_nce->nce_state ==
9155 				    ND_REACHABLE);
9156 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9157 			}
9158 
9159 			/* Prevent save_ire from getting deleted */
9160 			if (save_ire != NULL) {
9161 				IRB_REFHOLD(save_ire->ire_bucket);
9162 				/* Has it been removed already ? */
9163 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9164 					IRB_REFRELE(save_ire->ire_bucket);
9165 					ire_refrele(save_ire);
9166 					break;
9167 				}
9168 			}
9169 
9170 			ire_add_then_send(q, ire, first_mp);
9171 
9172 			/* Assert that save_ire is not deleted yet. */
9173 			if (save_ire != NULL) {
9174 				ASSERT(save_ire->ire_ptpn != NULL);
9175 				IRB_REFRELE(save_ire->ire_bucket);
9176 				ire_refrele(save_ire);
9177 				save_ire = NULL;
9178 			}
9179 			if (fire != NULL) {
9180 				ire_refrele(fire);
9181 				fire = NULL;
9182 			}
9183 
9184 			/*
9185 			 * the resolution loop is re-entered if this
9186 			 * was requested through flags and if we
9187 			 * actually are in a multirouting case.
9188 			 */
9189 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9190 				boolean_t need_resolve =
9191 				    ire_multirt_need_resolve(ipha_dst,
9192 				    MBLK_GETLABEL(copy_mp), ipst);
9193 				if (!need_resolve) {
9194 					MULTIRT_DEBUG_UNTAG(copy_mp);
9195 					freemsg(copy_mp);
9196 					copy_mp = NULL;
9197 				} else {
9198 					/*
9199 					 * ipif_lookup_group() calls
9200 					 * ire_lookup_multi() that uses
9201 					 * ire_ftable_lookup() to find
9202 					 * an IRE_INTERFACE for the group.
9203 					 * In the multirt case,
9204 					 * ire_lookup_multi() then invokes
9205 					 * ire_multirt_lookup() to find
9206 					 * the next resolvable ire.
9207 					 * As a result, we obtain an new
9208 					 * interface, derived from the
9209 					 * next ire.
9210 					 */
9211 					ipif_refrele(ipif);
9212 					ipif = ipif_lookup_group(ipha_dst,
9213 					    zoneid, ipst);
9214 					ip2dbg(("ip_newroute_ipif: "
9215 					    "multirt dst %08x, ipif %p\n",
9216 					    htonl(dst), (void *)ipif));
9217 					if (ipif != NULL) {
9218 						mp = copy_mp;
9219 						copy_mp = NULL;
9220 						multirt_resolve_next = B_TRUE;
9221 						continue;
9222 					} else {
9223 						freemsg(copy_mp);
9224 					}
9225 				}
9226 			}
9227 			if (ipif != NULL)
9228 				ipif_refrele(ipif);
9229 			ill_refrele(dst_ill);
9230 			ipif_refrele(src_ipif);
9231 			return;
9232 		}
9233 		case IRE_IF_RESOLVER:
9234 			/*
9235 			 * We can't build an IRE_CACHE yet, but at least
9236 			 * we found a resolver that can help.
9237 			 */
9238 			res_mp = dst_ill->ill_resolver_mp;
9239 			if (!OK_RESOLVER_MP(res_mp))
9240 				break;
9241 
9242 			/*
9243 			 * We obtain a partial IRE_CACHE which we will pass
9244 			 * along with the resolver query.  When the response
9245 			 * comes back it will be there ready for us to add.
9246 			 * The new ire inherits the IRE_OFFSUBNET flags
9247 			 * and source address, if this was requested.
9248 			 * The ire_max_frag is atomically set under the
9249 			 * irebucket lock in ire_add_v[46]. Only in the
9250 			 * case of IRE_MARK_NOADD, we set it here itself.
9251 			 */
9252 			ire = ire_create_mp(
9253 			    (uchar_t *)&dst,		/* dest address */
9254 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9255 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9256 			    NULL,			/* gateway address */
9257 			    (ire_marks & IRE_MARK_NOADD) ?
9258 			    ipif->ipif_mtu : 0,		/* max_frag */
9259 			    NULL,			/* no src nce */
9260 			    dst_ill->ill_rq,		/* recv-from queue */
9261 			    dst_ill->ill_wq,		/* send-to queue */
9262 			    IRE_CACHE,
9263 			    src_ipif,
9264 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9265 			    (fire != NULL) ?		/* Parent handle */
9266 			    fire->ire_phandle : 0,
9267 			    (save_ire != NULL) ?	/* Interface handle */
9268 			    save_ire->ire_ihandle : 0,
9269 			    (fire != NULL) ?		/* flags if any */
9270 			    (fire->ire_flags &
9271 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9272 			    (save_ire == NULL ? &ire_uinfo_null :
9273 			    &save_ire->ire_uinfo),
9274 			    NULL,
9275 			    NULL,
9276 			    ipst);
9277 
9278 			if (save_ire != NULL) {
9279 				ire_refrele(save_ire);
9280 				save_ire = NULL;
9281 			}
9282 			if (ire == NULL)
9283 				break;
9284 
9285 			ire->ire_marks |= ire_marks;
9286 			/*
9287 			 * Construct message chain for the resolver of the
9288 			 * form:
9289 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9290 			 *
9291 			 * NOTE : ire will be added later when the response
9292 			 * comes back from ARP. If the response does not
9293 			 * come back, ARP frees the packet. For this reason,
9294 			 * we can't REFHOLD the bucket of save_ire to prevent
9295 			 * deletions. We may not be able to REFRELE the
9296 			 * bucket if the response never comes back.
9297 			 * Thus, before adding the ire, ire_add_v4 will make
9298 			 * sure that the interface route does not get deleted.
9299 			 * This is the only case unlike ip_newroute_v6,
9300 			 * ip_newroute_ipif_v6 where we can always prevent
9301 			 * deletions because ire_add_then_send is called after
9302 			 * creating the IRE.
9303 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9304 			 * does not add this IRE into the IRE CACHE.
9305 			 */
9306 			ASSERT(ire->ire_mp != NULL);
9307 			ire->ire_mp->b_cont = first_mp;
9308 			/* Have saved_mp handy, for cleanup if canput fails */
9309 			saved_mp = mp;
9310 			mp = copyb(res_mp);
9311 			if (mp == NULL) {
9312 				/* Prepare for cleanup */
9313 				mp = saved_mp; /* pkt */
9314 				ire_delete(ire); /* ire_mp */
9315 				ire = NULL;
9316 				if (copy_mp != NULL) {
9317 					MULTIRT_DEBUG_UNTAG(copy_mp);
9318 					freemsg(copy_mp);
9319 					copy_mp = NULL;
9320 				}
9321 				break;
9322 			}
9323 			linkb(mp, ire->ire_mp);
9324 
9325 			/*
9326 			 * Fill in the source and dest addrs for the resolver.
9327 			 * NOTE: this depends on memory layouts imposed by
9328 			 * ill_init().  There are corner cases above where we
9329 			 * might've created the IRE with an INADDR_ANY source
9330 			 * address (e.g., if the zeroth ipif on an underlying
9331 			 * ill in an IPMP group is 0.0.0.0, but another ipif
9332 			 * on the ill has a usable test address).  If so, tell
9333 			 * ARP to use ipha_src as its sender address.
9334 			 */
9335 			areq = (areq_t *)mp->b_rptr;
9336 			addrp = (ipaddr_t *)((char *)areq +
9337 			    areq->areq_sender_addr_offset);
9338 			if (ire->ire_src_addr != INADDR_ANY)
9339 				*addrp = ire->ire_src_addr;
9340 			else
9341 				*addrp = ipha->ipha_src;
9342 			addrp = (ipaddr_t *)((char *)areq +
9343 			    areq->areq_target_addr_offset);
9344 			*addrp = dst;
9345 			/* Up to the resolver. */
9346 			if (canputnext(dst_ill->ill_rq) &&
9347 			    !(dst_ill->ill_arp_closing)) {
9348 				putnext(dst_ill->ill_rq, mp);
9349 				/*
9350 				 * The response will come back in ip_wput
9351 				 * with db_type IRE_DB_TYPE.
9352 				 */
9353 			} else {
9354 				mp->b_cont = NULL;
9355 				freeb(mp); /* areq */
9356 				ire_delete(ire); /* ire_mp */
9357 				saved_mp->b_next = NULL;
9358 				saved_mp->b_prev = NULL;
9359 				freemsg(first_mp); /* pkt */
9360 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9361 			}
9362 
9363 			if (fire != NULL) {
9364 				ire_refrele(fire);
9365 				fire = NULL;
9366 			}
9367 
9368 			/*
9369 			 * The resolution loop is re-entered if this was
9370 			 * requested through flags and we actually are
9371 			 * in a multirouting case.
9372 			 */
9373 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9374 				boolean_t need_resolve =
9375 				    ire_multirt_need_resolve(ipha_dst,
9376 				    MBLK_GETLABEL(copy_mp), ipst);
9377 				if (!need_resolve) {
9378 					MULTIRT_DEBUG_UNTAG(copy_mp);
9379 					freemsg(copy_mp);
9380 					copy_mp = NULL;
9381 				} else {
9382 					/*
9383 					 * ipif_lookup_group() calls
9384 					 * ire_lookup_multi() that uses
9385 					 * ire_ftable_lookup() to find
9386 					 * an IRE_INTERFACE for the group.
9387 					 * In the multirt case,
9388 					 * ire_lookup_multi() then invokes
9389 					 * ire_multirt_lookup() to find
9390 					 * the next resolvable ire.
9391 					 * As a result, we obtain an new
9392 					 * interface, derived from the
9393 					 * next ire.
9394 					 */
9395 					ipif_refrele(ipif);
9396 					ipif = ipif_lookup_group(ipha_dst,
9397 					    zoneid, ipst);
9398 					if (ipif != NULL) {
9399 						mp = copy_mp;
9400 						copy_mp = NULL;
9401 						multirt_resolve_next = B_TRUE;
9402 						continue;
9403 					} else {
9404 						freemsg(copy_mp);
9405 					}
9406 				}
9407 			}
9408 			if (ipif != NULL)
9409 				ipif_refrele(ipif);
9410 			ill_refrele(dst_ill);
9411 			ipif_refrele(src_ipif);
9412 			return;
9413 		default:
9414 			break;
9415 		}
9416 	} while (multirt_resolve_next);
9417 
9418 err_ret:
9419 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9420 	if (fire != NULL)
9421 		ire_refrele(fire);
9422 	ipif_refrele(ipif);
9423 	/* Did this packet originate externally? */
9424 	if (dst_ill != NULL)
9425 		ill_refrele(dst_ill);
9426 	if (src_ipif != NULL)
9427 		ipif_refrele(src_ipif);
9428 	if (mp->b_prev || mp->b_next) {
9429 		mp->b_next = NULL;
9430 		mp->b_prev = NULL;
9431 	} else {
9432 		/*
9433 		 * Since ip_wput() isn't close to finished, we fill
9434 		 * in enough of the header for credible error reporting.
9435 		 */
9436 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9437 			/* Failed */
9438 			freemsg(first_mp);
9439 			if (ire != NULL)
9440 				ire_refrele(ire);
9441 			return;
9442 		}
9443 	}
9444 	/*
9445 	 * At this point we will have ire only if RTF_BLACKHOLE
9446 	 * or RTF_REJECT flags are set on the IRE. It will not
9447 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9448 	 */
9449 	if (ire != NULL) {
9450 		if (ire->ire_flags & RTF_BLACKHOLE) {
9451 			ire_refrele(ire);
9452 			freemsg(first_mp);
9453 			return;
9454 		}
9455 		ire_refrele(ire);
9456 	}
9457 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9458 }
9459 
9460 /* Name/Value Table Lookup Routine */
9461 char *
9462 ip_nv_lookup(nv_t *nv, int value)
9463 {
9464 	if (!nv)
9465 		return (NULL);
9466 	for (; nv->nv_name; nv++) {
9467 		if (nv->nv_value == value)
9468 			return (nv->nv_name);
9469 	}
9470 	return ("unknown");
9471 }
9472 
9473 /*
9474  * This is a module open, i.e. this is a control stream for access
9475  * to a DLPI device.  We allocate an ill_t as the instance data in
9476  * this case.
9477  */
9478 int
9479 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9480 {
9481 	ill_t	*ill;
9482 	int	err;
9483 	zoneid_t zoneid;
9484 	netstack_t *ns;
9485 	ip_stack_t *ipst;
9486 
9487 	/*
9488 	 * Prevent unprivileged processes from pushing IP so that
9489 	 * they can't send raw IP.
9490 	 */
9491 	if (secpolicy_net_rawaccess(credp) != 0)
9492 		return (EPERM);
9493 
9494 	ns = netstack_find_by_cred(credp);
9495 	ASSERT(ns != NULL);
9496 	ipst = ns->netstack_ip;
9497 	ASSERT(ipst != NULL);
9498 
9499 	/*
9500 	 * For exclusive stacks we set the zoneid to zero
9501 	 * to make IP operate as if in the global zone.
9502 	 */
9503 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9504 		zoneid = GLOBAL_ZONEID;
9505 	else
9506 		zoneid = crgetzoneid(credp);
9507 
9508 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9509 	q->q_ptr = WR(q)->q_ptr = ill;
9510 	ill->ill_ipst = ipst;
9511 	ill->ill_zoneid = zoneid;
9512 
9513 	/*
9514 	 * ill_init initializes the ill fields and then sends down
9515 	 * down a DL_INFO_REQ after calling qprocson.
9516 	 */
9517 	err = ill_init(q, ill);
9518 	if (err != 0) {
9519 		mi_free(ill);
9520 		netstack_rele(ipst->ips_netstack);
9521 		q->q_ptr = NULL;
9522 		WR(q)->q_ptr = NULL;
9523 		return (err);
9524 	}
9525 
9526 	/* ill_init initializes the ipsq marking this thread as writer */
9527 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
9528 	/* Wait for the DL_INFO_ACK */
9529 	mutex_enter(&ill->ill_lock);
9530 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9531 		/*
9532 		 * Return value of 0 indicates a pending signal.
9533 		 */
9534 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9535 		if (err == 0) {
9536 			mutex_exit(&ill->ill_lock);
9537 			(void) ip_close(q, 0);
9538 			return (EINTR);
9539 		}
9540 	}
9541 	mutex_exit(&ill->ill_lock);
9542 
9543 	/*
9544 	 * ip_rput_other could have set an error  in ill_error on
9545 	 * receipt of M_ERROR.
9546 	 */
9547 
9548 	err = ill->ill_error;
9549 	if (err != 0) {
9550 		(void) ip_close(q, 0);
9551 		return (err);
9552 	}
9553 
9554 	ill->ill_credp = credp;
9555 	crhold(credp);
9556 
9557 	mutex_enter(&ipst->ips_ip_mi_lock);
9558 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9559 	    credp);
9560 	mutex_exit(&ipst->ips_ip_mi_lock);
9561 	if (err) {
9562 		(void) ip_close(q, 0);
9563 		return (err);
9564 	}
9565 	return (0);
9566 }
9567 
9568 /* For /dev/ip aka AF_INET open */
9569 int
9570 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9571 {
9572 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9573 }
9574 
9575 /* For /dev/ip6 aka AF_INET6 open */
9576 int
9577 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9578 {
9579 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9580 }
9581 
9582 /* IP open routine. */
9583 int
9584 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9585     boolean_t isv6)
9586 {
9587 	conn_t 		*connp;
9588 	major_t		maj;
9589 	zoneid_t	zoneid;
9590 	netstack_t	*ns;
9591 	ip_stack_t	*ipst;
9592 
9593 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9594 
9595 	/* Allow reopen. */
9596 	if (q->q_ptr != NULL)
9597 		return (0);
9598 
9599 	if (sflag & MODOPEN) {
9600 		/* This is a module open */
9601 		return (ip_modopen(q, devp, flag, sflag, credp));
9602 	}
9603 
9604 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
9605 		/*
9606 		 * Non streams based socket looking for a stream
9607 		 * to access IP
9608 		 */
9609 		return (ip_helper_stream_setup(q, devp, flag, sflag,
9610 		    credp, isv6));
9611 	}
9612 
9613 	ns = netstack_find_by_cred(credp);
9614 	ASSERT(ns != NULL);
9615 	ipst = ns->netstack_ip;
9616 	ASSERT(ipst != NULL);
9617 
9618 	/*
9619 	 * For exclusive stacks we set the zoneid to zero
9620 	 * to make IP operate as if in the global zone.
9621 	 */
9622 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9623 		zoneid = GLOBAL_ZONEID;
9624 	else
9625 		zoneid = crgetzoneid(credp);
9626 
9627 	/*
9628 	 * We are opening as a device. This is an IP client stream, and we
9629 	 * allocate an conn_t as the instance data.
9630 	 */
9631 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9632 
9633 	/*
9634 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9635 	 * done by netstack_find_by_cred()
9636 	 */
9637 	netstack_rele(ipst->ips_netstack);
9638 
9639 	connp->conn_zoneid = zoneid;
9640 	connp->conn_sqp = NULL;
9641 	connp->conn_initial_sqp = NULL;
9642 	connp->conn_final_sqp = NULL;
9643 
9644 	connp->conn_upq = q;
9645 	q->q_ptr = WR(q)->q_ptr = connp;
9646 
9647 	if (flag & SO_SOCKSTR)
9648 		connp->conn_flags |= IPCL_SOCKET;
9649 
9650 	/* Minor tells us which /dev entry was opened */
9651 	if (isv6) {
9652 		connp->conn_flags |= IPCL_ISV6;
9653 		connp->conn_af_isv6 = B_TRUE;
9654 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9655 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9656 	} else {
9657 		connp->conn_af_isv6 = B_FALSE;
9658 		connp->conn_pkt_isv6 = B_FALSE;
9659 	}
9660 
9661 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9662 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9663 		connp->conn_minor_arena = ip_minor_arena_la;
9664 	} else {
9665 		/*
9666 		 * Either minor numbers in the large arena were exhausted
9667 		 * or a non socket application is doing the open.
9668 		 * Try to allocate from the small arena.
9669 		 */
9670 		if ((connp->conn_dev =
9671 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9672 			/* CONN_DEC_REF takes care of netstack_rele() */
9673 			q->q_ptr = WR(q)->q_ptr = NULL;
9674 			CONN_DEC_REF(connp);
9675 			return (EBUSY);
9676 		}
9677 		connp->conn_minor_arena = ip_minor_arena_sa;
9678 	}
9679 
9680 	maj = getemajor(*devp);
9681 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9682 
9683 	/*
9684 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9685 	 */
9686 	connp->conn_cred = credp;
9687 
9688 	/*
9689 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9690 	 */
9691 	connp->conn_recv = ip_conn_input;
9692 
9693 	crhold(connp->conn_cred);
9694 
9695 	/*
9696 	 * If the caller has the process-wide flag set, then default to MAC
9697 	 * exempt mode.  This allows read-down to unlabeled hosts.
9698 	 */
9699 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9700 		connp->conn_mac_exempt = B_TRUE;
9701 
9702 	connp->conn_rq = q;
9703 	connp->conn_wq = WR(q);
9704 
9705 	/* Non-zero default values */
9706 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9707 
9708 	/*
9709 	 * Make the conn globally visible to walkers
9710 	 */
9711 	ASSERT(connp->conn_ref == 1);
9712 	mutex_enter(&connp->conn_lock);
9713 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9714 	mutex_exit(&connp->conn_lock);
9715 
9716 	qprocson(q);
9717 
9718 	return (0);
9719 }
9720 
9721 /*
9722  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9723  * Note that there is no race since either ip_output function works - it
9724  * is just an optimization to enter the best ip_output routine directly.
9725  */
9726 void
9727 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9728     ip_stack_t *ipst)
9729 {
9730 	if (isv6)  {
9731 		if (bump_mib) {
9732 			BUMP_MIB(&ipst->ips_ip6_mib,
9733 			    ipIfStatsOutSwitchIPVersion);
9734 		}
9735 		connp->conn_send = ip_output_v6;
9736 		connp->conn_pkt_isv6 = B_TRUE;
9737 	} else {
9738 		if (bump_mib) {
9739 			BUMP_MIB(&ipst->ips_ip_mib,
9740 			    ipIfStatsOutSwitchIPVersion);
9741 		}
9742 		connp->conn_send = ip_output;
9743 		connp->conn_pkt_isv6 = B_FALSE;
9744 	}
9745 
9746 }
9747 
9748 /*
9749  * See if IPsec needs loading because of the options in mp.
9750  */
9751 static boolean_t
9752 ipsec_opt_present(mblk_t *mp)
9753 {
9754 	uint8_t *optcp, *next_optcp, *opt_endcp;
9755 	struct opthdr *opt;
9756 	struct T_opthdr *topt;
9757 	int opthdr_len;
9758 	t_uscalar_t optname, optlevel;
9759 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9760 	ipsec_req_t *ipsr;
9761 
9762 	/*
9763 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9764 	 * return TRUE.
9765 	 */
9766 
9767 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9768 	opt_endcp = optcp + tor->OPT_length;
9769 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9770 		opthdr_len = sizeof (struct T_opthdr);
9771 	} else {		/* O_OPTMGMT_REQ */
9772 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9773 		opthdr_len = sizeof (struct opthdr);
9774 	}
9775 	for (; optcp < opt_endcp; optcp = next_optcp) {
9776 		if (optcp + opthdr_len > opt_endcp)
9777 			return (B_FALSE);	/* Not enough option header. */
9778 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9779 			topt = (struct T_opthdr *)optcp;
9780 			optlevel = topt->level;
9781 			optname = topt->name;
9782 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9783 		} else {
9784 			opt = (struct opthdr *)optcp;
9785 			optlevel = opt->level;
9786 			optname = opt->name;
9787 			next_optcp = optcp + opthdr_len +
9788 			    _TPI_ALIGN_OPT(opt->len);
9789 		}
9790 		if ((next_optcp < optcp) || /* wraparound pointer space */
9791 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9792 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9793 			return (B_FALSE); /* bad option buffer */
9794 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9795 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9796 			/*
9797 			 * Check to see if it's an all-bypass or all-zeroes
9798 			 * IPsec request.  Don't bother loading IPsec if
9799 			 * the socket doesn't want to use it.  (A good example
9800 			 * is a bypass request.)
9801 			 *
9802 			 * Basically, if any of the non-NEVER bits are set,
9803 			 * load IPsec.
9804 			 */
9805 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9806 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9807 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9808 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9809 			    != 0)
9810 				return (B_TRUE);
9811 		}
9812 	}
9813 	return (B_FALSE);
9814 }
9815 
9816 /*
9817  * If conn is is waiting for ipsec to finish loading, kick it.
9818  */
9819 /* ARGSUSED */
9820 static void
9821 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9822 {
9823 	t_scalar_t	optreq_prim;
9824 	mblk_t		*mp;
9825 	cred_t		*cr;
9826 	int		err = 0;
9827 
9828 	/*
9829 	 * This function is called, after ipsec loading is complete.
9830 	 * Since IP checks exclusively and atomically (i.e it prevents
9831 	 * ipsec load from completing until ip_optcom_req completes)
9832 	 * whether ipsec load is complete, there cannot be a race with IP
9833 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9834 	 */
9835 	mutex_enter(&connp->conn_lock);
9836 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9837 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9838 		mp = connp->conn_ipsec_opt_mp;
9839 		connp->conn_ipsec_opt_mp = NULL;
9840 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9841 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
9842 		mutex_exit(&connp->conn_lock);
9843 
9844 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9845 
9846 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9847 		if (optreq_prim == T_OPTMGMT_REQ) {
9848 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9849 			    &ip_opt_obj, B_FALSE);
9850 		} else {
9851 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9852 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9853 			    &ip_opt_obj, B_FALSE);
9854 		}
9855 		if (err != EINPROGRESS)
9856 			CONN_OPER_PENDING_DONE(connp);
9857 		return;
9858 	}
9859 	mutex_exit(&connp->conn_lock);
9860 }
9861 
9862 /*
9863  * Called from the ipsec_loader thread, outside any perimeter, to tell
9864  * ip qenable any of the queues waiting for the ipsec loader to
9865  * complete.
9866  */
9867 void
9868 ip_ipsec_load_complete(ipsec_stack_t *ipss)
9869 {
9870 	netstack_t *ns = ipss->ipsec_netstack;
9871 
9872 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
9873 }
9874 
9875 /*
9876  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
9877  * determines the grp on which it has to become exclusive, queues the mp
9878  * and IPSQ draining restarts the optmgmt
9879  */
9880 static boolean_t
9881 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
9882 {
9883 	conn_t *connp = Q_TO_CONN(q);
9884 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
9885 
9886 	/*
9887 	 * Take IPsec requests and treat them special.
9888 	 */
9889 	if (ipsec_opt_present(mp)) {
9890 		/* First check if IPsec is loaded. */
9891 		mutex_enter(&ipss->ipsec_loader_lock);
9892 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
9893 			mutex_exit(&ipss->ipsec_loader_lock);
9894 			return (B_FALSE);
9895 		}
9896 		mutex_enter(&connp->conn_lock);
9897 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
9898 
9899 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
9900 		connp->conn_ipsec_opt_mp = mp;
9901 		mutex_exit(&connp->conn_lock);
9902 		mutex_exit(&ipss->ipsec_loader_lock);
9903 
9904 		ipsec_loader_loadnow(ipss);
9905 		return (B_TRUE);
9906 	}
9907 	return (B_FALSE);
9908 }
9909 
9910 /*
9911  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
9912  * all of them are copied to the conn_t. If the req is "zero", the policy is
9913  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
9914  * fields.
9915  * We keep only the latest setting of the policy and thus policy setting
9916  * is not incremental/cumulative.
9917  *
9918  * Requests to set policies with multiple alternative actions will
9919  * go through a different API.
9920  */
9921 int
9922 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
9923 {
9924 	uint_t ah_req = 0;
9925 	uint_t esp_req = 0;
9926 	uint_t se_req = 0;
9927 	ipsec_selkey_t sel;
9928 	ipsec_act_t *actp = NULL;
9929 	uint_t nact;
9930 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
9931 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
9932 	ipsec_policy_root_t *pr;
9933 	ipsec_policy_head_t *ph;
9934 	int fam;
9935 	boolean_t is_pol_reset;
9936 	int error = 0;
9937 	netstack_t	*ns = connp->conn_netstack;
9938 	ip_stack_t	*ipst = ns->netstack_ip;
9939 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
9940 
9941 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
9942 
9943 	/*
9944 	 * The IP_SEC_OPT option does not allow variable length parameters,
9945 	 * hence a request cannot be NULL.
9946 	 */
9947 	if (req == NULL)
9948 		return (EINVAL);
9949 
9950 	ah_req = req->ipsr_ah_req;
9951 	esp_req = req->ipsr_esp_req;
9952 	se_req = req->ipsr_self_encap_req;
9953 
9954 	/* Don't allow setting self-encap without one or more of AH/ESP. */
9955 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
9956 		return (EINVAL);
9957 
9958 	/*
9959 	 * Are we dealing with a request to reset the policy (i.e.
9960 	 * zero requests).
9961 	 */
9962 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
9963 	    (esp_req & REQ_MASK) == 0 &&
9964 	    (se_req & REQ_MASK) == 0);
9965 
9966 	if (!is_pol_reset) {
9967 		/*
9968 		 * If we couldn't load IPsec, fail with "protocol
9969 		 * not supported".
9970 		 * IPsec may not have been loaded for a request with zero
9971 		 * policies, so we don't fail in this case.
9972 		 */
9973 		mutex_enter(&ipss->ipsec_loader_lock);
9974 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
9975 			mutex_exit(&ipss->ipsec_loader_lock);
9976 			return (EPROTONOSUPPORT);
9977 		}
9978 		mutex_exit(&ipss->ipsec_loader_lock);
9979 
9980 		/*
9981 		 * Test for valid requests. Invalid algorithms
9982 		 * need to be tested by IPsec code because new
9983 		 * algorithms can be added dynamically.
9984 		 */
9985 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9986 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9987 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
9988 			return (EINVAL);
9989 		}
9990 
9991 		/*
9992 		 * Only privileged users can issue these
9993 		 * requests.
9994 		 */
9995 		if (((ah_req & IPSEC_PREF_NEVER) ||
9996 		    (esp_req & IPSEC_PREF_NEVER) ||
9997 		    (se_req & IPSEC_PREF_NEVER)) &&
9998 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
9999 			return (EPERM);
10000 		}
10001 
10002 		/*
10003 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10004 		 * are mutually exclusive.
10005 		 */
10006 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10007 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10008 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10009 			/* Both of them are set */
10010 			return (EINVAL);
10011 		}
10012 	}
10013 
10014 	mutex_enter(&connp->conn_lock);
10015 
10016 	/*
10017 	 * If we have already cached policies in ip_bind_connected*(), don't
10018 	 * let them change now. We cache policies for connections
10019 	 * whose src,dst [addr, port] is known.
10020 	 */
10021 	if (connp->conn_policy_cached) {
10022 		mutex_exit(&connp->conn_lock);
10023 		return (EINVAL);
10024 	}
10025 
10026 	/*
10027 	 * We have a zero policies, reset the connection policy if already
10028 	 * set. This will cause the connection to inherit the
10029 	 * global policy, if any.
10030 	 */
10031 	if (is_pol_reset) {
10032 		if (connp->conn_policy != NULL) {
10033 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10034 			connp->conn_policy = NULL;
10035 		}
10036 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10037 		connp->conn_in_enforce_policy = B_FALSE;
10038 		connp->conn_out_enforce_policy = B_FALSE;
10039 		mutex_exit(&connp->conn_lock);
10040 		return (0);
10041 	}
10042 
10043 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10044 	    ipst->ips_netstack);
10045 	if (ph == NULL)
10046 		goto enomem;
10047 
10048 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10049 	if (actp == NULL)
10050 		goto enomem;
10051 
10052 	/*
10053 	 * Always allocate IPv4 policy entries, since they can also
10054 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10055 	 */
10056 	bzero(&sel, sizeof (sel));
10057 	sel.ipsl_valid = IPSL_IPV4;
10058 
10059 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10060 	    ipst->ips_netstack);
10061 	if (pin4 == NULL)
10062 		goto enomem;
10063 
10064 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10065 	    ipst->ips_netstack);
10066 	if (pout4 == NULL)
10067 		goto enomem;
10068 
10069 	if (connp->conn_af_isv6) {
10070 		/*
10071 		 * We're looking at a v6 socket, also allocate the
10072 		 * v6-specific entries...
10073 		 */
10074 		sel.ipsl_valid = IPSL_IPV6;
10075 		pin6 = ipsec_policy_create(&sel, actp, nact,
10076 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10077 		if (pin6 == NULL)
10078 			goto enomem;
10079 
10080 		pout6 = ipsec_policy_create(&sel, actp, nact,
10081 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10082 		if (pout6 == NULL)
10083 			goto enomem;
10084 
10085 		/*
10086 		 * .. and file them away in the right place.
10087 		 */
10088 		fam = IPSEC_AF_V6;
10089 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10090 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10091 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10092 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10093 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10094 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10095 	}
10096 
10097 	ipsec_actvec_free(actp, nact);
10098 
10099 	/*
10100 	 * File the v4 policies.
10101 	 */
10102 	fam = IPSEC_AF_V4;
10103 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10104 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10105 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10106 
10107 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10108 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10109 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10110 
10111 	/*
10112 	 * If the requests need security, set enforce_policy.
10113 	 * If the requests are IPSEC_PREF_NEVER, one should
10114 	 * still set conn_out_enforce_policy so that an ipsec_out
10115 	 * gets attached in ip_wput. This is needed so that
10116 	 * for connections that we don't cache policy in ip_bind,
10117 	 * if global policy matches in ip_wput_attach_policy, we
10118 	 * don't wrongly inherit global policy. Similarly, we need
10119 	 * to set conn_in_enforce_policy also so that we don't verify
10120 	 * policy wrongly.
10121 	 */
10122 	if ((ah_req & REQ_MASK) != 0 ||
10123 	    (esp_req & REQ_MASK) != 0 ||
10124 	    (se_req & REQ_MASK) != 0) {
10125 		connp->conn_in_enforce_policy = B_TRUE;
10126 		connp->conn_out_enforce_policy = B_TRUE;
10127 		connp->conn_flags |= IPCL_CHECK_POLICY;
10128 	}
10129 
10130 	mutex_exit(&connp->conn_lock);
10131 	return (error);
10132 #undef REQ_MASK
10133 
10134 	/*
10135 	 * Common memory-allocation-failure exit path.
10136 	 */
10137 enomem:
10138 	mutex_exit(&connp->conn_lock);
10139 	if (actp != NULL)
10140 		ipsec_actvec_free(actp, nact);
10141 	if (pin4 != NULL)
10142 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10143 	if (pout4 != NULL)
10144 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10145 	if (pin6 != NULL)
10146 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10147 	if (pout6 != NULL)
10148 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10149 	return (ENOMEM);
10150 }
10151 
10152 /*
10153  * Only for options that pass in an IP addr. Currently only V4 options
10154  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10155  * So this function assumes level is IPPROTO_IP
10156  */
10157 int
10158 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10159     mblk_t *first_mp)
10160 {
10161 	ipif_t *ipif = NULL;
10162 	int error;
10163 	ill_t *ill;
10164 	int zoneid;
10165 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10166 
10167 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10168 
10169 	if (addr != INADDR_ANY || checkonly) {
10170 		ASSERT(connp != NULL);
10171 		zoneid = IPCL_ZONEID(connp);
10172 		if (option == IP_NEXTHOP) {
10173 			ipif = ipif_lookup_onlink_addr(addr,
10174 			    connp->conn_zoneid, ipst);
10175 		} else {
10176 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10177 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10178 			    &error, ipst);
10179 		}
10180 		if (ipif == NULL) {
10181 			if (error == EINPROGRESS)
10182 				return (error);
10183 			if ((option == IP_MULTICAST_IF) ||
10184 			    (option == IP_NEXTHOP))
10185 				return (EHOSTUNREACH);
10186 			else
10187 				return (EINVAL);
10188 		} else if (checkonly) {
10189 			if (option == IP_MULTICAST_IF) {
10190 				ill = ipif->ipif_ill;
10191 				/* not supported by the virtual network iface */
10192 				if (IS_VNI(ill)) {
10193 					ipif_refrele(ipif);
10194 					return (EINVAL);
10195 				}
10196 			}
10197 			ipif_refrele(ipif);
10198 			return (0);
10199 		}
10200 		ill = ipif->ipif_ill;
10201 		mutex_enter(&connp->conn_lock);
10202 		mutex_enter(&ill->ill_lock);
10203 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10204 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10205 			mutex_exit(&ill->ill_lock);
10206 			mutex_exit(&connp->conn_lock);
10207 			ipif_refrele(ipif);
10208 			return (option == IP_MULTICAST_IF ?
10209 			    EHOSTUNREACH : EINVAL);
10210 		}
10211 	} else {
10212 		mutex_enter(&connp->conn_lock);
10213 	}
10214 
10215 	/* None of the options below are supported on the VNI */
10216 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10217 		mutex_exit(&ill->ill_lock);
10218 		mutex_exit(&connp->conn_lock);
10219 		ipif_refrele(ipif);
10220 		return (EINVAL);
10221 	}
10222 
10223 	switch (option) {
10224 	case IP_MULTICAST_IF:
10225 		connp->conn_multicast_ipif = ipif;
10226 		break;
10227 	case IP_NEXTHOP:
10228 		connp->conn_nexthop_v4 = addr;
10229 		connp->conn_nexthop_set = B_TRUE;
10230 		break;
10231 	}
10232 
10233 	if (ipif != NULL) {
10234 		mutex_exit(&ill->ill_lock);
10235 		mutex_exit(&connp->conn_lock);
10236 		ipif_refrele(ipif);
10237 		return (0);
10238 	}
10239 	mutex_exit(&connp->conn_lock);
10240 	/* We succeded in cleared the option */
10241 	return (0);
10242 }
10243 
10244 /*
10245  * For options that pass in an ifindex specifying the ill. V6 options always
10246  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10247  */
10248 int
10249 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10250     int level, int option, mblk_t *first_mp)
10251 {
10252 	ill_t *ill = NULL;
10253 	int error = 0;
10254 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10255 
10256 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10257 	if (ifindex != 0) {
10258 		ASSERT(connp != NULL);
10259 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10260 		    first_mp, ip_restart_optmgmt, &error, ipst);
10261 		if (ill != NULL) {
10262 			if (checkonly) {
10263 				/* not supported by the virtual network iface */
10264 				if (IS_VNI(ill)) {
10265 					ill_refrele(ill);
10266 					return (EINVAL);
10267 				}
10268 				ill_refrele(ill);
10269 				return (0);
10270 			}
10271 			if (!ipif_lookup_zoneid(ill, connp->conn_zoneid,
10272 			    0, NULL)) {
10273 				ill_refrele(ill);
10274 				ill = NULL;
10275 				mutex_enter(&connp->conn_lock);
10276 				goto setit;
10277 			}
10278 			mutex_enter(&connp->conn_lock);
10279 			mutex_enter(&ill->ill_lock);
10280 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10281 				mutex_exit(&ill->ill_lock);
10282 				mutex_exit(&connp->conn_lock);
10283 				ill_refrele(ill);
10284 				ill = NULL;
10285 				mutex_enter(&connp->conn_lock);
10286 			}
10287 			goto setit;
10288 		} else if (error == EINPROGRESS) {
10289 			return (error);
10290 		} else {
10291 			error = 0;
10292 		}
10293 	}
10294 	mutex_enter(&connp->conn_lock);
10295 setit:
10296 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10297 
10298 	/*
10299 	 * The options below assume that the ILL (if any) transmits and/or
10300 	 * receives traffic. Neither of which is true for the virtual network
10301 	 * interface, so fail setting these on a VNI.
10302 	 */
10303 	if (IS_VNI(ill)) {
10304 		ASSERT(ill != NULL);
10305 		mutex_exit(&ill->ill_lock);
10306 		mutex_exit(&connp->conn_lock);
10307 		ill_refrele(ill);
10308 		return (EINVAL);
10309 	}
10310 
10311 	if (level == IPPROTO_IP) {
10312 		switch (option) {
10313 		case IP_BOUND_IF:
10314 			connp->conn_incoming_ill = ill;
10315 			connp->conn_outgoing_ill = ill;
10316 			break;
10317 
10318 		case IP_MULTICAST_IF:
10319 			/*
10320 			 * This option is an internal special. The socket
10321 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10322 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10323 			 * specifies an ifindex and we try first on V6 ill's.
10324 			 * If we don't find one, we they try using on v4 ill's
10325 			 * intenally and we come here.
10326 			 */
10327 			if (!checkonly && ill != NULL) {
10328 				ipif_t	*ipif;
10329 				ipif = ill->ill_ipif;
10330 
10331 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10332 					mutex_exit(&ill->ill_lock);
10333 					mutex_exit(&connp->conn_lock);
10334 					ill_refrele(ill);
10335 					ill = NULL;
10336 					mutex_enter(&connp->conn_lock);
10337 				} else {
10338 					connp->conn_multicast_ipif = ipif;
10339 				}
10340 			}
10341 			break;
10342 
10343 		case IP_DHCPINIT_IF:
10344 			if (connp->conn_dhcpinit_ill != NULL) {
10345 				/*
10346 				 * We've locked the conn so conn_cleanup_ill()
10347 				 * cannot clear conn_dhcpinit_ill -- so it's
10348 				 * safe to access the ill.
10349 				 */
10350 				ill_t *oill = connp->conn_dhcpinit_ill;
10351 
10352 				ASSERT(oill->ill_dhcpinit != 0);
10353 				atomic_dec_32(&oill->ill_dhcpinit);
10354 				connp->conn_dhcpinit_ill = NULL;
10355 			}
10356 
10357 			if (ill != NULL) {
10358 				connp->conn_dhcpinit_ill = ill;
10359 				atomic_inc_32(&ill->ill_dhcpinit);
10360 			}
10361 			break;
10362 		}
10363 	} else {
10364 		switch (option) {
10365 		case IPV6_BOUND_IF:
10366 			connp->conn_incoming_ill = ill;
10367 			connp->conn_outgoing_ill = ill;
10368 			break;
10369 
10370 		case IPV6_MULTICAST_IF:
10371 			/*
10372 			 * Set conn_multicast_ill to be the IPv6 ill.
10373 			 * Set conn_multicast_ipif to be an IPv4 ipif
10374 			 * for ifindex to make IPv4 mapped addresses
10375 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10376 			 * Even if no IPv6 ill exists for the ifindex
10377 			 * we need to check for an IPv4 ifindex in order
10378 			 * for this to work with mapped addresses. In that
10379 			 * case only set conn_multicast_ipif.
10380 			 */
10381 			if (!checkonly) {
10382 				if (ifindex == 0) {
10383 					connp->conn_multicast_ill = NULL;
10384 					connp->conn_multicast_ipif = NULL;
10385 				} else if (ill != NULL) {
10386 					connp->conn_multicast_ill = ill;
10387 				}
10388 			}
10389 			break;
10390 		}
10391 	}
10392 
10393 	if (ill != NULL) {
10394 		mutex_exit(&ill->ill_lock);
10395 		mutex_exit(&connp->conn_lock);
10396 		ill_refrele(ill);
10397 		return (0);
10398 	}
10399 	mutex_exit(&connp->conn_lock);
10400 	/*
10401 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10402 	 * locate the ill and could not set the option (ifindex != 0)
10403 	 */
10404 	return (ifindex == 0 ? 0 : EINVAL);
10405 }
10406 
10407 /* This routine sets socket options. */
10408 /* ARGSUSED */
10409 int
10410 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10411     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10412     void *dummy, cred_t *cr, mblk_t *first_mp)
10413 {
10414 	int		*i1 = (int *)invalp;
10415 	conn_t		*connp = Q_TO_CONN(q);
10416 	int		error = 0;
10417 	boolean_t	checkonly;
10418 	ire_t		*ire;
10419 	boolean_t	found;
10420 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10421 
10422 	switch (optset_context) {
10423 
10424 	case SETFN_OPTCOM_CHECKONLY:
10425 		checkonly = B_TRUE;
10426 		/*
10427 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10428 		 * inlen != 0 implies value supplied and
10429 		 * 	we have to "pretend" to set it.
10430 		 * inlen == 0 implies that there is no
10431 		 * 	value part in T_CHECK request and just validation
10432 		 * done elsewhere should be enough, we just return here.
10433 		 */
10434 		if (inlen == 0) {
10435 			*outlenp = 0;
10436 			return (0);
10437 		}
10438 		break;
10439 	case SETFN_OPTCOM_NEGOTIATE:
10440 	case SETFN_UD_NEGOTIATE:
10441 	case SETFN_CONN_NEGOTIATE:
10442 		checkonly = B_FALSE;
10443 		break;
10444 	default:
10445 		/*
10446 		 * We should never get here
10447 		 */
10448 		*outlenp = 0;
10449 		return (EINVAL);
10450 	}
10451 
10452 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10453 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10454 
10455 	/*
10456 	 * For fixed length options, no sanity check
10457 	 * of passed in length is done. It is assumed *_optcom_req()
10458 	 * routines do the right thing.
10459 	 */
10460 
10461 	switch (level) {
10462 	case SOL_SOCKET:
10463 		/*
10464 		 * conn_lock protects the bitfields, and is used to
10465 		 * set the fields atomically.
10466 		 */
10467 		switch (name) {
10468 		case SO_BROADCAST:
10469 			if (!checkonly) {
10470 				/* TODO: use value someplace? */
10471 				mutex_enter(&connp->conn_lock);
10472 				connp->conn_broadcast = *i1 ? 1 : 0;
10473 				mutex_exit(&connp->conn_lock);
10474 			}
10475 			break;	/* goto sizeof (int) option return */
10476 		case SO_USELOOPBACK:
10477 			if (!checkonly) {
10478 				/* TODO: use value someplace? */
10479 				mutex_enter(&connp->conn_lock);
10480 				connp->conn_loopback = *i1 ? 1 : 0;
10481 				mutex_exit(&connp->conn_lock);
10482 			}
10483 			break;	/* goto sizeof (int) option return */
10484 		case SO_DONTROUTE:
10485 			if (!checkonly) {
10486 				mutex_enter(&connp->conn_lock);
10487 				connp->conn_dontroute = *i1 ? 1 : 0;
10488 				mutex_exit(&connp->conn_lock);
10489 			}
10490 			break;	/* goto sizeof (int) option return */
10491 		case SO_REUSEADDR:
10492 			if (!checkonly) {
10493 				mutex_enter(&connp->conn_lock);
10494 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10495 				mutex_exit(&connp->conn_lock);
10496 			}
10497 			break;	/* goto sizeof (int) option return */
10498 		case SO_PROTOTYPE:
10499 			if (!checkonly) {
10500 				mutex_enter(&connp->conn_lock);
10501 				connp->conn_proto = *i1;
10502 				mutex_exit(&connp->conn_lock);
10503 			}
10504 			break;	/* goto sizeof (int) option return */
10505 		case SO_ALLZONES:
10506 			if (!checkonly) {
10507 				mutex_enter(&connp->conn_lock);
10508 				if (IPCL_IS_BOUND(connp)) {
10509 					mutex_exit(&connp->conn_lock);
10510 					return (EINVAL);
10511 				}
10512 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10513 				mutex_exit(&connp->conn_lock);
10514 			}
10515 			break;	/* goto sizeof (int) option return */
10516 		case SO_ANON_MLP:
10517 			if (!checkonly) {
10518 				mutex_enter(&connp->conn_lock);
10519 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10520 				mutex_exit(&connp->conn_lock);
10521 			}
10522 			break;	/* goto sizeof (int) option return */
10523 		case SO_MAC_EXEMPT:
10524 			if (secpolicy_net_mac_aware(cr) != 0 ||
10525 			    IPCL_IS_BOUND(connp))
10526 				return (EACCES);
10527 			if (!checkonly) {
10528 				mutex_enter(&connp->conn_lock);
10529 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10530 				mutex_exit(&connp->conn_lock);
10531 			}
10532 			break;	/* goto sizeof (int) option return */
10533 		default:
10534 			/*
10535 			 * "soft" error (negative)
10536 			 * option not handled at this level
10537 			 * Note: Do not modify *outlenp
10538 			 */
10539 			return (-EINVAL);
10540 		}
10541 		break;
10542 	case IPPROTO_IP:
10543 		switch (name) {
10544 		case IP_NEXTHOP:
10545 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10546 				return (EPERM);
10547 			/* FALLTHRU */
10548 		case IP_MULTICAST_IF: {
10549 			ipaddr_t addr = *i1;
10550 
10551 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10552 			    first_mp);
10553 			if (error != 0)
10554 				return (error);
10555 			break;	/* goto sizeof (int) option return */
10556 		}
10557 
10558 		case IP_MULTICAST_TTL:
10559 			/* Recorded in transport above IP */
10560 			*outvalp = *invalp;
10561 			*outlenp = sizeof (uchar_t);
10562 			return (0);
10563 		case IP_MULTICAST_LOOP:
10564 			if (!checkonly) {
10565 				mutex_enter(&connp->conn_lock);
10566 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10567 				mutex_exit(&connp->conn_lock);
10568 			}
10569 			*outvalp = *invalp;
10570 			*outlenp = sizeof (uchar_t);
10571 			return (0);
10572 		case IP_ADD_MEMBERSHIP:
10573 		case MCAST_JOIN_GROUP:
10574 		case IP_DROP_MEMBERSHIP:
10575 		case MCAST_LEAVE_GROUP: {
10576 			struct ip_mreq *mreqp;
10577 			struct group_req *greqp;
10578 			ire_t *ire;
10579 			boolean_t done = B_FALSE;
10580 			ipaddr_t group, ifaddr;
10581 			struct sockaddr_in *sin;
10582 			uint32_t *ifindexp;
10583 			boolean_t mcast_opt = B_TRUE;
10584 			mcast_record_t fmode;
10585 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10586 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10587 
10588 			switch (name) {
10589 			case IP_ADD_MEMBERSHIP:
10590 				mcast_opt = B_FALSE;
10591 				/* FALLTHRU */
10592 			case MCAST_JOIN_GROUP:
10593 				fmode = MODE_IS_EXCLUDE;
10594 				optfn = ip_opt_add_group;
10595 				break;
10596 
10597 			case IP_DROP_MEMBERSHIP:
10598 				mcast_opt = B_FALSE;
10599 				/* FALLTHRU */
10600 			case MCAST_LEAVE_GROUP:
10601 				fmode = MODE_IS_INCLUDE;
10602 				optfn = ip_opt_delete_group;
10603 				break;
10604 			}
10605 
10606 			if (mcast_opt) {
10607 				greqp = (struct group_req *)i1;
10608 				sin = (struct sockaddr_in *)&greqp->gr_group;
10609 				if (sin->sin_family != AF_INET) {
10610 					*outlenp = 0;
10611 					return (ENOPROTOOPT);
10612 				}
10613 				group = (ipaddr_t)sin->sin_addr.s_addr;
10614 				ifaddr = INADDR_ANY;
10615 				ifindexp = &greqp->gr_interface;
10616 			} else {
10617 				mreqp = (struct ip_mreq *)i1;
10618 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10619 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10620 				ifindexp = NULL;
10621 			}
10622 
10623 			/*
10624 			 * In the multirouting case, we need to replicate
10625 			 * the request on all interfaces that will take part
10626 			 * in replication.  We do so because multirouting is
10627 			 * reflective, thus we will probably receive multi-
10628 			 * casts on those interfaces.
10629 			 * The ip_multirt_apply_membership() succeeds if the
10630 			 * operation succeeds on at least one interface.
10631 			 */
10632 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10633 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10634 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10635 			if (ire != NULL) {
10636 				if (ire->ire_flags & RTF_MULTIRT) {
10637 					error = ip_multirt_apply_membership(
10638 					    optfn, ire, connp, checkonly, group,
10639 					    fmode, INADDR_ANY, first_mp);
10640 					done = B_TRUE;
10641 				}
10642 				ire_refrele(ire);
10643 			}
10644 			if (!done) {
10645 				error = optfn(connp, checkonly, group, ifaddr,
10646 				    ifindexp, fmode, INADDR_ANY, first_mp);
10647 			}
10648 			if (error) {
10649 				/*
10650 				 * EINPROGRESS is a soft error, needs retry
10651 				 * so don't make *outlenp zero.
10652 				 */
10653 				if (error != EINPROGRESS)
10654 					*outlenp = 0;
10655 				return (error);
10656 			}
10657 			/* OK return - copy input buffer into output buffer */
10658 			if (invalp != outvalp) {
10659 				/* don't trust bcopy for identical src/dst */
10660 				bcopy(invalp, outvalp, inlen);
10661 			}
10662 			*outlenp = inlen;
10663 			return (0);
10664 		}
10665 		case IP_BLOCK_SOURCE:
10666 		case IP_UNBLOCK_SOURCE:
10667 		case IP_ADD_SOURCE_MEMBERSHIP:
10668 		case IP_DROP_SOURCE_MEMBERSHIP:
10669 		case MCAST_BLOCK_SOURCE:
10670 		case MCAST_UNBLOCK_SOURCE:
10671 		case MCAST_JOIN_SOURCE_GROUP:
10672 		case MCAST_LEAVE_SOURCE_GROUP: {
10673 			struct ip_mreq_source *imreqp;
10674 			struct group_source_req *gsreqp;
10675 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10676 			uint32_t ifindex = 0;
10677 			mcast_record_t fmode;
10678 			struct sockaddr_in *sin;
10679 			ire_t *ire;
10680 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10681 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10682 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10683 
10684 			switch (name) {
10685 			case IP_BLOCK_SOURCE:
10686 				mcast_opt = B_FALSE;
10687 				/* FALLTHRU */
10688 			case MCAST_BLOCK_SOURCE:
10689 				fmode = MODE_IS_EXCLUDE;
10690 				optfn = ip_opt_add_group;
10691 				break;
10692 
10693 			case IP_UNBLOCK_SOURCE:
10694 				mcast_opt = B_FALSE;
10695 				/* FALLTHRU */
10696 			case MCAST_UNBLOCK_SOURCE:
10697 				fmode = MODE_IS_EXCLUDE;
10698 				optfn = ip_opt_delete_group;
10699 				break;
10700 
10701 			case IP_ADD_SOURCE_MEMBERSHIP:
10702 				mcast_opt = B_FALSE;
10703 				/* FALLTHRU */
10704 			case MCAST_JOIN_SOURCE_GROUP:
10705 				fmode = MODE_IS_INCLUDE;
10706 				optfn = ip_opt_add_group;
10707 				break;
10708 
10709 			case IP_DROP_SOURCE_MEMBERSHIP:
10710 				mcast_opt = B_FALSE;
10711 				/* FALLTHRU */
10712 			case MCAST_LEAVE_SOURCE_GROUP:
10713 				fmode = MODE_IS_INCLUDE;
10714 				optfn = ip_opt_delete_group;
10715 				break;
10716 			}
10717 
10718 			if (mcast_opt) {
10719 				gsreqp = (struct group_source_req *)i1;
10720 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10721 					*outlenp = 0;
10722 					return (ENOPROTOOPT);
10723 				}
10724 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10725 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10726 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10727 				src = (ipaddr_t)sin->sin_addr.s_addr;
10728 				ifindex = gsreqp->gsr_interface;
10729 			} else {
10730 				imreqp = (struct ip_mreq_source *)i1;
10731 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10732 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10733 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10734 			}
10735 
10736 			/*
10737 			 * In the multirouting case, we need to replicate
10738 			 * the request as noted in the mcast cases above.
10739 			 */
10740 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10741 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10742 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10743 			if (ire != NULL) {
10744 				if (ire->ire_flags & RTF_MULTIRT) {
10745 					error = ip_multirt_apply_membership(
10746 					    optfn, ire, connp, checkonly, grp,
10747 					    fmode, src, first_mp);
10748 					done = B_TRUE;
10749 				}
10750 				ire_refrele(ire);
10751 			}
10752 			if (!done) {
10753 				error = optfn(connp, checkonly, grp, ifaddr,
10754 				    &ifindex, fmode, src, first_mp);
10755 			}
10756 			if (error != 0) {
10757 				/*
10758 				 * EINPROGRESS is a soft error, needs retry
10759 				 * so don't make *outlenp zero.
10760 				 */
10761 				if (error != EINPROGRESS)
10762 					*outlenp = 0;
10763 				return (error);
10764 			}
10765 			/* OK return - copy input buffer into output buffer */
10766 			if (invalp != outvalp) {
10767 				bcopy(invalp, outvalp, inlen);
10768 			}
10769 			*outlenp = inlen;
10770 			return (0);
10771 		}
10772 		case IP_SEC_OPT:
10773 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10774 			if (error != 0) {
10775 				*outlenp = 0;
10776 				return (error);
10777 			}
10778 			break;
10779 		case IP_HDRINCL:
10780 		case IP_OPTIONS:
10781 		case T_IP_OPTIONS:
10782 		case IP_TOS:
10783 		case T_IP_TOS:
10784 		case IP_TTL:
10785 		case IP_RECVDSTADDR:
10786 		case IP_RECVOPTS:
10787 			/* OK return - copy input buffer into output buffer */
10788 			if (invalp != outvalp) {
10789 				/* don't trust bcopy for identical src/dst */
10790 				bcopy(invalp, outvalp, inlen);
10791 			}
10792 			*outlenp = inlen;
10793 			return (0);
10794 		case IP_RECVIF:
10795 			/* Retrieve the inbound interface index */
10796 			if (!checkonly) {
10797 				mutex_enter(&connp->conn_lock);
10798 				connp->conn_recvif = *i1 ? 1 : 0;
10799 				mutex_exit(&connp->conn_lock);
10800 			}
10801 			break;	/* goto sizeof (int) option return */
10802 		case IP_RECVPKTINFO:
10803 			if (!checkonly) {
10804 				mutex_enter(&connp->conn_lock);
10805 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
10806 				mutex_exit(&connp->conn_lock);
10807 			}
10808 			break;	/* goto sizeof (int) option return */
10809 		case IP_RECVSLLA:
10810 			/* Retrieve the source link layer address */
10811 			if (!checkonly) {
10812 				mutex_enter(&connp->conn_lock);
10813 				connp->conn_recvslla = *i1 ? 1 : 0;
10814 				mutex_exit(&connp->conn_lock);
10815 			}
10816 			break;	/* goto sizeof (int) option return */
10817 		case MRT_INIT:
10818 		case MRT_DONE:
10819 		case MRT_ADD_VIF:
10820 		case MRT_DEL_VIF:
10821 		case MRT_ADD_MFC:
10822 		case MRT_DEL_MFC:
10823 		case MRT_ASSERT:
10824 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
10825 				*outlenp = 0;
10826 				return (error);
10827 			}
10828 			error = ip_mrouter_set((int)name, q, checkonly,
10829 			    (uchar_t *)invalp, inlen, first_mp);
10830 			if (error) {
10831 				*outlenp = 0;
10832 				return (error);
10833 			}
10834 			/* OK return - copy input buffer into output buffer */
10835 			if (invalp != outvalp) {
10836 				/* don't trust bcopy for identical src/dst */
10837 				bcopy(invalp, outvalp, inlen);
10838 			}
10839 			*outlenp = inlen;
10840 			return (0);
10841 		case IP_BOUND_IF:
10842 		case IP_DHCPINIT_IF:
10843 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10844 			    level, name, first_mp);
10845 			if (error != 0)
10846 				return (error);
10847 			break; 		/* goto sizeof (int) option return */
10848 
10849 		case IP_UNSPEC_SRC:
10850 			/* Allow sending with a zero source address */
10851 			if (!checkonly) {
10852 				mutex_enter(&connp->conn_lock);
10853 				connp->conn_unspec_src = *i1 ? 1 : 0;
10854 				mutex_exit(&connp->conn_lock);
10855 			}
10856 			break;	/* goto sizeof (int) option return */
10857 		default:
10858 			/*
10859 			 * "soft" error (negative)
10860 			 * option not handled at this level
10861 			 * Note: Do not modify *outlenp
10862 			 */
10863 			return (-EINVAL);
10864 		}
10865 		break;
10866 	case IPPROTO_IPV6:
10867 		switch (name) {
10868 		case IPV6_BOUND_IF:
10869 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10870 			    level, name, first_mp);
10871 			if (error != 0)
10872 				return (error);
10873 			break; 		/* goto sizeof (int) option return */
10874 
10875 		case IPV6_MULTICAST_IF:
10876 			/*
10877 			 * The only possible errors are EINPROGRESS and
10878 			 * EINVAL. EINPROGRESS will be restarted and is not
10879 			 * a hard error. We call this option on both V4 and V6
10880 			 * If both return EINVAL, then this call returns
10881 			 * EINVAL. If at least one of them succeeds we
10882 			 * return success.
10883 			 */
10884 			found = B_FALSE;
10885 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10886 			    level, name, first_mp);
10887 			if (error == EINPROGRESS)
10888 				return (error);
10889 			if (error == 0)
10890 				found = B_TRUE;
10891 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10892 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
10893 			if (error == 0)
10894 				found = B_TRUE;
10895 			if (!found)
10896 				return (error);
10897 			break; 		/* goto sizeof (int) option return */
10898 
10899 		case IPV6_MULTICAST_HOPS:
10900 			/* Recorded in transport above IP */
10901 			break;	/* goto sizeof (int) option return */
10902 		case IPV6_MULTICAST_LOOP:
10903 			if (!checkonly) {
10904 				mutex_enter(&connp->conn_lock);
10905 				connp->conn_multicast_loop = *i1;
10906 				mutex_exit(&connp->conn_lock);
10907 			}
10908 			break;	/* goto sizeof (int) option return */
10909 		case IPV6_JOIN_GROUP:
10910 		case MCAST_JOIN_GROUP:
10911 		case IPV6_LEAVE_GROUP:
10912 		case MCAST_LEAVE_GROUP: {
10913 			struct ipv6_mreq *ip_mreqp;
10914 			struct group_req *greqp;
10915 			ire_t *ire;
10916 			boolean_t done = B_FALSE;
10917 			in6_addr_t groupv6;
10918 			uint32_t ifindex;
10919 			boolean_t mcast_opt = B_TRUE;
10920 			mcast_record_t fmode;
10921 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10922 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10923 
10924 			switch (name) {
10925 			case IPV6_JOIN_GROUP:
10926 				mcast_opt = B_FALSE;
10927 				/* FALLTHRU */
10928 			case MCAST_JOIN_GROUP:
10929 				fmode = MODE_IS_EXCLUDE;
10930 				optfn = ip_opt_add_group_v6;
10931 				break;
10932 
10933 			case IPV6_LEAVE_GROUP:
10934 				mcast_opt = B_FALSE;
10935 				/* FALLTHRU */
10936 			case MCAST_LEAVE_GROUP:
10937 				fmode = MODE_IS_INCLUDE;
10938 				optfn = ip_opt_delete_group_v6;
10939 				break;
10940 			}
10941 
10942 			if (mcast_opt) {
10943 				struct sockaddr_in *sin;
10944 				struct sockaddr_in6 *sin6;
10945 				greqp = (struct group_req *)i1;
10946 				if (greqp->gr_group.ss_family == AF_INET) {
10947 					sin = (struct sockaddr_in *)
10948 					    &(greqp->gr_group);
10949 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
10950 					    &groupv6);
10951 				} else {
10952 					sin6 = (struct sockaddr_in6 *)
10953 					    &(greqp->gr_group);
10954 					groupv6 = sin6->sin6_addr;
10955 				}
10956 				ifindex = greqp->gr_interface;
10957 			} else {
10958 				ip_mreqp = (struct ipv6_mreq *)i1;
10959 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
10960 				ifindex = ip_mreqp->ipv6mr_interface;
10961 			}
10962 			/*
10963 			 * In the multirouting case, we need to replicate
10964 			 * the request on all interfaces that will take part
10965 			 * in replication.  We do so because multirouting is
10966 			 * reflective, thus we will probably receive multi-
10967 			 * casts on those interfaces.
10968 			 * The ip_multirt_apply_membership_v6() succeeds if
10969 			 * the operation succeeds on at least one interface.
10970 			 */
10971 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
10972 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10973 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10974 			if (ire != NULL) {
10975 				if (ire->ire_flags & RTF_MULTIRT) {
10976 					error = ip_multirt_apply_membership_v6(
10977 					    optfn, ire, connp, checkonly,
10978 					    &groupv6, fmode, &ipv6_all_zeros,
10979 					    first_mp);
10980 					done = B_TRUE;
10981 				}
10982 				ire_refrele(ire);
10983 			}
10984 			if (!done) {
10985 				error = optfn(connp, checkonly, &groupv6,
10986 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
10987 			}
10988 			if (error) {
10989 				/*
10990 				 * EINPROGRESS is a soft error, needs retry
10991 				 * so don't make *outlenp zero.
10992 				 */
10993 				if (error != EINPROGRESS)
10994 					*outlenp = 0;
10995 				return (error);
10996 			}
10997 			/* OK return - copy input buffer into output buffer */
10998 			if (invalp != outvalp) {
10999 				/* don't trust bcopy for identical src/dst */
11000 				bcopy(invalp, outvalp, inlen);
11001 			}
11002 			*outlenp = inlen;
11003 			return (0);
11004 		}
11005 		case MCAST_BLOCK_SOURCE:
11006 		case MCAST_UNBLOCK_SOURCE:
11007 		case MCAST_JOIN_SOURCE_GROUP:
11008 		case MCAST_LEAVE_SOURCE_GROUP: {
11009 			struct group_source_req *gsreqp;
11010 			in6_addr_t v6grp, v6src;
11011 			uint32_t ifindex;
11012 			mcast_record_t fmode;
11013 			ire_t *ire;
11014 			boolean_t done = B_FALSE;
11015 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11016 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11017 
11018 			switch (name) {
11019 			case MCAST_BLOCK_SOURCE:
11020 				fmode = MODE_IS_EXCLUDE;
11021 				optfn = ip_opt_add_group_v6;
11022 				break;
11023 			case MCAST_UNBLOCK_SOURCE:
11024 				fmode = MODE_IS_EXCLUDE;
11025 				optfn = ip_opt_delete_group_v6;
11026 				break;
11027 			case MCAST_JOIN_SOURCE_GROUP:
11028 				fmode = MODE_IS_INCLUDE;
11029 				optfn = ip_opt_add_group_v6;
11030 				break;
11031 			case MCAST_LEAVE_SOURCE_GROUP:
11032 				fmode = MODE_IS_INCLUDE;
11033 				optfn = ip_opt_delete_group_v6;
11034 				break;
11035 			}
11036 
11037 			gsreqp = (struct group_source_req *)i1;
11038 			ifindex = gsreqp->gsr_interface;
11039 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11040 				struct sockaddr_in *s;
11041 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11042 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11043 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11044 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11045 			} else {
11046 				struct sockaddr_in6 *s6;
11047 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11048 				v6grp = s6->sin6_addr;
11049 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11050 				v6src = s6->sin6_addr;
11051 			}
11052 
11053 			/*
11054 			 * In the multirouting case, we need to replicate
11055 			 * the request as noted in the mcast cases above.
11056 			 */
11057 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11058 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11059 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11060 			if (ire != NULL) {
11061 				if (ire->ire_flags & RTF_MULTIRT) {
11062 					error = ip_multirt_apply_membership_v6(
11063 					    optfn, ire, connp, checkonly,
11064 					    &v6grp, fmode, &v6src, first_mp);
11065 					done = B_TRUE;
11066 				}
11067 				ire_refrele(ire);
11068 			}
11069 			if (!done) {
11070 				error = optfn(connp, checkonly, &v6grp,
11071 				    ifindex, fmode, &v6src, first_mp);
11072 			}
11073 			if (error != 0) {
11074 				/*
11075 				 * EINPROGRESS is a soft error, needs retry
11076 				 * so don't make *outlenp zero.
11077 				 */
11078 				if (error != EINPROGRESS)
11079 					*outlenp = 0;
11080 				return (error);
11081 			}
11082 			/* OK return - copy input buffer into output buffer */
11083 			if (invalp != outvalp) {
11084 				bcopy(invalp, outvalp, inlen);
11085 			}
11086 			*outlenp = inlen;
11087 			return (0);
11088 		}
11089 		case IPV6_UNICAST_HOPS:
11090 			/* Recorded in transport above IP */
11091 			break;	/* goto sizeof (int) option return */
11092 		case IPV6_UNSPEC_SRC:
11093 			/* Allow sending with a zero source address */
11094 			if (!checkonly) {
11095 				mutex_enter(&connp->conn_lock);
11096 				connp->conn_unspec_src = *i1 ? 1 : 0;
11097 				mutex_exit(&connp->conn_lock);
11098 			}
11099 			break;	/* goto sizeof (int) option return */
11100 		case IPV6_RECVPKTINFO:
11101 			if (!checkonly) {
11102 				mutex_enter(&connp->conn_lock);
11103 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11104 				mutex_exit(&connp->conn_lock);
11105 			}
11106 			break;	/* goto sizeof (int) option return */
11107 		case IPV6_RECVTCLASS:
11108 			if (!checkonly) {
11109 				if (*i1 < 0 || *i1 > 1) {
11110 					return (EINVAL);
11111 				}
11112 				mutex_enter(&connp->conn_lock);
11113 				connp->conn_ipv6_recvtclass = *i1;
11114 				mutex_exit(&connp->conn_lock);
11115 			}
11116 			break;
11117 		case IPV6_RECVPATHMTU:
11118 			if (!checkonly) {
11119 				if (*i1 < 0 || *i1 > 1) {
11120 					return (EINVAL);
11121 				}
11122 				mutex_enter(&connp->conn_lock);
11123 				connp->conn_ipv6_recvpathmtu = *i1;
11124 				mutex_exit(&connp->conn_lock);
11125 			}
11126 			break;
11127 		case IPV6_RECVHOPLIMIT:
11128 			if (!checkonly) {
11129 				mutex_enter(&connp->conn_lock);
11130 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11131 				mutex_exit(&connp->conn_lock);
11132 			}
11133 			break;	/* goto sizeof (int) option return */
11134 		case IPV6_RECVHOPOPTS:
11135 			if (!checkonly) {
11136 				mutex_enter(&connp->conn_lock);
11137 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11138 				mutex_exit(&connp->conn_lock);
11139 			}
11140 			break;	/* goto sizeof (int) option return */
11141 		case IPV6_RECVDSTOPTS:
11142 			if (!checkonly) {
11143 				mutex_enter(&connp->conn_lock);
11144 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11145 				mutex_exit(&connp->conn_lock);
11146 			}
11147 			break;	/* goto sizeof (int) option return */
11148 		case IPV6_RECVRTHDR:
11149 			if (!checkonly) {
11150 				mutex_enter(&connp->conn_lock);
11151 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11152 				mutex_exit(&connp->conn_lock);
11153 			}
11154 			break;	/* goto sizeof (int) option return */
11155 		case IPV6_RECVRTHDRDSTOPTS:
11156 			if (!checkonly) {
11157 				mutex_enter(&connp->conn_lock);
11158 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11159 				mutex_exit(&connp->conn_lock);
11160 			}
11161 			break;	/* goto sizeof (int) option return */
11162 		case IPV6_PKTINFO:
11163 			if (inlen == 0)
11164 				return (-EINVAL);	/* clearing option */
11165 			error = ip6_set_pktinfo(cr, connp,
11166 			    (struct in6_pktinfo *)invalp);
11167 			if (error != 0)
11168 				*outlenp = 0;
11169 			else
11170 				*outlenp = inlen;
11171 			return (error);
11172 		case IPV6_NEXTHOP: {
11173 			struct sockaddr_in6 *sin6;
11174 
11175 			/* Verify that the nexthop is reachable */
11176 			if (inlen == 0)
11177 				return (-EINVAL);	/* clearing option */
11178 
11179 			sin6 = (struct sockaddr_in6 *)invalp;
11180 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11181 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11182 			    NULL, MATCH_IRE_DEFAULT, ipst);
11183 
11184 			if (ire == NULL) {
11185 				*outlenp = 0;
11186 				return (EHOSTUNREACH);
11187 			}
11188 			ire_refrele(ire);
11189 			return (-EINVAL);
11190 		}
11191 		case IPV6_SEC_OPT:
11192 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11193 			if (error != 0) {
11194 				*outlenp = 0;
11195 				return (error);
11196 			}
11197 			break;
11198 		case IPV6_SRC_PREFERENCES: {
11199 			/*
11200 			 * This is implemented strictly in the ip module
11201 			 * (here and in tcp_opt_*() to accomodate tcp
11202 			 * sockets).  Modules above ip pass this option
11203 			 * down here since ip is the only one that needs to
11204 			 * be aware of source address preferences.
11205 			 *
11206 			 * This socket option only affects connected
11207 			 * sockets that haven't already bound to a specific
11208 			 * IPv6 address.  In other words, sockets that
11209 			 * don't call bind() with an address other than the
11210 			 * unspecified address and that call connect().
11211 			 * ip_bind_connected_v6() passes these preferences
11212 			 * to the ipif_select_source_v6() function.
11213 			 */
11214 			if (inlen != sizeof (uint32_t))
11215 				return (EINVAL);
11216 			error = ip6_set_src_preferences(connp,
11217 			    *(uint32_t *)invalp);
11218 			if (error != 0) {
11219 				*outlenp = 0;
11220 				return (error);
11221 			} else {
11222 				*outlenp = sizeof (uint32_t);
11223 			}
11224 			break;
11225 		}
11226 		case IPV6_V6ONLY:
11227 			if (*i1 < 0 || *i1 > 1) {
11228 				return (EINVAL);
11229 			}
11230 			mutex_enter(&connp->conn_lock);
11231 			connp->conn_ipv6_v6only = *i1;
11232 			mutex_exit(&connp->conn_lock);
11233 			break;
11234 		default:
11235 			return (-EINVAL);
11236 		}
11237 		break;
11238 	default:
11239 		/*
11240 		 * "soft" error (negative)
11241 		 * option not handled at this level
11242 		 * Note: Do not modify *outlenp
11243 		 */
11244 		return (-EINVAL);
11245 	}
11246 	/*
11247 	 * Common case of return from an option that is sizeof (int)
11248 	 */
11249 	*(int *)outvalp = *i1;
11250 	*outlenp = sizeof (int);
11251 	return (0);
11252 }
11253 
11254 /*
11255  * This routine gets default values of certain options whose default
11256  * values are maintained by protocol specific code
11257  */
11258 /* ARGSUSED */
11259 int
11260 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11261 {
11262 	int *i1 = (int *)ptr;
11263 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11264 
11265 	switch (level) {
11266 	case IPPROTO_IP:
11267 		switch (name) {
11268 		case IP_MULTICAST_TTL:
11269 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11270 			return (sizeof (uchar_t));
11271 		case IP_MULTICAST_LOOP:
11272 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11273 			return (sizeof (uchar_t));
11274 		default:
11275 			return (-1);
11276 		}
11277 	case IPPROTO_IPV6:
11278 		switch (name) {
11279 		case IPV6_UNICAST_HOPS:
11280 			*i1 = ipst->ips_ipv6_def_hops;
11281 			return (sizeof (int));
11282 		case IPV6_MULTICAST_HOPS:
11283 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11284 			return (sizeof (int));
11285 		case IPV6_MULTICAST_LOOP:
11286 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11287 			return (sizeof (int));
11288 		case IPV6_V6ONLY:
11289 			*i1 = 1;
11290 			return (sizeof (int));
11291 		default:
11292 			return (-1);
11293 		}
11294 	default:
11295 		return (-1);
11296 	}
11297 	/* NOTREACHED */
11298 }
11299 
11300 /*
11301  * Given a destination address and a pointer to where to put the information
11302  * this routine fills in the mtuinfo.
11303  */
11304 int
11305 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11306     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11307 {
11308 	ire_t *ire;
11309 	ip_stack_t	*ipst = ns->netstack_ip;
11310 
11311 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11312 		return (-1);
11313 
11314 	bzero(mtuinfo, sizeof (*mtuinfo));
11315 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11316 	mtuinfo->ip6m_addr.sin6_port = port;
11317 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11318 
11319 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11320 	if (ire != NULL) {
11321 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11322 		ire_refrele(ire);
11323 	} else {
11324 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11325 	}
11326 	return (sizeof (struct ip6_mtuinfo));
11327 }
11328 
11329 /*
11330  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11331  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11332  * isn't.  This doesn't matter as the error checking is done properly for the
11333  * other MRT options coming in through ip_opt_set.
11334  */
11335 int
11336 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11337 {
11338 	conn_t		*connp = Q_TO_CONN(q);
11339 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11340 
11341 	switch (level) {
11342 	case IPPROTO_IP:
11343 		switch (name) {
11344 		case MRT_VERSION:
11345 		case MRT_ASSERT:
11346 			(void) ip_mrouter_get(name, q, ptr);
11347 			return (sizeof (int));
11348 		case IP_SEC_OPT:
11349 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11350 		case IP_NEXTHOP:
11351 			if (connp->conn_nexthop_set) {
11352 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11353 				return (sizeof (ipaddr_t));
11354 			} else
11355 				return (0);
11356 		case IP_RECVPKTINFO:
11357 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11358 			return (sizeof (int));
11359 		default:
11360 			break;
11361 		}
11362 		break;
11363 	case IPPROTO_IPV6:
11364 		switch (name) {
11365 		case IPV6_SEC_OPT:
11366 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11367 		case IPV6_SRC_PREFERENCES: {
11368 			return (ip6_get_src_preferences(connp,
11369 			    (uint32_t *)ptr));
11370 		}
11371 		case IPV6_V6ONLY:
11372 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11373 			return (sizeof (int));
11374 		case IPV6_PATHMTU:
11375 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11376 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11377 		default:
11378 			break;
11379 		}
11380 		break;
11381 	default:
11382 		break;
11383 	}
11384 	return (-1);
11385 }
11386 /* Named Dispatch routine to get a current value out of our parameter table. */
11387 /* ARGSUSED */
11388 static int
11389 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11390 {
11391 	ipparam_t *ippa = (ipparam_t *)cp;
11392 
11393 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11394 	return (0);
11395 }
11396 
11397 /* ARGSUSED */
11398 static int
11399 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11400 {
11401 
11402 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11403 	return (0);
11404 }
11405 
11406 /*
11407  * Set ip{,6}_forwarding values.  This means walking through all of the
11408  * ill's and toggling their forwarding values.
11409  */
11410 /* ARGSUSED */
11411 static int
11412 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11413 {
11414 	long new_value;
11415 	int *forwarding_value = (int *)cp;
11416 	ill_t *ill;
11417 	boolean_t isv6;
11418 	ill_walk_context_t ctx;
11419 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11420 
11421 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11422 
11423 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11424 	    new_value < 0 || new_value > 1) {
11425 		return (EINVAL);
11426 	}
11427 
11428 	*forwarding_value = new_value;
11429 
11430 	/*
11431 	 * Regardless of the current value of ip_forwarding, set all per-ill
11432 	 * values of ip_forwarding to the value being set.
11433 	 *
11434 	 * Bring all the ill's up to date with the new global value.
11435 	 */
11436 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11437 
11438 	if (isv6)
11439 		ill = ILL_START_WALK_V6(&ctx, ipst);
11440 	else
11441 		ill = ILL_START_WALK_V4(&ctx, ipst);
11442 
11443 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11444 		(void) ill_forward_set(ill, new_value != 0);
11445 
11446 	rw_exit(&ipst->ips_ill_g_lock);
11447 	return (0);
11448 }
11449 
11450 /*
11451  * Walk through the param array specified registering each element with the
11452  * Named Dispatch handler. This is called only during init. So it is ok
11453  * not to acquire any locks
11454  */
11455 static boolean_t
11456 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11457     ipndp_t *ipnd, size_t ipnd_cnt)
11458 {
11459 	for (; ippa_cnt-- > 0; ippa++) {
11460 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11461 			if (!nd_load(ndp, ippa->ip_param_name,
11462 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11463 				nd_free(ndp);
11464 				return (B_FALSE);
11465 			}
11466 		}
11467 	}
11468 
11469 	for (; ipnd_cnt-- > 0; ipnd++) {
11470 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11471 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11472 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11473 			    ipnd->ip_ndp_data)) {
11474 				nd_free(ndp);
11475 				return (B_FALSE);
11476 			}
11477 		}
11478 	}
11479 
11480 	return (B_TRUE);
11481 }
11482 
11483 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11484 /* ARGSUSED */
11485 static int
11486 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11487 {
11488 	long		new_value;
11489 	ipparam_t	*ippa = (ipparam_t *)cp;
11490 
11491 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11492 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11493 		return (EINVAL);
11494 	}
11495 	ippa->ip_param_value = new_value;
11496 	return (0);
11497 }
11498 
11499 /*
11500  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11501  * When an ipf is passed here for the first time, if
11502  * we already have in-order fragments on the queue, we convert from the fast-
11503  * path reassembly scheme to the hard-case scheme.  From then on, additional
11504  * fragments are reassembled here.  We keep track of the start and end offsets
11505  * of each piece, and the number of holes in the chain.  When the hole count
11506  * goes to zero, we are done!
11507  *
11508  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11509  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11510  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11511  * after the call to ip_reassemble().
11512  */
11513 int
11514 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11515     size_t msg_len)
11516 {
11517 	uint_t	end;
11518 	mblk_t	*next_mp;
11519 	mblk_t	*mp1;
11520 	uint_t	offset;
11521 	boolean_t incr_dups = B_TRUE;
11522 	boolean_t offset_zero_seen = B_FALSE;
11523 	boolean_t pkt_boundary_checked = B_FALSE;
11524 
11525 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11526 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11527 
11528 	/* Add in byte count */
11529 	ipf->ipf_count += msg_len;
11530 	if (ipf->ipf_end) {
11531 		/*
11532 		 * We were part way through in-order reassembly, but now there
11533 		 * is a hole.  We walk through messages already queued, and
11534 		 * mark them for hard case reassembly.  We know that up till
11535 		 * now they were in order starting from offset zero.
11536 		 */
11537 		offset = 0;
11538 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11539 			IP_REASS_SET_START(mp1, offset);
11540 			if (offset == 0) {
11541 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11542 				offset = -ipf->ipf_nf_hdr_len;
11543 			}
11544 			offset += mp1->b_wptr - mp1->b_rptr;
11545 			IP_REASS_SET_END(mp1, offset);
11546 		}
11547 		/* One hole at the end. */
11548 		ipf->ipf_hole_cnt = 1;
11549 		/* Brand it as a hard case, forever. */
11550 		ipf->ipf_end = 0;
11551 	}
11552 	/* Walk through all the new pieces. */
11553 	do {
11554 		end = start + (mp->b_wptr - mp->b_rptr);
11555 		/*
11556 		 * If start is 0, decrease 'end' only for the first mblk of
11557 		 * the fragment. Otherwise 'end' can get wrong value in the
11558 		 * second pass of the loop if first mblk is exactly the
11559 		 * size of ipf_nf_hdr_len.
11560 		 */
11561 		if (start == 0 && !offset_zero_seen) {
11562 			/* First segment */
11563 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11564 			end -= ipf->ipf_nf_hdr_len;
11565 			offset_zero_seen = B_TRUE;
11566 		}
11567 		next_mp = mp->b_cont;
11568 		/*
11569 		 * We are checking to see if there is any interesing data
11570 		 * to process.  If there isn't and the mblk isn't the
11571 		 * one which carries the unfragmentable header then we
11572 		 * drop it.  It's possible to have just the unfragmentable
11573 		 * header come through without any data.  That needs to be
11574 		 * saved.
11575 		 *
11576 		 * If the assert at the top of this function holds then the
11577 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11578 		 * is infrequently traveled enough that the test is left in
11579 		 * to protect against future code changes which break that
11580 		 * invariant.
11581 		 */
11582 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11583 			/* Empty.  Blast it. */
11584 			IP_REASS_SET_START(mp, 0);
11585 			IP_REASS_SET_END(mp, 0);
11586 			/*
11587 			 * If the ipf points to the mblk we are about to free,
11588 			 * update ipf to point to the next mblk (or NULL
11589 			 * if none).
11590 			 */
11591 			if (ipf->ipf_mp->b_cont == mp)
11592 				ipf->ipf_mp->b_cont = next_mp;
11593 			freeb(mp);
11594 			continue;
11595 		}
11596 		mp->b_cont = NULL;
11597 		IP_REASS_SET_START(mp, start);
11598 		IP_REASS_SET_END(mp, end);
11599 		if (!ipf->ipf_tail_mp) {
11600 			ipf->ipf_tail_mp = mp;
11601 			ipf->ipf_mp->b_cont = mp;
11602 			if (start == 0 || !more) {
11603 				ipf->ipf_hole_cnt = 1;
11604 				/*
11605 				 * if the first fragment comes in more than one
11606 				 * mblk, this loop will be executed for each
11607 				 * mblk. Need to adjust hole count so exiting
11608 				 * this routine will leave hole count at 1.
11609 				 */
11610 				if (next_mp)
11611 					ipf->ipf_hole_cnt++;
11612 			} else
11613 				ipf->ipf_hole_cnt = 2;
11614 			continue;
11615 		} else if (ipf->ipf_last_frag_seen && !more &&
11616 		    !pkt_boundary_checked) {
11617 			/*
11618 			 * We check datagram boundary only if this fragment
11619 			 * claims to be the last fragment and we have seen a
11620 			 * last fragment in the past too. We do this only
11621 			 * once for a given fragment.
11622 			 *
11623 			 * start cannot be 0 here as fragments with start=0
11624 			 * and MF=0 gets handled as a complete packet. These
11625 			 * fragments should not reach here.
11626 			 */
11627 
11628 			if (start + msgdsize(mp) !=
11629 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11630 				/*
11631 				 * We have two fragments both of which claim
11632 				 * to be the last fragment but gives conflicting
11633 				 * information about the whole datagram size.
11634 				 * Something fishy is going on. Drop the
11635 				 * fragment and free up the reassembly list.
11636 				 */
11637 				return (IP_REASS_FAILED);
11638 			}
11639 
11640 			/*
11641 			 * We shouldn't come to this code block again for this
11642 			 * particular fragment.
11643 			 */
11644 			pkt_boundary_checked = B_TRUE;
11645 		}
11646 
11647 		/* New stuff at or beyond tail? */
11648 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11649 		if (start >= offset) {
11650 			if (ipf->ipf_last_frag_seen) {
11651 				/* current fragment is beyond last fragment */
11652 				return (IP_REASS_FAILED);
11653 			}
11654 			/* Link it on end. */
11655 			ipf->ipf_tail_mp->b_cont = mp;
11656 			ipf->ipf_tail_mp = mp;
11657 			if (more) {
11658 				if (start != offset)
11659 					ipf->ipf_hole_cnt++;
11660 			} else if (start == offset && next_mp == NULL)
11661 					ipf->ipf_hole_cnt--;
11662 			continue;
11663 		}
11664 		mp1 = ipf->ipf_mp->b_cont;
11665 		offset = IP_REASS_START(mp1);
11666 		/* New stuff at the front? */
11667 		if (start < offset) {
11668 			if (start == 0) {
11669 				if (end >= offset) {
11670 					/* Nailed the hole at the begining. */
11671 					ipf->ipf_hole_cnt--;
11672 				}
11673 			} else if (end < offset) {
11674 				/*
11675 				 * A hole, stuff, and a hole where there used
11676 				 * to be just a hole.
11677 				 */
11678 				ipf->ipf_hole_cnt++;
11679 			}
11680 			mp->b_cont = mp1;
11681 			/* Check for overlap. */
11682 			while (end > offset) {
11683 				if (end < IP_REASS_END(mp1)) {
11684 					mp->b_wptr -= end - offset;
11685 					IP_REASS_SET_END(mp, offset);
11686 					BUMP_MIB(ill->ill_ip_mib,
11687 					    ipIfStatsReasmPartDups);
11688 					break;
11689 				}
11690 				/* Did we cover another hole? */
11691 				if ((mp1->b_cont &&
11692 				    IP_REASS_END(mp1) !=
11693 				    IP_REASS_START(mp1->b_cont) &&
11694 				    end >= IP_REASS_START(mp1->b_cont)) ||
11695 				    (!ipf->ipf_last_frag_seen && !more)) {
11696 					ipf->ipf_hole_cnt--;
11697 				}
11698 				/* Clip out mp1. */
11699 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11700 					/*
11701 					 * After clipping out mp1, this guy
11702 					 * is now hanging off the end.
11703 					 */
11704 					ipf->ipf_tail_mp = mp;
11705 				}
11706 				IP_REASS_SET_START(mp1, 0);
11707 				IP_REASS_SET_END(mp1, 0);
11708 				/* Subtract byte count */
11709 				ipf->ipf_count -= mp1->b_datap->db_lim -
11710 				    mp1->b_datap->db_base;
11711 				freeb(mp1);
11712 				BUMP_MIB(ill->ill_ip_mib,
11713 				    ipIfStatsReasmPartDups);
11714 				mp1 = mp->b_cont;
11715 				if (!mp1)
11716 					break;
11717 				offset = IP_REASS_START(mp1);
11718 			}
11719 			ipf->ipf_mp->b_cont = mp;
11720 			continue;
11721 		}
11722 		/*
11723 		 * The new piece starts somewhere between the start of the head
11724 		 * and before the end of the tail.
11725 		 */
11726 		for (; mp1; mp1 = mp1->b_cont) {
11727 			offset = IP_REASS_END(mp1);
11728 			if (start < offset) {
11729 				if (end <= offset) {
11730 					/* Nothing new. */
11731 					IP_REASS_SET_START(mp, 0);
11732 					IP_REASS_SET_END(mp, 0);
11733 					/* Subtract byte count */
11734 					ipf->ipf_count -= mp->b_datap->db_lim -
11735 					    mp->b_datap->db_base;
11736 					if (incr_dups) {
11737 						ipf->ipf_num_dups++;
11738 						incr_dups = B_FALSE;
11739 					}
11740 					freeb(mp);
11741 					BUMP_MIB(ill->ill_ip_mib,
11742 					    ipIfStatsReasmDuplicates);
11743 					break;
11744 				}
11745 				/*
11746 				 * Trim redundant stuff off beginning of new
11747 				 * piece.
11748 				 */
11749 				IP_REASS_SET_START(mp, offset);
11750 				mp->b_rptr += offset - start;
11751 				BUMP_MIB(ill->ill_ip_mib,
11752 				    ipIfStatsReasmPartDups);
11753 				start = offset;
11754 				if (!mp1->b_cont) {
11755 					/*
11756 					 * After trimming, this guy is now
11757 					 * hanging off the end.
11758 					 */
11759 					mp1->b_cont = mp;
11760 					ipf->ipf_tail_mp = mp;
11761 					if (!more) {
11762 						ipf->ipf_hole_cnt--;
11763 					}
11764 					break;
11765 				}
11766 			}
11767 			if (start >= IP_REASS_START(mp1->b_cont))
11768 				continue;
11769 			/* Fill a hole */
11770 			if (start > offset)
11771 				ipf->ipf_hole_cnt++;
11772 			mp->b_cont = mp1->b_cont;
11773 			mp1->b_cont = mp;
11774 			mp1 = mp->b_cont;
11775 			offset = IP_REASS_START(mp1);
11776 			if (end >= offset) {
11777 				ipf->ipf_hole_cnt--;
11778 				/* Check for overlap. */
11779 				while (end > offset) {
11780 					if (end < IP_REASS_END(mp1)) {
11781 						mp->b_wptr -= end - offset;
11782 						IP_REASS_SET_END(mp, offset);
11783 						/*
11784 						 * TODO we might bump
11785 						 * this up twice if there is
11786 						 * overlap at both ends.
11787 						 */
11788 						BUMP_MIB(ill->ill_ip_mib,
11789 						    ipIfStatsReasmPartDups);
11790 						break;
11791 					}
11792 					/* Did we cover another hole? */
11793 					if ((mp1->b_cont &&
11794 					    IP_REASS_END(mp1)
11795 					    != IP_REASS_START(mp1->b_cont) &&
11796 					    end >=
11797 					    IP_REASS_START(mp1->b_cont)) ||
11798 					    (!ipf->ipf_last_frag_seen &&
11799 					    !more)) {
11800 						ipf->ipf_hole_cnt--;
11801 					}
11802 					/* Clip out mp1. */
11803 					if ((mp->b_cont = mp1->b_cont) ==
11804 					    NULL) {
11805 						/*
11806 						 * After clipping out mp1,
11807 						 * this guy is now hanging
11808 						 * off the end.
11809 						 */
11810 						ipf->ipf_tail_mp = mp;
11811 					}
11812 					IP_REASS_SET_START(mp1, 0);
11813 					IP_REASS_SET_END(mp1, 0);
11814 					/* Subtract byte count */
11815 					ipf->ipf_count -=
11816 					    mp1->b_datap->db_lim -
11817 					    mp1->b_datap->db_base;
11818 					freeb(mp1);
11819 					BUMP_MIB(ill->ill_ip_mib,
11820 					    ipIfStatsReasmPartDups);
11821 					mp1 = mp->b_cont;
11822 					if (!mp1)
11823 						break;
11824 					offset = IP_REASS_START(mp1);
11825 				}
11826 			}
11827 			break;
11828 		}
11829 	} while (start = end, mp = next_mp);
11830 
11831 	/* Fragment just processed could be the last one. Remember this fact */
11832 	if (!more)
11833 		ipf->ipf_last_frag_seen = B_TRUE;
11834 
11835 	/* Still got holes? */
11836 	if (ipf->ipf_hole_cnt)
11837 		return (IP_REASS_PARTIAL);
11838 	/* Clean up overloaded fields to avoid upstream disasters. */
11839 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11840 		IP_REASS_SET_START(mp1, 0);
11841 		IP_REASS_SET_END(mp1, 0);
11842 	}
11843 	return (IP_REASS_COMPLETE);
11844 }
11845 
11846 /*
11847  * ipsec processing for the fast path, used for input UDP Packets
11848  * Returns true if ready for passup to UDP.
11849  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
11850  * was an ESP-in-UDP packet, etc.).
11851  */
11852 static boolean_t
11853 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
11854     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
11855 {
11856 	uint32_t	ill_index;
11857 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
11858 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
11859 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
11860 	udp_t		*udp = connp->conn_udp;
11861 
11862 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11863 	/* The ill_index of the incoming ILL */
11864 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
11865 
11866 	/* pass packet up to the transport */
11867 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
11868 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
11869 		    NULL, mctl_present);
11870 		if (*first_mpp == NULL) {
11871 			return (B_FALSE);
11872 		}
11873 	}
11874 
11875 	/* Initiate IPPF processing for fastpath UDP */
11876 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
11877 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
11878 		if (*mpp == NULL) {
11879 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
11880 			    "deferred/dropped during IPPF processing\n"));
11881 			return (B_FALSE);
11882 		}
11883 	}
11884 	/*
11885 	 * Remove 0-spi if it's 0, or move everything behind
11886 	 * the UDP header over it and forward to ESP via
11887 	 * ip_proto_input().
11888 	 */
11889 	if (udp->udp_nat_t_endpoint) {
11890 		if (mctl_present) {
11891 			/* mctl_present *shouldn't* happen. */
11892 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
11893 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
11894 			    &ipss->ipsec_dropper);
11895 			*first_mpp = NULL;
11896 			return (B_FALSE);
11897 		}
11898 
11899 		/* "ill" is "recv_ill" in actuality. */
11900 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
11901 			return (B_FALSE);
11902 
11903 		/* Else continue like a normal UDP packet. */
11904 	}
11905 
11906 	/*
11907 	 * We make the checks as below since we are in the fast path
11908 	 * and want to minimize the number of checks if the IP_RECVIF and/or
11909 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
11910 	 */
11911 	if (connp->conn_recvif || connp->conn_recvslla ||
11912 	    connp->conn_ip_recvpktinfo) {
11913 		if (connp->conn_recvif) {
11914 			in_flags = IPF_RECVIF;
11915 		}
11916 		/*
11917 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
11918 		 * so the flag passed to ip_add_info is based on IP version
11919 		 * of connp.
11920 		 */
11921 		if (connp->conn_ip_recvpktinfo) {
11922 			if (connp->conn_af_isv6) {
11923 				/*
11924 				 * V6 only needs index
11925 				 */
11926 				in_flags |= IPF_RECVIF;
11927 			} else {
11928 				/*
11929 				 * V4 needs index + matching address.
11930 				 */
11931 				in_flags |= IPF_RECVADDR;
11932 			}
11933 		}
11934 		if (connp->conn_recvslla) {
11935 			in_flags |= IPF_RECVSLLA;
11936 		}
11937 		/*
11938 		 * since in_flags are being set ill will be
11939 		 * referenced in ip_add_info, so it better not
11940 		 * be NULL.
11941 		 */
11942 		/*
11943 		 * the actual data will be contained in b_cont
11944 		 * upon successful return of the following call.
11945 		 * If the call fails then the original mblk is
11946 		 * returned.
11947 		 */
11948 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
11949 		    ipst);
11950 	}
11951 
11952 	return (B_TRUE);
11953 }
11954 
11955 /*
11956  * Fragmentation reassembly.  Each ILL has a hash table for
11957  * queuing packets undergoing reassembly for all IPIFs
11958  * associated with the ILL.  The hash is based on the packet
11959  * IP ident field.  The ILL frag hash table was allocated
11960  * as a timer block at the time the ILL was created.  Whenever
11961  * there is anything on the reassembly queue, the timer will
11962  * be running.  Returns B_TRUE if successful else B_FALSE;
11963  * frees mp on failure.
11964  */
11965 static boolean_t
11966 ip_rput_fragment(ill_t *ill, ill_t *recv_ill, mblk_t **mpp, ipha_t *ipha,
11967     uint32_t *cksum_val, uint16_t *cksum_flags)
11968 {
11969 	uint32_t	frag_offset_flags;
11970 	mblk_t		*mp = *mpp;
11971 	mblk_t		*t_mp;
11972 	ipaddr_t	dst;
11973 	uint8_t		proto = ipha->ipha_protocol;
11974 	uint32_t	sum_val;
11975 	uint16_t	sum_flags;
11976 	ipf_t		*ipf;
11977 	ipf_t		**ipfp;
11978 	ipfb_t		*ipfb;
11979 	uint16_t	ident;
11980 	uint32_t	offset;
11981 	ipaddr_t	src;
11982 	uint_t		hdr_length;
11983 	uint32_t	end;
11984 	mblk_t		*mp1;
11985 	mblk_t		*tail_mp;
11986 	size_t		count;
11987 	size_t		msg_len;
11988 	uint8_t		ecn_info = 0;
11989 	uint32_t	packet_size;
11990 	boolean_t	pruned = B_FALSE;
11991 	ip_stack_t *ipst = ill->ill_ipst;
11992 
11993 	if (cksum_val != NULL)
11994 		*cksum_val = 0;
11995 	if (cksum_flags != NULL)
11996 		*cksum_flags = 0;
11997 
11998 	/*
11999 	 * Drop the fragmented as early as possible, if
12000 	 * we don't have resource(s) to re-assemble.
12001 	 */
12002 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12003 		freemsg(mp);
12004 		return (B_FALSE);
12005 	}
12006 
12007 	/* Check for fragmentation offset; return if there's none */
12008 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12009 	    (IPH_MF | IPH_OFFSET)) == 0)
12010 		return (B_TRUE);
12011 
12012 	/*
12013 	 * We utilize hardware computed checksum info only for UDP since
12014 	 * IP fragmentation is a normal occurrence for the protocol.  In
12015 	 * addition, checksum offload support for IP fragments carrying
12016 	 * UDP payload is commonly implemented across network adapters.
12017 	 */
12018 	ASSERT(recv_ill != NULL);
12019 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(recv_ill) &&
12020 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12021 		mblk_t *mp1 = mp->b_cont;
12022 		int32_t len;
12023 
12024 		/* Record checksum information from the packet */
12025 		sum_val = (uint32_t)DB_CKSUM16(mp);
12026 		sum_flags = DB_CKSUMFLAGS(mp);
12027 
12028 		/* IP payload offset from beginning of mblk */
12029 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12030 
12031 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12032 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12033 		    offset >= DB_CKSUMSTART(mp) &&
12034 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12035 			uint32_t adj;
12036 			/*
12037 			 * Partial checksum has been calculated by hardware
12038 			 * and attached to the packet; in addition, any
12039 			 * prepended extraneous data is even byte aligned.
12040 			 * If any such data exists, we adjust the checksum;
12041 			 * this would also handle any postpended data.
12042 			 */
12043 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12044 			    mp, mp1, len, adj);
12045 
12046 			/* One's complement subtract extraneous checksum */
12047 			if (adj >= sum_val)
12048 				sum_val = ~(adj - sum_val) & 0xFFFF;
12049 			else
12050 				sum_val -= adj;
12051 		}
12052 	} else {
12053 		sum_val = 0;
12054 		sum_flags = 0;
12055 	}
12056 
12057 	/* Clear hardware checksumming flag */
12058 	DB_CKSUMFLAGS(mp) = 0;
12059 
12060 	ident = ipha->ipha_ident;
12061 	offset = (frag_offset_flags << 3) & 0xFFFF;
12062 	src = ipha->ipha_src;
12063 	dst = ipha->ipha_dst;
12064 	hdr_length = IPH_HDR_LENGTH(ipha);
12065 	end = ntohs(ipha->ipha_length) - hdr_length;
12066 
12067 	/* If end == 0 then we have a packet with no data, so just free it */
12068 	if (end == 0) {
12069 		freemsg(mp);
12070 		return (B_FALSE);
12071 	}
12072 
12073 	/* Record the ECN field info. */
12074 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12075 	if (offset != 0) {
12076 		/*
12077 		 * If this isn't the first piece, strip the header, and
12078 		 * add the offset to the end value.
12079 		 */
12080 		mp->b_rptr += hdr_length;
12081 		end += offset;
12082 	}
12083 
12084 	msg_len = MBLKSIZE(mp);
12085 	tail_mp = mp;
12086 	while (tail_mp->b_cont != NULL) {
12087 		tail_mp = tail_mp->b_cont;
12088 		msg_len += MBLKSIZE(tail_mp);
12089 	}
12090 
12091 	/* If the reassembly list for this ILL will get too big, prune it */
12092 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12093 	    ipst->ips_ip_reass_queue_bytes) {
12094 		ill_frag_prune(ill,
12095 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12096 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12097 		pruned = B_TRUE;
12098 	}
12099 
12100 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12101 	mutex_enter(&ipfb->ipfb_lock);
12102 
12103 	ipfp = &ipfb->ipfb_ipf;
12104 	/* Try to find an existing fragment queue for this packet. */
12105 	for (;;) {
12106 		ipf = ipfp[0];
12107 		if (ipf != NULL) {
12108 			/*
12109 			 * It has to match on ident and src/dst address.
12110 			 */
12111 			if (ipf->ipf_ident == ident &&
12112 			    ipf->ipf_src == src &&
12113 			    ipf->ipf_dst == dst &&
12114 			    ipf->ipf_protocol == proto) {
12115 				/*
12116 				 * If we have received too many
12117 				 * duplicate fragments for this packet
12118 				 * free it.
12119 				 */
12120 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12121 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12122 					freemsg(mp);
12123 					mutex_exit(&ipfb->ipfb_lock);
12124 					return (B_FALSE);
12125 				}
12126 				/* Found it. */
12127 				break;
12128 			}
12129 			ipfp = &ipf->ipf_hash_next;
12130 			continue;
12131 		}
12132 
12133 		/*
12134 		 * If we pruned the list, do we want to store this new
12135 		 * fragment?. We apply an optimization here based on the
12136 		 * fact that most fragments will be received in order.
12137 		 * So if the offset of this incoming fragment is zero,
12138 		 * it is the first fragment of a new packet. We will
12139 		 * keep it.  Otherwise drop the fragment, as we have
12140 		 * probably pruned the packet already (since the
12141 		 * packet cannot be found).
12142 		 */
12143 		if (pruned && offset != 0) {
12144 			mutex_exit(&ipfb->ipfb_lock);
12145 			freemsg(mp);
12146 			return (B_FALSE);
12147 		}
12148 
12149 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12150 			/*
12151 			 * Too many fragmented packets in this hash
12152 			 * bucket. Free the oldest.
12153 			 */
12154 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12155 		}
12156 
12157 		/* New guy.  Allocate a frag message. */
12158 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12159 		if (mp1 == NULL) {
12160 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12161 			freemsg(mp);
12162 reass_done:
12163 			mutex_exit(&ipfb->ipfb_lock);
12164 			return (B_FALSE);
12165 		}
12166 
12167 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12168 		mp1->b_cont = mp;
12169 
12170 		/* Initialize the fragment header. */
12171 		ipf = (ipf_t *)mp1->b_rptr;
12172 		ipf->ipf_mp = mp1;
12173 		ipf->ipf_ptphn = ipfp;
12174 		ipfp[0] = ipf;
12175 		ipf->ipf_hash_next = NULL;
12176 		ipf->ipf_ident = ident;
12177 		ipf->ipf_protocol = proto;
12178 		ipf->ipf_src = src;
12179 		ipf->ipf_dst = dst;
12180 		ipf->ipf_nf_hdr_len = 0;
12181 		/* Record reassembly start time. */
12182 		ipf->ipf_timestamp = gethrestime_sec();
12183 		/* Record ipf generation and account for frag header */
12184 		ipf->ipf_gen = ill->ill_ipf_gen++;
12185 		ipf->ipf_count = MBLKSIZE(mp1);
12186 		ipf->ipf_last_frag_seen = B_FALSE;
12187 		ipf->ipf_ecn = ecn_info;
12188 		ipf->ipf_num_dups = 0;
12189 		ipfb->ipfb_frag_pkts++;
12190 		ipf->ipf_checksum = 0;
12191 		ipf->ipf_checksum_flags = 0;
12192 
12193 		/* Store checksum value in fragment header */
12194 		if (sum_flags != 0) {
12195 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12196 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12197 			ipf->ipf_checksum = sum_val;
12198 			ipf->ipf_checksum_flags = sum_flags;
12199 		}
12200 
12201 		/*
12202 		 * We handle reassembly two ways.  In the easy case,
12203 		 * where all the fragments show up in order, we do
12204 		 * minimal bookkeeping, and just clip new pieces on
12205 		 * the end.  If we ever see a hole, then we go off
12206 		 * to ip_reassemble which has to mark the pieces and
12207 		 * keep track of the number of holes, etc.  Obviously,
12208 		 * the point of having both mechanisms is so we can
12209 		 * handle the easy case as efficiently as possible.
12210 		 */
12211 		if (offset == 0) {
12212 			/* Easy case, in-order reassembly so far. */
12213 			ipf->ipf_count += msg_len;
12214 			ipf->ipf_tail_mp = tail_mp;
12215 			/*
12216 			 * Keep track of next expected offset in
12217 			 * ipf_end.
12218 			 */
12219 			ipf->ipf_end = end;
12220 			ipf->ipf_nf_hdr_len = hdr_length;
12221 		} else {
12222 			/* Hard case, hole at the beginning. */
12223 			ipf->ipf_tail_mp = NULL;
12224 			/*
12225 			 * ipf_end == 0 means that we have given up
12226 			 * on easy reassembly.
12227 			 */
12228 			ipf->ipf_end = 0;
12229 
12230 			/* Forget checksum offload from now on */
12231 			ipf->ipf_checksum_flags = 0;
12232 
12233 			/*
12234 			 * ipf_hole_cnt is set by ip_reassemble.
12235 			 * ipf_count is updated by ip_reassemble.
12236 			 * No need to check for return value here
12237 			 * as we don't expect reassembly to complete
12238 			 * or fail for the first fragment itself.
12239 			 */
12240 			(void) ip_reassemble(mp, ipf,
12241 			    (frag_offset_flags & IPH_OFFSET) << 3,
12242 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12243 		}
12244 		/* Update per ipfb and ill byte counts */
12245 		ipfb->ipfb_count += ipf->ipf_count;
12246 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12247 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
12248 		/* If the frag timer wasn't already going, start it. */
12249 		mutex_enter(&ill->ill_lock);
12250 		ill_frag_timer_start(ill);
12251 		mutex_exit(&ill->ill_lock);
12252 		goto reass_done;
12253 	}
12254 
12255 	/*
12256 	 * If the packet's flag has changed (it could be coming up
12257 	 * from an interface different than the previous, therefore
12258 	 * possibly different checksum capability), then forget about
12259 	 * any stored checksum states.  Otherwise add the value to
12260 	 * the existing one stored in the fragment header.
12261 	 */
12262 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12263 		sum_val += ipf->ipf_checksum;
12264 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12265 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12266 		ipf->ipf_checksum = sum_val;
12267 	} else if (ipf->ipf_checksum_flags != 0) {
12268 		/* Forget checksum offload from now on */
12269 		ipf->ipf_checksum_flags = 0;
12270 	}
12271 
12272 	/*
12273 	 * We have a new piece of a datagram which is already being
12274 	 * reassembled.  Update the ECN info if all IP fragments
12275 	 * are ECN capable.  If there is one which is not, clear
12276 	 * all the info.  If there is at least one which has CE
12277 	 * code point, IP needs to report that up to transport.
12278 	 */
12279 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12280 		if (ecn_info == IPH_ECN_CE)
12281 			ipf->ipf_ecn = IPH_ECN_CE;
12282 	} else {
12283 		ipf->ipf_ecn = IPH_ECN_NECT;
12284 	}
12285 	if (offset && ipf->ipf_end == offset) {
12286 		/* The new fragment fits at the end */
12287 		ipf->ipf_tail_mp->b_cont = mp;
12288 		/* Update the byte count */
12289 		ipf->ipf_count += msg_len;
12290 		/* Update per ipfb and ill byte counts */
12291 		ipfb->ipfb_count += msg_len;
12292 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12293 		atomic_add_32(&ill->ill_frag_count, msg_len);
12294 		if (frag_offset_flags & IPH_MF) {
12295 			/* More to come. */
12296 			ipf->ipf_end = end;
12297 			ipf->ipf_tail_mp = tail_mp;
12298 			goto reass_done;
12299 		}
12300 	} else {
12301 		/* Go do the hard cases. */
12302 		int ret;
12303 
12304 		if (offset == 0)
12305 			ipf->ipf_nf_hdr_len = hdr_length;
12306 
12307 		/* Save current byte count */
12308 		count = ipf->ipf_count;
12309 		ret = ip_reassemble(mp, ipf,
12310 		    (frag_offset_flags & IPH_OFFSET) << 3,
12311 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12312 		/* Count of bytes added and subtracted (freeb()ed) */
12313 		count = ipf->ipf_count - count;
12314 		if (count) {
12315 			/* Update per ipfb and ill byte counts */
12316 			ipfb->ipfb_count += count;
12317 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12318 			atomic_add_32(&ill->ill_frag_count, count);
12319 		}
12320 		if (ret == IP_REASS_PARTIAL) {
12321 			goto reass_done;
12322 		} else if (ret == IP_REASS_FAILED) {
12323 			/* Reassembly failed. Free up all resources */
12324 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12325 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12326 				IP_REASS_SET_START(t_mp, 0);
12327 				IP_REASS_SET_END(t_mp, 0);
12328 			}
12329 			freemsg(mp);
12330 			goto reass_done;
12331 		}
12332 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12333 	}
12334 	/*
12335 	 * We have completed reassembly.  Unhook the frag header from
12336 	 * the reassembly list.
12337 	 *
12338 	 * Before we free the frag header, record the ECN info
12339 	 * to report back to the transport.
12340 	 */
12341 	ecn_info = ipf->ipf_ecn;
12342 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12343 	ipfp = ipf->ipf_ptphn;
12344 
12345 	/* We need to supply these to caller */
12346 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12347 		sum_val = ipf->ipf_checksum;
12348 	else
12349 		sum_val = 0;
12350 
12351 	mp1 = ipf->ipf_mp;
12352 	count = ipf->ipf_count;
12353 	ipf = ipf->ipf_hash_next;
12354 	if (ipf != NULL)
12355 		ipf->ipf_ptphn = ipfp;
12356 	ipfp[0] = ipf;
12357 	atomic_add_32(&ill->ill_frag_count, -count);
12358 	ASSERT(ipfb->ipfb_count >= count);
12359 	ipfb->ipfb_count -= count;
12360 	ipfb->ipfb_frag_pkts--;
12361 	mutex_exit(&ipfb->ipfb_lock);
12362 	/* Ditch the frag header. */
12363 	mp = mp1->b_cont;
12364 
12365 	freeb(mp1);
12366 
12367 	/* Restore original IP length in header. */
12368 	packet_size = (uint32_t)msgdsize(mp);
12369 	if (packet_size > IP_MAXPACKET) {
12370 		freemsg(mp);
12371 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12372 		return (B_FALSE);
12373 	}
12374 
12375 	if (DB_REF(mp) > 1) {
12376 		mblk_t *mp2 = copymsg(mp);
12377 
12378 		freemsg(mp);
12379 		if (mp2 == NULL) {
12380 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12381 			return (B_FALSE);
12382 		}
12383 		mp = mp2;
12384 	}
12385 	ipha = (ipha_t *)mp->b_rptr;
12386 
12387 	ipha->ipha_length = htons((uint16_t)packet_size);
12388 	/* We're now complete, zip the frag state */
12389 	ipha->ipha_fragment_offset_and_flags = 0;
12390 	/* Record the ECN info. */
12391 	ipha->ipha_type_of_service &= 0xFC;
12392 	ipha->ipha_type_of_service |= ecn_info;
12393 	*mpp = mp;
12394 
12395 	/* Reassembly is successful; return checksum information if needed */
12396 	if (cksum_val != NULL)
12397 		*cksum_val = sum_val;
12398 	if (cksum_flags != NULL)
12399 		*cksum_flags = sum_flags;
12400 
12401 	return (B_TRUE);
12402 }
12403 
12404 /*
12405  * Perform ip header check sum update local options.
12406  * return B_TRUE if all is well, else return B_FALSE and release
12407  * the mp. caller is responsible for decrementing ire ref cnt.
12408  */
12409 static boolean_t
12410 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12411     ip_stack_t *ipst)
12412 {
12413 	mblk_t		*first_mp;
12414 	boolean_t	mctl_present;
12415 	uint16_t	sum;
12416 
12417 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12418 	/*
12419 	 * Don't do the checksum if it has gone through AH/ESP
12420 	 * processing.
12421 	 */
12422 	if (!mctl_present) {
12423 		sum = ip_csum_hdr(ipha);
12424 		if (sum != 0) {
12425 			if (ill != NULL) {
12426 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12427 			} else {
12428 				BUMP_MIB(&ipst->ips_ip_mib,
12429 				    ipIfStatsInCksumErrs);
12430 			}
12431 			freemsg(first_mp);
12432 			return (B_FALSE);
12433 		}
12434 	}
12435 
12436 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12437 		if (mctl_present)
12438 			freeb(first_mp);
12439 		return (B_FALSE);
12440 	}
12441 
12442 	return (B_TRUE);
12443 }
12444 
12445 /*
12446  * All udp packet are delivered to the local host via this routine.
12447  */
12448 void
12449 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12450     ill_t *recv_ill)
12451 {
12452 	uint32_t	sum;
12453 	uint32_t	u1;
12454 	boolean_t	mctl_present;
12455 	conn_t		*connp;
12456 	mblk_t		*first_mp;
12457 	uint16_t	*up;
12458 	ill_t		*ill = (ill_t *)q->q_ptr;
12459 	uint16_t	reass_hck_flags = 0;
12460 	ip_stack_t	*ipst;
12461 
12462 	ASSERT(recv_ill != NULL);
12463 	ipst = recv_ill->ill_ipst;
12464 
12465 #define	rptr    ((uchar_t *)ipha)
12466 
12467 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12468 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12469 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12470 	ASSERT(ill != NULL);
12471 
12472 	/*
12473 	 * FAST PATH for udp packets
12474 	 */
12475 
12476 	/* u1 is # words of IP options */
12477 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12478 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12479 
12480 	/* IP options present */
12481 	if (u1 != 0)
12482 		goto ipoptions;
12483 
12484 	/* Check the IP header checksum.  */
12485 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12486 		/* Clear the IP header h/w cksum flag */
12487 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12488 	} else if (!mctl_present) {
12489 		/*
12490 		 * Don't verify header checksum if this packet is coming
12491 		 * back from AH/ESP as we already did it.
12492 		 */
12493 #define	uph	((uint16_t *)ipha)
12494 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12495 		    uph[6] + uph[7] + uph[8] + uph[9];
12496 #undef	uph
12497 		/* finish doing IP checksum */
12498 		sum = (sum & 0xFFFF) + (sum >> 16);
12499 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12500 		if (sum != 0 && sum != 0xFFFF) {
12501 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12502 			freemsg(first_mp);
12503 			return;
12504 		}
12505 	}
12506 
12507 	/*
12508 	 * Count for SNMP of inbound packets for ire.
12509 	 * if mctl is present this might be a secure packet and
12510 	 * has already been counted for in ip_proto_input().
12511 	 */
12512 	if (!mctl_present) {
12513 		UPDATE_IB_PKT_COUNT(ire);
12514 		ire->ire_last_used_time = lbolt;
12515 	}
12516 
12517 	/* packet part of fragmented IP packet? */
12518 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12519 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12520 		goto fragmented;
12521 	}
12522 
12523 	/* u1 = IP header length (20 bytes) */
12524 	u1 = IP_SIMPLE_HDR_LENGTH;
12525 
12526 	/* packet does not contain complete IP & UDP headers */
12527 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12528 		goto udppullup;
12529 
12530 	/* up points to UDP header */
12531 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12532 #define	iphs    ((uint16_t *)ipha)
12533 
12534 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12535 	if (up[3] != 0) {
12536 		mblk_t *mp1 = mp->b_cont;
12537 		boolean_t cksum_err;
12538 		uint16_t hck_flags = 0;
12539 
12540 		/* Pseudo-header checksum */
12541 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12542 		    iphs[9] + up[2];
12543 
12544 		/*
12545 		 * Revert to software checksum calculation if the interface
12546 		 * isn't capable of checksum offload or if IPsec is present.
12547 		 */
12548 		if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
12549 			hck_flags = DB_CKSUMFLAGS(mp);
12550 
12551 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12552 			IP_STAT(ipst, ip_in_sw_cksum);
12553 
12554 		IP_CKSUM_RECV(hck_flags, u1,
12555 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12556 		    (int32_t)((uchar_t *)up - rptr),
12557 		    mp, mp1, cksum_err);
12558 
12559 		if (cksum_err) {
12560 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12561 			if (hck_flags & HCK_FULLCKSUM)
12562 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12563 			else if (hck_flags & HCK_PARTIALCKSUM)
12564 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12565 			else
12566 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12567 
12568 			freemsg(first_mp);
12569 			return;
12570 		}
12571 	}
12572 
12573 	/* Non-fragmented broadcast or multicast packet? */
12574 	if (ire->ire_type == IRE_BROADCAST)
12575 		goto udpslowpath;
12576 
12577 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12578 	    ire->ire_zoneid, ipst)) != NULL) {
12579 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
12580 		IP_STAT(ipst, ip_udp_fast_path);
12581 
12582 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
12583 		    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
12584 			freemsg(mp);
12585 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12586 		} else {
12587 			if (!mctl_present) {
12588 				BUMP_MIB(ill->ill_ip_mib,
12589 				    ipIfStatsHCInDelivers);
12590 			}
12591 			/*
12592 			 * mp and first_mp can change.
12593 			 */
12594 			if (ip_udp_check(q, connp, recv_ill,
12595 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12596 				/* Send it upstream */
12597 				(connp->conn_recv)(connp, mp, NULL);
12598 			}
12599 		}
12600 		/*
12601 		 * freeb() cannot deal with null mblk being passed
12602 		 * in and first_mp can be set to null in the call
12603 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12604 		 */
12605 		if (mctl_present && first_mp != NULL) {
12606 			freeb(first_mp);
12607 		}
12608 		CONN_DEC_REF(connp);
12609 		return;
12610 	}
12611 
12612 	/*
12613 	 * if we got here we know the packet is not fragmented and
12614 	 * has no options. The classifier could not find a conn_t and
12615 	 * most likely its an icmp packet so send it through slow path.
12616 	 */
12617 
12618 	goto udpslowpath;
12619 
12620 ipoptions:
12621 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12622 		goto slow_done;
12623 	}
12624 
12625 	UPDATE_IB_PKT_COUNT(ire);
12626 	ire->ire_last_used_time = lbolt;
12627 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12628 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12629 fragmented:
12630 		/*
12631 		 * "sum" and "reass_hck_flags" are non-zero if the
12632 		 * reassembled packet has a valid hardware computed
12633 		 * checksum information associated with it.
12634 		 */
12635 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, &sum,
12636 		    &reass_hck_flags)) {
12637 			goto slow_done;
12638 		}
12639 
12640 		/*
12641 		 * Make sure that first_mp points back to mp as
12642 		 * the mp we came in with could have changed in
12643 		 * ip_rput_fragment().
12644 		 */
12645 		ASSERT(!mctl_present);
12646 		ipha = (ipha_t *)mp->b_rptr;
12647 		first_mp = mp;
12648 	}
12649 
12650 	/* Now we have a complete datagram, destined for this machine. */
12651 	u1 = IPH_HDR_LENGTH(ipha);
12652 	/* Pull up the UDP header, if necessary. */
12653 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12654 udppullup:
12655 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12656 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12657 			freemsg(first_mp);
12658 			goto slow_done;
12659 		}
12660 		ipha = (ipha_t *)mp->b_rptr;
12661 	}
12662 
12663 	/*
12664 	 * Validate the checksum for the reassembled packet; for the
12665 	 * pullup case we calculate the payload checksum in software.
12666 	 */
12667 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12668 	if (up[3] != 0) {
12669 		boolean_t cksum_err;
12670 
12671 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12672 			IP_STAT(ipst, ip_in_sw_cksum);
12673 
12674 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12675 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12676 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12677 		    iphs[9] + up[2], sum, cksum_err);
12678 
12679 		if (cksum_err) {
12680 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12681 
12682 			if (reass_hck_flags & HCK_FULLCKSUM)
12683 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12684 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12685 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12686 			else
12687 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12688 
12689 			freemsg(first_mp);
12690 			goto slow_done;
12691 		}
12692 	}
12693 udpslowpath:
12694 
12695 	/* Clear hardware checksum flag to be safe */
12696 	DB_CKSUMFLAGS(mp) = 0;
12697 
12698 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12699 	    (ire->ire_type == IRE_BROADCAST),
12700 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12701 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12702 
12703 slow_done:
12704 	IP_STAT(ipst, ip_udp_slow_path);
12705 	return;
12706 
12707 #undef  iphs
12708 #undef  rptr
12709 }
12710 
12711 /* ARGSUSED */
12712 static mblk_t *
12713 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12714     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12715     ill_rx_ring_t *ill_ring)
12716 {
12717 	conn_t		*connp;
12718 	uint32_t	sum;
12719 	uint32_t	u1;
12720 	uint16_t	*up;
12721 	int		offset;
12722 	ssize_t		len;
12723 	mblk_t		*mp1;
12724 	boolean_t	syn_present = B_FALSE;
12725 	tcph_t		*tcph;
12726 	uint_t		tcph_flags;
12727 	uint_t		ip_hdr_len;
12728 	ill_t		*ill = (ill_t *)q->q_ptr;
12729 	zoneid_t	zoneid = ire->ire_zoneid;
12730 	boolean_t	cksum_err;
12731 	uint16_t	hck_flags = 0;
12732 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12733 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12734 
12735 #define	rptr	((uchar_t *)ipha)
12736 
12737 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12738 	ASSERT(ill != NULL);
12739 
12740 	/*
12741 	 * FAST PATH for tcp packets
12742 	 */
12743 
12744 	/* u1 is # words of IP options */
12745 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12746 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12747 
12748 	/* IP options present */
12749 	if (u1) {
12750 		goto ipoptions;
12751 	} else if (!mctl_present) {
12752 		/* Check the IP header checksum.  */
12753 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12754 			/* Clear the IP header h/w cksum flag */
12755 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12756 		} else if (!mctl_present) {
12757 			/*
12758 			 * Don't verify header checksum if this packet
12759 			 * is coming back from AH/ESP as we already did it.
12760 			 */
12761 #define	uph	((uint16_t *)ipha)
12762 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12763 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12764 #undef	uph
12765 			/* finish doing IP checksum */
12766 			sum = (sum & 0xFFFF) + (sum >> 16);
12767 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12768 			if (sum != 0 && sum != 0xFFFF) {
12769 				BUMP_MIB(ill->ill_ip_mib,
12770 				    ipIfStatsInCksumErrs);
12771 				goto error;
12772 			}
12773 		}
12774 	}
12775 
12776 	if (!mctl_present) {
12777 		UPDATE_IB_PKT_COUNT(ire);
12778 		ire->ire_last_used_time = lbolt;
12779 	}
12780 
12781 	/* packet part of fragmented IP packet? */
12782 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12783 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12784 		goto fragmented;
12785 	}
12786 
12787 	/* u1 = IP header length (20 bytes) */
12788 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12789 
12790 	/* does packet contain IP+TCP headers? */
12791 	len = mp->b_wptr - rptr;
12792 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12793 		IP_STAT(ipst, ip_tcppullup);
12794 		goto tcppullup;
12795 	}
12796 
12797 	/* TCP options present? */
12798 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12799 
12800 	/*
12801 	 * If options need to be pulled up, then goto tcpoptions.
12802 	 * otherwise we are still in the fast path
12803 	 */
12804 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12805 		IP_STAT(ipst, ip_tcpoptions);
12806 		goto tcpoptions;
12807 	}
12808 
12809 	/* multiple mblks of tcp data? */
12810 	if ((mp1 = mp->b_cont) != NULL) {
12811 		/* more then two? */
12812 		if (mp1->b_cont != NULL) {
12813 			IP_STAT(ipst, ip_multipkttcp);
12814 			goto multipkttcp;
12815 		}
12816 		len += mp1->b_wptr - mp1->b_rptr;
12817 	}
12818 
12819 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12820 
12821 	/* part of pseudo checksum */
12822 
12823 	/* TCP datagram length */
12824 	u1 = len - IP_SIMPLE_HDR_LENGTH;
12825 
12826 #define	iphs    ((uint16_t *)ipha)
12827 
12828 #ifdef	_BIG_ENDIAN
12829 	u1 += IPPROTO_TCP;
12830 #else
12831 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12832 #endif
12833 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12834 
12835 	/*
12836 	 * Revert to software checksum calculation if the interface
12837 	 * isn't capable of checksum offload or if IPsec is present.
12838 	 */
12839 	if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
12840 		hck_flags = DB_CKSUMFLAGS(mp);
12841 
12842 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12843 		IP_STAT(ipst, ip_in_sw_cksum);
12844 
12845 	IP_CKSUM_RECV(hck_flags, u1,
12846 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12847 	    (int32_t)((uchar_t *)up - rptr),
12848 	    mp, mp1, cksum_err);
12849 
12850 	if (cksum_err) {
12851 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
12852 
12853 		if (hck_flags & HCK_FULLCKSUM)
12854 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
12855 		else if (hck_flags & HCK_PARTIALCKSUM)
12856 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
12857 		else
12858 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
12859 
12860 		goto error;
12861 	}
12862 
12863 try_again:
12864 
12865 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
12866 	    zoneid, ipst)) == NULL) {
12867 		/* Send the TH_RST */
12868 		goto no_conn;
12869 	}
12870 
12871 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
12872 	tcph_flags = tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG);
12873 
12874 	/*
12875 	 * TCP FAST PATH for AF_INET socket.
12876 	 *
12877 	 * TCP fast path to avoid extra work. An AF_INET socket type
12878 	 * does not have facility to receive extra information via
12879 	 * ip_process or ip_add_info. Also, when the connection was
12880 	 * established, we made a check if this connection is impacted
12881 	 * by any global IPsec policy or per connection policy (a
12882 	 * policy that comes in effect later will not apply to this
12883 	 * connection). Since all this can be determined at the
12884 	 * connection establishment time, a quick check of flags
12885 	 * can avoid extra work.
12886 	 */
12887 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
12888 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12889 		ASSERT(first_mp == mp);
12890 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
12891 		if (tcph_flags != (TH_SYN | TH_ACK)) {
12892 			SET_SQUEUE(mp, tcp_rput_data, connp);
12893 			return (mp);
12894 		}
12895 		mp->b_datap->db_struioflag |= STRUIO_CONNECT;
12896 		DB_CKSUMSTART(mp) = (intptr_t)ip_squeue_get(ill_ring);
12897 		SET_SQUEUE(mp, tcp_input, connp);
12898 		return (mp);
12899 	}
12900 
12901 	if (tcph_flags == TH_SYN) {
12902 		if (IPCL_IS_TCP(connp)) {
12903 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
12904 			DB_CKSUMSTART(mp) =
12905 			    (intptr_t)ip_squeue_get(ill_ring);
12906 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
12907 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
12908 				BUMP_MIB(ill->ill_ip_mib,
12909 				    ipIfStatsHCInDelivers);
12910 				SET_SQUEUE(mp, connp->conn_recv, connp);
12911 				return (mp);
12912 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
12913 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
12914 				BUMP_MIB(ill->ill_ip_mib,
12915 				    ipIfStatsHCInDelivers);
12916 				ip_squeue_enter_unbound++;
12917 				SET_SQUEUE(mp, tcp_conn_request_unbound,
12918 				    connp);
12919 				return (mp);
12920 			}
12921 			syn_present = B_TRUE;
12922 		}
12923 	}
12924 
12925 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
12926 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12927 
12928 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
12929 		/* No need to send this packet to TCP */
12930 		if ((flags & TH_RST) || (flags & TH_URG)) {
12931 			CONN_DEC_REF(connp);
12932 			freemsg(first_mp);
12933 			return (NULL);
12934 		}
12935 		if (flags & TH_ACK) {
12936 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
12937 			    ipst->ips_netstack->netstack_tcp, connp);
12938 			CONN_DEC_REF(connp);
12939 			return (NULL);
12940 		}
12941 
12942 		CONN_DEC_REF(connp);
12943 		freemsg(first_mp);
12944 		return (NULL);
12945 	}
12946 
12947 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12948 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
12949 		    ipha, NULL, mctl_present);
12950 		if (first_mp == NULL) {
12951 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12952 			CONN_DEC_REF(connp);
12953 			return (NULL);
12954 		}
12955 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
12956 			ASSERT(syn_present);
12957 			if (mctl_present) {
12958 				ASSERT(first_mp != mp);
12959 				first_mp->b_datap->db_struioflag |=
12960 				    STRUIO_POLICY;
12961 			} else {
12962 				ASSERT(first_mp == mp);
12963 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
12964 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
12965 			}
12966 		} else {
12967 			/*
12968 			 * Discard first_mp early since we're dealing with a
12969 			 * fully-connected conn_t and tcp doesn't do policy in
12970 			 * this case.
12971 			 */
12972 			if (mctl_present) {
12973 				freeb(first_mp);
12974 				mctl_present = B_FALSE;
12975 			}
12976 			first_mp = mp;
12977 		}
12978 	}
12979 
12980 	/* Initiate IPPF processing for fastpath */
12981 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12982 		uint32_t	ill_index;
12983 
12984 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
12985 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
12986 		if (mp == NULL) {
12987 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
12988 			    "deferred/dropped during IPPF processing\n"));
12989 			CONN_DEC_REF(connp);
12990 			if (mctl_present)
12991 				freeb(first_mp);
12992 			return (NULL);
12993 		} else if (mctl_present) {
12994 			/*
12995 			 * ip_process might return a new mp.
12996 			 */
12997 			ASSERT(first_mp != mp);
12998 			first_mp->b_cont = mp;
12999 		} else {
13000 			first_mp = mp;
13001 		}
13002 
13003 	}
13004 
13005 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13006 		/*
13007 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13008 		 * make sure IPF_RECVIF is passed to ip_add_info.
13009 		 */
13010 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13011 		    IPCL_ZONEID(connp), ipst);
13012 		if (mp == NULL) {
13013 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13014 			CONN_DEC_REF(connp);
13015 			if (mctl_present)
13016 				freeb(first_mp);
13017 			return (NULL);
13018 		} else if (mctl_present) {
13019 			/*
13020 			 * ip_add_info might return a new mp.
13021 			 */
13022 			ASSERT(first_mp != mp);
13023 			first_mp->b_cont = mp;
13024 		} else {
13025 			first_mp = mp;
13026 		}
13027 	}
13028 
13029 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13030 	if (IPCL_IS_TCP(connp)) {
13031 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13032 		return (first_mp);
13033 	} else {
13034 		/* SOCK_RAW, IPPROTO_TCP case */
13035 		(connp->conn_recv)(connp, first_mp, NULL);
13036 		CONN_DEC_REF(connp);
13037 		return (NULL);
13038 	}
13039 
13040 no_conn:
13041 	/* Initiate IPPf processing, if needed. */
13042 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13043 		uint32_t ill_index;
13044 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13045 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13046 		if (first_mp == NULL) {
13047 			return (NULL);
13048 		}
13049 	}
13050 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13051 
13052 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13053 	    ipst->ips_netstack->netstack_tcp, NULL);
13054 	return (NULL);
13055 ipoptions:
13056 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13057 		goto slow_done;
13058 	}
13059 
13060 	UPDATE_IB_PKT_COUNT(ire);
13061 	ire->ire_last_used_time = lbolt;
13062 
13063 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13064 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13065 fragmented:
13066 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL)) {
13067 			if (mctl_present)
13068 				freeb(first_mp);
13069 			goto slow_done;
13070 		}
13071 		/*
13072 		 * Make sure that first_mp points back to mp as
13073 		 * the mp we came in with could have changed in
13074 		 * ip_rput_fragment().
13075 		 */
13076 		ASSERT(!mctl_present);
13077 		ipha = (ipha_t *)mp->b_rptr;
13078 		first_mp = mp;
13079 	}
13080 
13081 	/* Now we have a complete datagram, destined for this machine. */
13082 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13083 
13084 	len = mp->b_wptr - mp->b_rptr;
13085 	/* Pull up a minimal TCP header, if necessary. */
13086 	if (len < (u1 + 20)) {
13087 tcppullup:
13088 		if (!pullupmsg(mp, u1 + 20)) {
13089 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13090 			goto error;
13091 		}
13092 		ipha = (ipha_t *)mp->b_rptr;
13093 		len = mp->b_wptr - mp->b_rptr;
13094 	}
13095 
13096 	/*
13097 	 * Extract the offset field from the TCP header.  As usual, we
13098 	 * try to help the compiler more than the reader.
13099 	 */
13100 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13101 	if (offset != 5) {
13102 tcpoptions:
13103 		if (offset < 5) {
13104 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13105 			goto error;
13106 		}
13107 		/*
13108 		 * There must be TCP options.
13109 		 * Make sure we can grab them.
13110 		 */
13111 		offset <<= 2;
13112 		offset += u1;
13113 		if (len < offset) {
13114 			if (!pullupmsg(mp, offset)) {
13115 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13116 				goto error;
13117 			}
13118 			ipha = (ipha_t *)mp->b_rptr;
13119 			len = mp->b_wptr - rptr;
13120 		}
13121 	}
13122 
13123 	/* Get the total packet length in len, including headers. */
13124 	if (mp->b_cont) {
13125 multipkttcp:
13126 		len = msgdsize(mp);
13127 	}
13128 
13129 	/*
13130 	 * Check the TCP checksum by pulling together the pseudo-
13131 	 * header checksum, and passing it to ip_csum to be added in
13132 	 * with the TCP datagram.
13133 	 *
13134 	 * Since we are not using the hwcksum if available we must
13135 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13136 	 * If either of these fails along the way the mblk is freed.
13137 	 * If this logic ever changes and mblk is reused to say send
13138 	 * ICMP's back, then this flag may need to be cleared in
13139 	 * other places as well.
13140 	 */
13141 	DB_CKSUMFLAGS(mp) = 0;
13142 
13143 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13144 
13145 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13146 #ifdef	_BIG_ENDIAN
13147 	u1 += IPPROTO_TCP;
13148 #else
13149 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13150 #endif
13151 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13152 	/*
13153 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13154 	 */
13155 	IP_STAT(ipst, ip_in_sw_cksum);
13156 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13157 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13158 		goto error;
13159 	}
13160 
13161 	IP_STAT(ipst, ip_tcp_slow_path);
13162 	goto try_again;
13163 #undef  iphs
13164 #undef  rptr
13165 
13166 error:
13167 	freemsg(first_mp);
13168 slow_done:
13169 	return (NULL);
13170 }
13171 
13172 /* ARGSUSED */
13173 static void
13174 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13175     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13176 {
13177 	conn_t		*connp;
13178 	uint32_t	sum;
13179 	uint32_t	u1;
13180 	ssize_t		len;
13181 	sctp_hdr_t	*sctph;
13182 	zoneid_t	zoneid = ire->ire_zoneid;
13183 	uint32_t	pktsum;
13184 	uint32_t	calcsum;
13185 	uint32_t	ports;
13186 	in6_addr_t	map_src, map_dst;
13187 	ill_t		*ill = (ill_t *)q->q_ptr;
13188 	ip_stack_t	*ipst;
13189 	sctp_stack_t	*sctps;
13190 	boolean_t	sctp_csum_err = B_FALSE;
13191 
13192 	ASSERT(recv_ill != NULL);
13193 	ipst = recv_ill->ill_ipst;
13194 	sctps = ipst->ips_netstack->netstack_sctp;
13195 
13196 #define	rptr	((uchar_t *)ipha)
13197 
13198 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13199 	ASSERT(ill != NULL);
13200 
13201 	/* u1 is # words of IP options */
13202 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13203 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13204 
13205 	/* IP options present */
13206 	if (u1 > 0) {
13207 		goto ipoptions;
13208 	} else {
13209 		/* Check the IP header checksum.  */
13210 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill) &&
13211 		    !mctl_present) {
13212 #define	uph	((uint16_t *)ipha)
13213 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13214 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13215 #undef	uph
13216 			/* finish doing IP checksum */
13217 			sum = (sum & 0xFFFF) + (sum >> 16);
13218 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13219 			/*
13220 			 * Don't verify header checksum if this packet
13221 			 * is coming back from AH/ESP as we already did it.
13222 			 */
13223 			if (sum != 0 && sum != 0xFFFF) {
13224 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13225 				goto error;
13226 			}
13227 		}
13228 		/*
13229 		 * Since there is no SCTP h/w cksum support yet, just
13230 		 * clear the flag.
13231 		 */
13232 		DB_CKSUMFLAGS(mp) = 0;
13233 	}
13234 
13235 	/*
13236 	 * Don't verify header checksum if this packet is coming
13237 	 * back from AH/ESP as we already did it.
13238 	 */
13239 	if (!mctl_present) {
13240 		UPDATE_IB_PKT_COUNT(ire);
13241 		ire->ire_last_used_time = lbolt;
13242 	}
13243 
13244 	/* packet part of fragmented IP packet? */
13245 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13246 	if (u1 & (IPH_MF | IPH_OFFSET))
13247 		goto fragmented;
13248 
13249 	/* u1 = IP header length (20 bytes) */
13250 	u1 = IP_SIMPLE_HDR_LENGTH;
13251 
13252 find_sctp_client:
13253 	/* Pullup if we don't have the sctp common header. */
13254 	len = MBLKL(mp);
13255 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13256 		if (mp->b_cont == NULL ||
13257 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13258 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13259 			goto error;
13260 		}
13261 		ipha = (ipha_t *)mp->b_rptr;
13262 		len = MBLKL(mp);
13263 	}
13264 
13265 	sctph = (sctp_hdr_t *)(rptr + u1);
13266 #ifdef	DEBUG
13267 	if (!skip_sctp_cksum) {
13268 #endif
13269 		pktsum = sctph->sh_chksum;
13270 		sctph->sh_chksum = 0;
13271 		calcsum = sctp_cksum(mp, u1);
13272 		sctph->sh_chksum = pktsum;
13273 		if (calcsum != pktsum)
13274 			sctp_csum_err = B_TRUE;
13275 #ifdef	DEBUG	/* skip_sctp_cksum */
13276 	}
13277 #endif
13278 	/* get the ports */
13279 	ports = *(uint32_t *)&sctph->sh_sport;
13280 
13281 	IRE_REFRELE(ire);
13282 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13283 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13284 	if (sctp_csum_err) {
13285 		/*
13286 		 * No potential sctp checksum errors go to the Sun
13287 		 * sctp stack however they might be Adler-32 summed
13288 		 * packets a userland stack bound to a raw IP socket
13289 		 * could reasonably use. Note though that Adler-32 is
13290 		 * a long deprecated algorithm and customer sctp
13291 		 * networks should eventually migrate to CRC-32 at
13292 		 * which time this facility should be removed.
13293 		 */
13294 		flags |= IP_FF_SCTP_CSUM_ERR;
13295 		goto no_conn;
13296 	}
13297 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13298 	    sctps)) == NULL) {
13299 		/* Check for raw socket or OOTB handling */
13300 		goto no_conn;
13301 	}
13302 
13303 	/* Found a client; up it goes */
13304 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13305 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13306 	return;
13307 
13308 no_conn:
13309 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13310 	    ports, mctl_present, flags, B_TRUE, zoneid);
13311 	return;
13312 
13313 ipoptions:
13314 	DB_CKSUMFLAGS(mp) = 0;
13315 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13316 		goto slow_done;
13317 
13318 	UPDATE_IB_PKT_COUNT(ire);
13319 	ire->ire_last_used_time = lbolt;
13320 
13321 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13322 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13323 fragmented:
13324 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
13325 			goto slow_done;
13326 		/*
13327 		 * Make sure that first_mp points back to mp as
13328 		 * the mp we came in with could have changed in
13329 		 * ip_rput_fragment().
13330 		 */
13331 		ASSERT(!mctl_present);
13332 		ipha = (ipha_t *)mp->b_rptr;
13333 		first_mp = mp;
13334 	}
13335 
13336 	/* Now we have a complete datagram, destined for this machine. */
13337 	u1 = IPH_HDR_LENGTH(ipha);
13338 	goto find_sctp_client;
13339 #undef  iphs
13340 #undef  rptr
13341 
13342 error:
13343 	freemsg(first_mp);
13344 slow_done:
13345 	IRE_REFRELE(ire);
13346 }
13347 
13348 #define	VER_BITS	0xF0
13349 #define	VERSION_6	0x60
13350 
13351 static boolean_t
13352 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13353     ipaddr_t *dstp, ip_stack_t *ipst)
13354 {
13355 	uint_t	opt_len;
13356 	ipha_t *ipha;
13357 	ssize_t len;
13358 	uint_t	pkt_len;
13359 
13360 	ASSERT(ill != NULL);
13361 	IP_STAT(ipst, ip_ipoptions);
13362 	ipha = *iphapp;
13363 
13364 #define	rptr    ((uchar_t *)ipha)
13365 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13366 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13367 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13368 		freemsg(mp);
13369 		return (B_FALSE);
13370 	}
13371 
13372 	/* multiple mblk or too short */
13373 	pkt_len = ntohs(ipha->ipha_length);
13374 
13375 	/* Get the number of words of IP options in the IP header. */
13376 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13377 	if (opt_len) {
13378 		/* IP Options present!  Validate and process. */
13379 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13380 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13381 			goto done;
13382 		}
13383 		/*
13384 		 * Recompute complete header length and make sure we
13385 		 * have access to all of it.
13386 		 */
13387 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13388 		if (len > (mp->b_wptr - rptr)) {
13389 			if (len > pkt_len) {
13390 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13391 				goto done;
13392 			}
13393 			if (!pullupmsg(mp, len)) {
13394 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13395 				goto done;
13396 			}
13397 			ipha = (ipha_t *)mp->b_rptr;
13398 		}
13399 		/*
13400 		 * Go off to ip_rput_options which returns the next hop
13401 		 * destination address, which may have been affected
13402 		 * by source routing.
13403 		 */
13404 		IP_STAT(ipst, ip_opt);
13405 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13406 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13407 			return (B_FALSE);
13408 		}
13409 	}
13410 	*iphapp = ipha;
13411 	return (B_TRUE);
13412 done:
13413 	/* clear b_prev - used by ip_mroute_decap */
13414 	mp->b_prev = NULL;
13415 	freemsg(mp);
13416 	return (B_FALSE);
13417 #undef  rptr
13418 }
13419 
13420 /*
13421  * Deal with the fact that there is no ire for the destination.
13422  */
13423 static ire_t *
13424 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13425 {
13426 	ipha_t	*ipha;
13427 	ill_t	*ill;
13428 	ire_t	*ire;
13429 	ip_stack_t *ipst;
13430 	enum	ire_forward_action ret_action;
13431 
13432 	ipha = (ipha_t *)mp->b_rptr;
13433 	ill = (ill_t *)q->q_ptr;
13434 
13435 	ASSERT(ill != NULL);
13436 	ipst = ill->ill_ipst;
13437 
13438 	/*
13439 	 * No IRE for this destination, so it can't be for us.
13440 	 * Unless we are forwarding, drop the packet.
13441 	 * We have to let source routed packets through
13442 	 * since we don't yet know if they are 'ping -l'
13443 	 * packets i.e. if they will go out over the
13444 	 * same interface as they came in on.
13445 	 */
13446 	if (ll_multicast) {
13447 		freemsg(mp);
13448 		return (NULL);
13449 	}
13450 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13451 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13452 		freemsg(mp);
13453 		return (NULL);
13454 	}
13455 
13456 	/*
13457 	 * Mark this packet as having originated externally.
13458 	 *
13459 	 * For non-forwarding code path, ire_send later double
13460 	 * checks this interface to see if it is still exists
13461 	 * post-ARP resolution.
13462 	 *
13463 	 * Also, IPQOS uses this to differentiate between
13464 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13465 	 * QOS packet processing in ip_wput_attach_llhdr().
13466 	 * The QoS module can mark the b_band for a fastpath message
13467 	 * or the dl_priority field in a unitdata_req header for
13468 	 * CoS marking. This info can only be found in
13469 	 * ip_wput_attach_llhdr().
13470 	 */
13471 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13472 	/*
13473 	 * Clear the indication that this may have a hardware checksum
13474 	 * as we are not using it
13475 	 */
13476 	DB_CKSUMFLAGS(mp) = 0;
13477 
13478 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13479 	    MBLK_GETLABEL(mp), ipst);
13480 
13481 	if (ire == NULL && ret_action == Forward_check_multirt) {
13482 		/* Let ip_newroute handle CGTP  */
13483 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13484 		return (NULL);
13485 	}
13486 
13487 	if (ire != NULL)
13488 		return (ire);
13489 
13490 	mp->b_prev = mp->b_next = 0;
13491 
13492 	if (ret_action == Forward_blackhole) {
13493 		freemsg(mp);
13494 		return (NULL);
13495 	}
13496 	/* send icmp unreachable */
13497 	q = WR(q);
13498 	/* Sent by forwarding path, and router is global zone */
13499 	if (ip_source_routed(ipha, ipst)) {
13500 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13501 		    GLOBAL_ZONEID, ipst);
13502 	} else {
13503 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13504 		    ipst);
13505 	}
13506 
13507 	return (NULL);
13508 
13509 }
13510 
13511 /*
13512  * check ip header length and align it.
13513  */
13514 static boolean_t
13515 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13516 {
13517 	ssize_t len;
13518 	ill_t *ill;
13519 	ipha_t	*ipha;
13520 
13521 	len = MBLKL(mp);
13522 
13523 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13524 		ill = (ill_t *)q->q_ptr;
13525 
13526 		if (!OK_32PTR(mp->b_rptr))
13527 			IP_STAT(ipst, ip_notaligned1);
13528 		else
13529 			IP_STAT(ipst, ip_notaligned2);
13530 		/* Guard against bogus device drivers */
13531 		if (len < 0) {
13532 			/* clear b_prev - used by ip_mroute_decap */
13533 			mp->b_prev = NULL;
13534 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13535 			freemsg(mp);
13536 			return (B_FALSE);
13537 		}
13538 
13539 		if (ip_rput_pullups++ == 0) {
13540 			ipha = (ipha_t *)mp->b_rptr;
13541 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13542 			    "ip_check_and_align_header: %s forced us to "
13543 			    " pullup pkt, hdr len %ld, hdr addr %p",
13544 			    ill->ill_name, len, (void *)ipha);
13545 		}
13546 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13547 			/* clear b_prev - used by ip_mroute_decap */
13548 			mp->b_prev = NULL;
13549 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13550 			freemsg(mp);
13551 			return (B_FALSE);
13552 		}
13553 	}
13554 	return (B_TRUE);
13555 }
13556 
13557 /*
13558  * Handle the situation where a packet came in on `ill' but matched an IRE
13559  * whose ire_rfq doesn't match `ill'.  We return the IRE that should be used
13560  * for interface statistics.
13561  */
13562 ire_t *
13563 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13564 {
13565 	ire_t		*new_ire;
13566 	ill_t		*ire_ill;
13567 	uint_t		ifindex;
13568 	ip_stack_t	*ipst = ill->ill_ipst;
13569 	boolean_t	strict_check = B_FALSE;
13570 
13571 	/*
13572 	 * IPMP common case: if IRE and ILL are in the same group, there's no
13573 	 * issue (e.g. packet received on an underlying interface matched an
13574 	 * IRE_LOCAL on its associated group interface).
13575 	 */
13576 	if (ire->ire_rfq != NULL &&
13577 	    IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr)) {
13578 		return (ire);
13579 	}
13580 
13581 	/*
13582 	 * Do another ire lookup here, using the ingress ill, to see if the
13583 	 * interface is in a usesrc group.
13584 	 * As long as the ills belong to the same group, we don't consider
13585 	 * them to be arriving on the wrong interface. Thus, if the switch
13586 	 * is doing inbound load spreading, we won't drop packets when the
13587 	 * ip*_strict_dst_multihoming switch is on.
13588 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13589 	 * where the local address may not be unique. In this case we were
13590 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13591 	 * actually returned. The new lookup, which is more specific, should
13592 	 * only find the IRE_LOCAL associated with the ingress ill if one
13593 	 * exists.
13594 	 */
13595 
13596 	if (ire->ire_ipversion == IPV4_VERSION) {
13597 		if (ipst->ips_ip_strict_dst_multihoming)
13598 			strict_check = B_TRUE;
13599 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13600 		    ill->ill_ipif, ALL_ZONES, NULL,
13601 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13602 	} else {
13603 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13604 		if (ipst->ips_ipv6_strict_dst_multihoming)
13605 			strict_check = B_TRUE;
13606 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13607 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13608 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13609 	}
13610 	/*
13611 	 * If the same ire that was returned in ip_input() is found then this
13612 	 * is an indication that usesrc groups are in use. The packet
13613 	 * arrived on a different ill in the group than the one associated with
13614 	 * the destination address.  If a different ire was found then the same
13615 	 * IP address must be hosted on multiple ills. This is possible with
13616 	 * unnumbered point2point interfaces. We switch to use this new ire in
13617 	 * order to have accurate interface statistics.
13618 	 */
13619 	if (new_ire != NULL) {
13620 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13621 			ire_refrele(ire);
13622 			ire = new_ire;
13623 		} else {
13624 			ire_refrele(new_ire);
13625 		}
13626 		return (ire);
13627 	} else if ((ire->ire_rfq == NULL) &&
13628 	    (ire->ire_ipversion == IPV4_VERSION)) {
13629 		/*
13630 		 * The best match could have been the original ire which
13631 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13632 		 * the strict multihoming checks are irrelevant as we consider
13633 		 * local addresses hosted on lo0 to be interface agnostic. We
13634 		 * only expect a null ire_rfq on IREs which are associated with
13635 		 * lo0 hence we can return now.
13636 		 */
13637 		return (ire);
13638 	}
13639 
13640 	/*
13641 	 * Chase pointers once and store locally.
13642 	 */
13643 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13644 	    (ill_t *)(ire->ire_rfq->q_ptr);
13645 	ifindex = ill->ill_usesrc_ifindex;
13646 
13647 	/*
13648 	 * Check if it's a legal address on the 'usesrc' interface.
13649 	 */
13650 	if ((ifindex != 0) && (ire_ill != NULL) &&
13651 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13652 		return (ire);
13653 	}
13654 
13655 	/*
13656 	 * If the ip*_strict_dst_multihoming switch is on then we can
13657 	 * only accept this packet if the interface is marked as routing.
13658 	 */
13659 	if (!(strict_check))
13660 		return (ire);
13661 
13662 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13663 	    ILLF_ROUTER) != 0) {
13664 		return (ire);
13665 	}
13666 
13667 	ire_refrele(ire);
13668 	return (NULL);
13669 }
13670 
13671 /*
13672  *
13673  * This is the fast forward path. If we are here, we dont need to
13674  * worry about RSVP, CGTP, or TSol. Furthermore the ftable lookup
13675  * needed to find the nexthop in this case is much simpler
13676  */
13677 ire_t *
13678 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13679 {
13680 	ipha_t	*ipha;
13681 	ire_t	*src_ire;
13682 	ill_t	*stq_ill;
13683 	uint_t	hlen;
13684 	uint_t	pkt_len;
13685 	uint32_t sum;
13686 	queue_t	*dev_q;
13687 	ip_stack_t *ipst = ill->ill_ipst;
13688 	mblk_t *fpmp;
13689 	enum	ire_forward_action ret_action;
13690 
13691 	ipha = (ipha_t *)mp->b_rptr;
13692 
13693 	if (ire != NULL &&
13694 	    ire->ire_zoneid != GLOBAL_ZONEID &&
13695 	    ire->ire_zoneid != ALL_ZONES) {
13696 		/*
13697 		 * Should only use IREs that are visible to the global
13698 		 * zone for forwarding.
13699 		 */
13700 		ire_refrele(ire);
13701 		ire = ire_cache_lookup(dst, GLOBAL_ZONEID, NULL, ipst);
13702 		/*
13703 		 * ire_cache_lookup() can return ire of IRE_LOCAL in
13704 		 * transient cases. In such case, just drop the packet
13705 		 */
13706 		if (ire->ire_type != IRE_CACHE)
13707 			goto drop;
13708 	}
13709 
13710 	/*
13711 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13712 	 * The loopback address check for both src and dst has already
13713 	 * been checked in ip_input
13714 	 */
13715 
13716 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13717 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13718 		goto drop;
13719 	}
13720 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13721 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13722 
13723 	if (src_ire != NULL) {
13724 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13725 		ire_refrele(src_ire);
13726 		goto drop;
13727 	}
13728 
13729 	/* No ire cache of nexthop. So first create one  */
13730 	if (ire == NULL) {
13731 
13732 		ire = ire_forward_simple(dst, &ret_action, ipst);
13733 
13734 		/*
13735 		 * We only come to ip_fast_forward if ip_cgtp_filter
13736 		 * is not set. So ire_forward() should not return with
13737 		 * Forward_check_multirt as the next action.
13738 		 */
13739 		ASSERT(ret_action != Forward_check_multirt);
13740 		if (ire == NULL) {
13741 			/* An attempt was made to forward the packet */
13742 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13743 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13744 			mp->b_prev = mp->b_next = 0;
13745 			/* send icmp unreachable */
13746 			/* Sent by forwarding path, and router is global zone */
13747 			if (ret_action == Forward_ret_icmp_err) {
13748 				if (ip_source_routed(ipha, ipst)) {
13749 					icmp_unreachable(ill->ill_wq, mp,
13750 					    ICMP_SOURCE_ROUTE_FAILED,
13751 					    GLOBAL_ZONEID, ipst);
13752 				} else {
13753 					icmp_unreachable(ill->ill_wq, mp,
13754 					    ICMP_HOST_UNREACHABLE,
13755 					    GLOBAL_ZONEID, ipst);
13756 				}
13757 			} else {
13758 				freemsg(mp);
13759 			}
13760 			return (NULL);
13761 		}
13762 	}
13763 
13764 	/*
13765 	 * Forwarding fastpath exception case:
13766 	 * If any of the following are true, we take the slowpath:
13767 	 *	o forwarding is not enabled
13768 	 *	o incoming and outgoing interface are the same, or in the same
13769 	 *	  IPMP group.
13770 	 *	o corresponding ire is in incomplete state
13771 	 *	o packet needs fragmentation
13772 	 *	o ARP cache is not resolved
13773 	 *
13774 	 * The codeflow from here on is thus:
13775 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13776 	 */
13777 	pkt_len = ntohs(ipha->ipha_length);
13778 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13779 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13780 	    (ill == stq_ill) || IS_IN_SAME_ILLGRP(ill, stq_ill) ||
13781 	    (ire->ire_nce == NULL) ||
13782 	    (pkt_len > ire->ire_max_frag) ||
13783 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
13784 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
13785 	    ipha->ipha_ttl <= 1) {
13786 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13787 		    ipha, ill, B_FALSE, B_TRUE);
13788 		return (ire);
13789 	}
13790 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13791 
13792 	DTRACE_PROBE4(ip4__forwarding__start,
13793 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13794 
13795 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13796 	    ipst->ips_ipv4firewall_forwarding,
13797 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
13798 
13799 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13800 
13801 	if (mp == NULL)
13802 		goto drop;
13803 
13804 	mp->b_datap->db_struioun.cksum.flags = 0;
13805 	/* Adjust the checksum to reflect the ttl decrement. */
13806 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13807 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13808 	ipha->ipha_ttl--;
13809 
13810 	/*
13811 	 * Write the link layer header.  We can do this safely here,
13812 	 * because we have already tested to make sure that the IP
13813 	 * policy is not set, and that we have a fast path destination
13814 	 * header.
13815 	 */
13816 	mp->b_rptr -= hlen;
13817 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
13818 
13819 	UPDATE_IB_PKT_COUNT(ire);
13820 	ire->ire_last_used_time = lbolt;
13821 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
13822 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
13823 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
13824 
13825 	if (!ILL_DIRECT_CAPABLE(stq_ill) || DB_TYPE(mp) != M_DATA) {
13826 		dev_q = ire->ire_stq->q_next;
13827 		if (DEV_Q_FLOW_BLOCKED(dev_q))
13828 			goto indiscard;
13829 	}
13830 
13831 	DTRACE_PROBE4(ip4__physical__out__start,
13832 	    ill_t *, NULL, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13833 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
13834 	    ipst->ips_ipv4firewall_physical_out,
13835 	    NULL, stq_ill, ipha, mp, mp, 0, ipst);
13836 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
13837 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,
13838 	    ipha, __dtrace_ipsr_ill_t *, stq_ill, ipha_t *, ipha,
13839 	    ip6_t *, NULL, int, 0);
13840 
13841 	if (mp != NULL) {
13842 		if (ipst->ips_ipobs_enabled) {
13843 			zoneid_t szone;
13844 
13845 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
13846 			    ipst, ALL_ZONES);
13847 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
13848 			    ALL_ZONES, ill, IPV4_VERSION, hlen, ipst);
13849 		}
13850 
13851 		ILL_SEND_TX(stq_ill, ire, dst, mp, IP_DROP_ON_NO_DESC);
13852 	}
13853 	return (ire);
13854 
13855 indiscard:
13856 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13857 drop:
13858 	if (mp != NULL)
13859 		freemsg(mp);
13860 	return (ire);
13861 
13862 }
13863 
13864 /*
13865  * This function is called in the forwarding slowpath, when
13866  * either the ire lacks the link-layer address, or the packet needs
13867  * further processing(eg. fragmentation), before transmission.
13868  */
13869 
13870 static void
13871 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13872     ill_t *ill, boolean_t ll_multicast, boolean_t from_ip_fast_forward)
13873 {
13874 	queue_t		*dev_q;
13875 	ire_t		*src_ire;
13876 	ip_stack_t	*ipst = ill->ill_ipst;
13877 	boolean_t	same_illgrp = B_FALSE;
13878 
13879 	ASSERT(ire->ire_stq != NULL);
13880 
13881 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
13882 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
13883 
13884 	/*
13885 	 * If the caller of this function is ip_fast_forward() skip the
13886 	 * next three checks as it does not apply.
13887 	 */
13888 	if (from_ip_fast_forward)
13889 		goto skip;
13890 
13891 	if (ll_multicast != 0) {
13892 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13893 		goto drop_pkt;
13894 	}
13895 
13896 	/*
13897 	 * check if ipha_src is a broadcast address. Note that this
13898 	 * check is redundant when we get here from ip_fast_forward()
13899 	 * which has already done this check. However, since we can
13900 	 * also get here from ip_rput_process_broadcast() or, for
13901 	 * for the slow path through ip_fast_forward(), we perform
13902 	 * the check again for code-reusability
13903 	 */
13904 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13905 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13906 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
13907 		if (src_ire != NULL)
13908 			ire_refrele(src_ire);
13909 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13910 		ip2dbg(("ip_rput_process_forward: Received packet with"
13911 		    " bad src/dst address on %s\n", ill->ill_name));
13912 		goto drop_pkt;
13913 	}
13914 
13915 	/*
13916 	 * Check if we want to forward this one at this time.
13917 	 * We allow source routed packets on a host provided that
13918 	 * they go out the same ill or illgrp as they came in on.
13919 	 *
13920 	 * XXX To be quicker, we may wish to not chase pointers to
13921 	 * get the ILLF_ROUTER flag and instead store the
13922 	 * forwarding policy in the ire.  An unfortunate
13923 	 * side-effect of that would be requiring an ire flush
13924 	 * whenever the ILLF_ROUTER flag changes.
13925 	 */
13926 skip:
13927 	same_illgrp = IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr);
13928 
13929 	if (((ill->ill_flags &
13930 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags & ILLF_ROUTER) == 0) &&
13931 	    !(ip_source_routed(ipha, ipst) &&
13932 	    (ire->ire_rfq == q || same_illgrp))) {
13933 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13934 		if (ip_source_routed(ipha, ipst)) {
13935 			q = WR(q);
13936 			/*
13937 			 * Clear the indication that this may have
13938 			 * hardware checksum as we are not using it.
13939 			 */
13940 			DB_CKSUMFLAGS(mp) = 0;
13941 			/* Sent by forwarding path, and router is global zone */
13942 			icmp_unreachable(q, mp,
13943 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
13944 			return;
13945 		}
13946 		goto drop_pkt;
13947 	}
13948 
13949 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13950 
13951 	/* Packet is being forwarded. Turning off hwcksum flag. */
13952 	DB_CKSUMFLAGS(mp) = 0;
13953 	if (ipst->ips_ip_g_send_redirects) {
13954 		/*
13955 		 * Check whether the incoming interface and outgoing
13956 		 * interface is part of the same group. If so,
13957 		 * send redirects.
13958 		 *
13959 		 * Check the source address to see if it originated
13960 		 * on the same logical subnet it is going back out on.
13961 		 * If so, we should be able to send it a redirect.
13962 		 * Avoid sending a redirect if the destination
13963 		 * is directly connected (i.e., ipha_dst is the same
13964 		 * as ire_gateway_addr or the ire_addr of the
13965 		 * nexthop IRE_CACHE ), or if the packet was source
13966 		 * routed out this interface.
13967 		 */
13968 		ipaddr_t src, nhop;
13969 		mblk_t	*mp1;
13970 		ire_t	*nhop_ire = NULL;
13971 
13972 		/*
13973 		 * Check whether ire_rfq and q are from the same ill or illgrp.
13974 		 * If so, send redirects.
13975 		 */
13976 		if ((ire->ire_rfq == q || same_illgrp) &&
13977 		    !ip_source_routed(ipha, ipst)) {
13978 
13979 			nhop = (ire->ire_gateway_addr != 0 ?
13980 			    ire->ire_gateway_addr : ire->ire_addr);
13981 
13982 			if (ipha->ipha_dst == nhop) {
13983 				/*
13984 				 * We avoid sending a redirect if the
13985 				 * destination is directly connected
13986 				 * because it is possible that multiple
13987 				 * IP subnets may have been configured on
13988 				 * the link, and the source may not
13989 				 * be on the same subnet as ip destination,
13990 				 * even though they are on the same
13991 				 * physical link.
13992 				 */
13993 				goto sendit;
13994 			}
13995 
13996 			src = ipha->ipha_src;
13997 
13998 			/*
13999 			 * We look up the interface ire for the nexthop,
14000 			 * to see if ipha_src is in the same subnet
14001 			 * as the nexthop.
14002 			 *
14003 			 * Note that, if, in the future, IRE_CACHE entries
14004 			 * are obsoleted,  this lookup will not be needed,
14005 			 * as the ire passed to this function will be the
14006 			 * same as the nhop_ire computed below.
14007 			 */
14008 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14009 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14010 			    0, NULL, MATCH_IRE_TYPE, ipst);
14011 
14012 			if (nhop_ire != NULL) {
14013 				if ((src & nhop_ire->ire_mask) ==
14014 				    (nhop & nhop_ire->ire_mask)) {
14015 					/*
14016 					 * The source is directly connected.
14017 					 * Just copy the ip header (which is
14018 					 * in the first mblk)
14019 					 */
14020 					mp1 = copyb(mp);
14021 					if (mp1 != NULL) {
14022 						icmp_send_redirect(WR(q), mp1,
14023 						    nhop, ipst);
14024 					}
14025 				}
14026 				ire_refrele(nhop_ire);
14027 			}
14028 		}
14029 	}
14030 sendit:
14031 	dev_q = ire->ire_stq->q_next;
14032 	if (DEV_Q_FLOW_BLOCKED(dev_q)) {
14033 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14034 		freemsg(mp);
14035 		return;
14036 	}
14037 
14038 	ip_rput_forward(ire, ipha, mp, ill);
14039 	return;
14040 
14041 drop_pkt:
14042 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14043 	freemsg(mp);
14044 }
14045 
14046 ire_t *
14047 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14048     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14049 {
14050 	queue_t		*q;
14051 	uint16_t	hcksumflags;
14052 	ip_stack_t	*ipst = ill->ill_ipst;
14053 
14054 	q = *qp;
14055 
14056 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14057 
14058 	/*
14059 	 * Clear the indication that this may have hardware
14060 	 * checksum as we are not using it for forwarding.
14061 	 */
14062 	hcksumflags = DB_CKSUMFLAGS(mp);
14063 	DB_CKSUMFLAGS(mp) = 0;
14064 
14065 	/*
14066 	 * Directed broadcast forwarding: if the packet came in over a
14067 	 * different interface then it is routed out over we can forward it.
14068 	 */
14069 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14070 		ire_refrele(ire);
14071 		freemsg(mp);
14072 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14073 		return (NULL);
14074 	}
14075 	/*
14076 	 * For multicast we have set dst to be INADDR_BROADCAST
14077 	 * for delivering to all STREAMS.
14078 	 */
14079 	if (!CLASSD(ipha->ipha_dst)) {
14080 		ire_t *new_ire;
14081 		ipif_t *ipif;
14082 
14083 		ipif = ipif_get_next_ipif(NULL, ill);
14084 		if (ipif == NULL) {
14085 discard:		ire_refrele(ire);
14086 			freemsg(mp);
14087 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14088 			return (NULL);
14089 		}
14090 		new_ire = ire_ctable_lookup(dst, 0, 0,
14091 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14092 		ipif_refrele(ipif);
14093 
14094 		if (new_ire != NULL) {
14095 			/*
14096 			 * If the matching IRE_BROADCAST is part of an IPMP
14097 			 * group, then drop the packet unless our ill has been
14098 			 * nominated to receive for the group.
14099 			 */
14100 			if (IS_IPMP(new_ire->ire_ipif->ipif_ill) &&
14101 			    new_ire->ire_rfq != q) {
14102 				ire_refrele(new_ire);
14103 				goto discard;
14104 			}
14105 
14106 			/*
14107 			 * In the special case of multirouted broadcast
14108 			 * packets, we unconditionally need to "gateway"
14109 			 * them to the appropriate interface here.
14110 			 * In the normal case, this cannot happen, because
14111 			 * there is no broadcast IRE tagged with the
14112 			 * RTF_MULTIRT flag.
14113 			 */
14114 			if (new_ire->ire_flags & RTF_MULTIRT) {
14115 				ire_refrele(new_ire);
14116 				if (ire->ire_rfq != NULL) {
14117 					q = ire->ire_rfq;
14118 					*qp = q;
14119 				}
14120 			} else {
14121 				ire_refrele(ire);
14122 				ire = new_ire;
14123 			}
14124 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14125 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14126 				/*
14127 				 * Free the message if
14128 				 * ip_g_forward_directed_bcast is turned
14129 				 * off for non-local broadcast.
14130 				 */
14131 				ire_refrele(ire);
14132 				freemsg(mp);
14133 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14134 				return (NULL);
14135 			}
14136 		} else {
14137 			/*
14138 			 * This CGTP packet successfully passed the
14139 			 * CGTP filter, but the related CGTP
14140 			 * broadcast IRE has not been found,
14141 			 * meaning that the redundant ipif is
14142 			 * probably down. However, if we discarded
14143 			 * this packet, its duplicate would be
14144 			 * filtered out by the CGTP filter so none
14145 			 * of them would get through. So we keep
14146 			 * going with this one.
14147 			 */
14148 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14149 			if (ire->ire_rfq != NULL) {
14150 				q = ire->ire_rfq;
14151 				*qp = q;
14152 			}
14153 		}
14154 	}
14155 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14156 		/*
14157 		 * Verify that there are not more then one
14158 		 * IRE_BROADCAST with this broadcast address which
14159 		 * has ire_stq set.
14160 		 * TODO: simplify, loop over all IRE's
14161 		 */
14162 		ire_t	*ire1;
14163 		int	num_stq = 0;
14164 		mblk_t	*mp1;
14165 
14166 		/* Find the first one with ire_stq set */
14167 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14168 		for (ire1 = ire; ire1 &&
14169 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14170 		    ire1 = ire1->ire_next)
14171 			;
14172 		if (ire1) {
14173 			ire_refrele(ire);
14174 			ire = ire1;
14175 			IRE_REFHOLD(ire);
14176 		}
14177 
14178 		/* Check if there are additional ones with stq set */
14179 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14180 			if (ire->ire_addr != ire1->ire_addr)
14181 				break;
14182 			if (ire1->ire_stq) {
14183 				num_stq++;
14184 				break;
14185 			}
14186 		}
14187 		rw_exit(&ire->ire_bucket->irb_lock);
14188 		if (num_stq == 1 && ire->ire_stq != NULL) {
14189 			ip1dbg(("ip_rput_process_broadcast: directed "
14190 			    "broadcast to 0x%x\n",
14191 			    ntohl(ire->ire_addr)));
14192 			mp1 = copymsg(mp);
14193 			if (mp1) {
14194 				switch (ipha->ipha_protocol) {
14195 				case IPPROTO_UDP:
14196 					ip_udp_input(q, mp1, ipha, ire, ill);
14197 					break;
14198 				default:
14199 					ip_proto_input(q, mp1, ipha, ire, ill,
14200 					    0);
14201 					break;
14202 				}
14203 			}
14204 			/*
14205 			 * Adjust ttl to 2 (1+1 - the forward engine
14206 			 * will decrement it by one.
14207 			 */
14208 			if (ip_csum_hdr(ipha)) {
14209 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14210 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14211 				freemsg(mp);
14212 				ire_refrele(ire);
14213 				return (NULL);
14214 			}
14215 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14216 			ipha->ipha_hdr_checksum = 0;
14217 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14218 			ip_rput_process_forward(q, mp, ire, ipha,
14219 			    ill, ll_multicast, B_FALSE);
14220 			ire_refrele(ire);
14221 			return (NULL);
14222 		}
14223 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14224 		    ntohl(ire->ire_addr)));
14225 	}
14226 
14227 	/* Restore any hardware checksum flags */
14228 	DB_CKSUMFLAGS(mp) = hcksumflags;
14229 	return (ire);
14230 }
14231 
14232 /* ARGSUSED */
14233 static boolean_t
14234 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14235     int *ll_multicast, ipaddr_t *dstp)
14236 {
14237 	ip_stack_t	*ipst = ill->ill_ipst;
14238 
14239 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14240 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14241 	    ntohs(ipha->ipha_length));
14242 
14243 	/*
14244 	 * So that we don't end up with dups, only one ill in an IPMP group is
14245 	 * nominated to receive multicast traffic.
14246 	 */
14247 	if (IS_UNDER_IPMP(ill) && !ill->ill_nom_cast)
14248 		goto drop_pkt;
14249 
14250 	/*
14251 	 * Forward packets only if we have joined the allmulti
14252 	 * group on this interface.
14253 	 */
14254 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14255 		int retval;
14256 
14257 		/*
14258 		 * Clear the indication that this may have hardware
14259 		 * checksum as we are not using it.
14260 		 */
14261 		DB_CKSUMFLAGS(mp) = 0;
14262 		retval = ip_mforward(ill, ipha, mp);
14263 		/* ip_mforward updates mib variables if needed */
14264 		/* clear b_prev - used by ip_mroute_decap */
14265 		mp->b_prev = NULL;
14266 
14267 		switch (retval) {
14268 		case 0:
14269 			/*
14270 			 * pkt is okay and arrived on phyint.
14271 			 *
14272 			 * If we are running as a multicast router
14273 			 * we need to see all IGMP and/or PIM packets.
14274 			 */
14275 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14276 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14277 				goto done;
14278 			}
14279 			break;
14280 		case -1:
14281 			/* pkt is mal-formed, toss it */
14282 			goto drop_pkt;
14283 		case 1:
14284 			/* pkt is okay and arrived on a tunnel */
14285 			/*
14286 			 * If we are running a multicast router
14287 			 *  we need to see all igmp packets.
14288 			 */
14289 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14290 				*dstp = INADDR_BROADCAST;
14291 				*ll_multicast = 1;
14292 				return (B_FALSE);
14293 			}
14294 
14295 			goto drop_pkt;
14296 		}
14297 	}
14298 
14299 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14300 		/*
14301 		 * This might just be caused by the fact that
14302 		 * multiple IP Multicast addresses map to the same
14303 		 * link layer multicast - no need to increment counter!
14304 		 */
14305 		freemsg(mp);
14306 		return (B_TRUE);
14307 	}
14308 done:
14309 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14310 	/*
14311 	 * This assumes the we deliver to all streams for multicast
14312 	 * and broadcast packets.
14313 	 */
14314 	*dstp = INADDR_BROADCAST;
14315 	*ll_multicast = 1;
14316 	return (B_FALSE);
14317 drop_pkt:
14318 	ip2dbg(("ip_rput: drop pkt\n"));
14319 	freemsg(mp);
14320 	return (B_TRUE);
14321 }
14322 
14323 /*
14324  * This function is used to both return an indication of whether or not
14325  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14326  * and in doing so, determine whether or not it is broadcast vs multicast.
14327  * For it to be a broadcast packet, we must have the appropriate mblk_t
14328  * hanging off the ill_t.  If this is either not present or doesn't match
14329  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14330  * to be multicast.  Thus NICs that have no broadcast address (or no
14331  * capability for one, such as point to point links) cannot return as
14332  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14333  * the return values simplifies the current use of the return value of this
14334  * function, which is to pass through the multicast/broadcast characteristic
14335  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14336  * changing the return value to some other symbol demands the appropriate
14337  * "translation" when hpe_flags is set prior to calling hook_run() for
14338  * packet events.
14339  */
14340 int
14341 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14342 {
14343 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14344 	mblk_t *bmp;
14345 
14346 	if (ind->dl_group_address) {
14347 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14348 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14349 		    MBLKL(mb) &&
14350 		    (bmp = ill->ill_bcast_mp) != NULL) {
14351 			dl_unitdata_req_t *dlur;
14352 			uint8_t *bphys_addr;
14353 
14354 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14355 			if (ill->ill_sap_length < 0)
14356 				bphys_addr = (uchar_t *)dlur +
14357 				    dlur->dl_dest_addr_offset;
14358 			else
14359 				bphys_addr = (uchar_t *)dlur +
14360 				    dlur->dl_dest_addr_offset +
14361 				    ill->ill_sap_length;
14362 
14363 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14364 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14365 				return (HPE_BROADCAST);
14366 			}
14367 			return (HPE_MULTICAST);
14368 		}
14369 		return (HPE_MULTICAST);
14370 	}
14371 	return (0);
14372 }
14373 
14374 static boolean_t
14375 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14376     int *ll_multicast, mblk_t **mpp)
14377 {
14378 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14379 	boolean_t must_copy = B_FALSE;
14380 	struct iocblk   *iocp;
14381 	ipha_t		*ipha;
14382 	ip_stack_t	*ipst = ill->ill_ipst;
14383 
14384 #define	rptr    ((uchar_t *)ipha)
14385 
14386 	first_mp = *first_mpp;
14387 	mp = *mpp;
14388 
14389 	ASSERT(first_mp == mp);
14390 
14391 	/*
14392 	 * if db_ref > 1 then copymsg and free original. Packet may be
14393 	 * changed and do not want other entity who has a reference to this
14394 	 * message to trip over the changes. This is a blind change because
14395 	 * trying to catch all places that might change packet is too
14396 	 * difficult (since it may be a module above this one)
14397 	 *
14398 	 * This corresponds to the non-fast path case. We walk down the full
14399 	 * chain in this case, and check the db_ref count of all the dblks,
14400 	 * and do a copymsg if required. It is possible that the db_ref counts
14401 	 * of the data blocks in the mblk chain can be different.
14402 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14403 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14404 	 * 'snoop' is running.
14405 	 */
14406 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14407 		if (mp1->b_datap->db_ref > 1) {
14408 			must_copy = B_TRUE;
14409 			break;
14410 		}
14411 	}
14412 
14413 	if (must_copy) {
14414 		mp1 = copymsg(mp);
14415 		if (mp1 == NULL) {
14416 			for (mp1 = mp; mp1 != NULL;
14417 			    mp1 = mp1->b_cont) {
14418 				mp1->b_next = NULL;
14419 				mp1->b_prev = NULL;
14420 			}
14421 			freemsg(mp);
14422 			if (ill != NULL) {
14423 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14424 			} else {
14425 				BUMP_MIB(&ipst->ips_ip_mib,
14426 				    ipIfStatsInDiscards);
14427 			}
14428 			return (B_TRUE);
14429 		}
14430 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14431 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14432 			/* Copy b_prev - used by ip_mroute_decap */
14433 			to_mp->b_prev = from_mp->b_prev;
14434 			from_mp->b_prev = NULL;
14435 		}
14436 		*first_mpp = first_mp = mp1;
14437 		freemsg(mp);
14438 		mp = mp1;
14439 		*mpp = mp1;
14440 	}
14441 
14442 	ipha = (ipha_t *)mp->b_rptr;
14443 
14444 	/*
14445 	 * previous code has a case for M_DATA.
14446 	 * We want to check how that happens.
14447 	 */
14448 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14449 	switch (first_mp->b_datap->db_type) {
14450 	case M_PROTO:
14451 	case M_PCPROTO:
14452 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14453 		    DL_UNITDATA_IND) {
14454 			/* Go handle anything other than data elsewhere. */
14455 			ip_rput_dlpi(q, mp);
14456 			return (B_TRUE);
14457 		}
14458 
14459 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14460 		/* Ditch the DLPI header. */
14461 		mp1 = mp->b_cont;
14462 		ASSERT(first_mp == mp);
14463 		*first_mpp = mp1;
14464 		freeb(mp);
14465 		*mpp = mp1;
14466 		return (B_FALSE);
14467 	case M_IOCACK:
14468 		ip1dbg(("got iocack "));
14469 		iocp = (struct iocblk *)mp->b_rptr;
14470 		switch (iocp->ioc_cmd) {
14471 		case DL_IOC_HDR_INFO:
14472 			ill = (ill_t *)q->q_ptr;
14473 			ill_fastpath_ack(ill, mp);
14474 			return (B_TRUE);
14475 		case SIOCSTUNPARAM:
14476 		case OSIOCSTUNPARAM:
14477 			/* Go through qwriter_ip */
14478 			break;
14479 		case SIOCGTUNPARAM:
14480 		case OSIOCGTUNPARAM:
14481 			ip_rput_other(NULL, q, mp, NULL);
14482 			return (B_TRUE);
14483 		default:
14484 			putnext(q, mp);
14485 			return (B_TRUE);
14486 		}
14487 		/* FALLTHRU */
14488 	case M_ERROR:
14489 	case M_HANGUP:
14490 		/*
14491 		 * Since this is on the ill stream we unconditionally
14492 		 * bump up the refcount
14493 		 */
14494 		ill_refhold(ill);
14495 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14496 		return (B_TRUE);
14497 	case M_CTL:
14498 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14499 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14500 		    IPHADA_M_CTL)) {
14501 			/*
14502 			 * It's an IPsec accelerated packet.
14503 			 * Make sure that the ill from which we received the
14504 			 * packet has enabled IPsec hardware acceleration.
14505 			 */
14506 			if (!(ill->ill_capabilities &
14507 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14508 				/* IPsec kstats: bean counter */
14509 				freemsg(mp);
14510 				return (B_TRUE);
14511 			}
14512 
14513 			/*
14514 			 * Make mp point to the mblk following the M_CTL,
14515 			 * then process according to type of mp.
14516 			 * After this processing, first_mp will point to
14517 			 * the data-attributes and mp to the pkt following
14518 			 * the M_CTL.
14519 			 */
14520 			mp = first_mp->b_cont;
14521 			if (mp == NULL) {
14522 				freemsg(first_mp);
14523 				return (B_TRUE);
14524 			}
14525 			/*
14526 			 * A Hardware Accelerated packet can only be M_DATA
14527 			 * ESP or AH packet.
14528 			 */
14529 			if (mp->b_datap->db_type != M_DATA) {
14530 				/* non-M_DATA IPsec accelerated packet */
14531 				IPSECHW_DEBUG(IPSECHW_PKT,
14532 				    ("non-M_DATA IPsec accelerated pkt\n"));
14533 				freemsg(first_mp);
14534 				return (B_TRUE);
14535 			}
14536 			ipha = (ipha_t *)mp->b_rptr;
14537 			if (ipha->ipha_protocol != IPPROTO_AH &&
14538 			    ipha->ipha_protocol != IPPROTO_ESP) {
14539 				IPSECHW_DEBUG(IPSECHW_PKT,
14540 				    ("non-M_DATA IPsec accelerated pkt\n"));
14541 				freemsg(first_mp);
14542 				return (B_TRUE);
14543 			}
14544 			*mpp = mp;
14545 			return (B_FALSE);
14546 		}
14547 		putnext(q, mp);
14548 		return (B_TRUE);
14549 	case M_IOCNAK:
14550 		ip1dbg(("got iocnak "));
14551 		iocp = (struct iocblk *)mp->b_rptr;
14552 		switch (iocp->ioc_cmd) {
14553 		case SIOCSTUNPARAM:
14554 		case OSIOCSTUNPARAM:
14555 			/*
14556 			 * Since this is on the ill stream we unconditionally
14557 			 * bump up the refcount
14558 			 */
14559 			ill_refhold(ill);
14560 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14561 			return (B_TRUE);
14562 		case DL_IOC_HDR_INFO:
14563 		case SIOCGTUNPARAM:
14564 		case OSIOCGTUNPARAM:
14565 			ip_rput_other(NULL, q, mp, NULL);
14566 			return (B_TRUE);
14567 		default:
14568 			break;
14569 		}
14570 		/* FALLTHRU */
14571 	default:
14572 		putnext(q, mp);
14573 		return (B_TRUE);
14574 	}
14575 }
14576 
14577 /* Read side put procedure.  Packets coming from the wire arrive here. */
14578 void
14579 ip_rput(queue_t *q, mblk_t *mp)
14580 {
14581 	ill_t	*ill;
14582 	union DL_primitives *dl;
14583 
14584 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14585 
14586 	ill = (ill_t *)q->q_ptr;
14587 
14588 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14589 		/*
14590 		 * If things are opening or closing, only accept high-priority
14591 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14592 		 * created; on close, things hanging off the ill may have been
14593 		 * freed already.)
14594 		 */
14595 		dl = (union DL_primitives *)mp->b_rptr;
14596 		if (DB_TYPE(mp) != M_PCPROTO ||
14597 		    dl->dl_primitive == DL_UNITDATA_IND) {
14598 			/*
14599 			 * SIOC[GS]TUNPARAM ioctls can come here.
14600 			 */
14601 			inet_freemsg(mp);
14602 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14603 			    "ip_rput_end: q %p (%S)", q, "uninit");
14604 			return;
14605 		}
14606 	}
14607 
14608 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14609 	    "ip_rput_end: q %p (%S)", q, "end");
14610 
14611 	ip_input(ill, NULL, mp, NULL);
14612 }
14613 
14614 static mblk_t *
14615 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14616 {
14617 	mblk_t *mp1;
14618 	boolean_t adjusted = B_FALSE;
14619 	ip_stack_t *ipst = ill->ill_ipst;
14620 
14621 	IP_STAT(ipst, ip_db_ref);
14622 	/*
14623 	 * The IP_RECVSLLA option depends on having the
14624 	 * link layer header. First check that:
14625 	 * a> the underlying device is of type ether,
14626 	 * since this option is currently supported only
14627 	 * over ethernet.
14628 	 * b> there is enough room to copy over the link
14629 	 * layer header.
14630 	 *
14631 	 * Once the checks are done, adjust rptr so that
14632 	 * the link layer header will be copied via
14633 	 * copymsg. Note that, IFT_ETHER may be returned
14634 	 * by some non-ethernet drivers but in this case
14635 	 * the second check will fail.
14636 	 */
14637 	if (ill->ill_type == IFT_ETHER &&
14638 	    (mp->b_rptr - mp->b_datap->db_base) >=
14639 	    sizeof (struct ether_header)) {
14640 		mp->b_rptr -= sizeof (struct ether_header);
14641 		adjusted = B_TRUE;
14642 	}
14643 	mp1 = copymsg(mp);
14644 
14645 	if (mp1 == NULL) {
14646 		mp->b_next = NULL;
14647 		/* clear b_prev - used by ip_mroute_decap */
14648 		mp->b_prev = NULL;
14649 		freemsg(mp);
14650 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14651 		return (NULL);
14652 	}
14653 
14654 	if (adjusted) {
14655 		/*
14656 		 * Copy is done. Restore the pointer in
14657 		 * the _new_ mblk
14658 		 */
14659 		mp1->b_rptr += sizeof (struct ether_header);
14660 	}
14661 
14662 	/* Copy b_prev - used by ip_mroute_decap */
14663 	mp1->b_prev = mp->b_prev;
14664 	mp->b_prev = NULL;
14665 
14666 	/* preserve the hardware checksum flags and data, if present */
14667 	if (DB_CKSUMFLAGS(mp) != 0) {
14668 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14669 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14670 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14671 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14672 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14673 	}
14674 
14675 	freemsg(mp);
14676 	return (mp1);
14677 }
14678 
14679 #define	ADD_TO_CHAIN(head, tail, cnt, mp) {    			\
14680 	if (tail != NULL)					\
14681 		tail->b_next = mp;				\
14682 	else							\
14683 		head = mp;					\
14684 	tail = mp;						\
14685 	cnt++;							\
14686 }
14687 
14688 /*
14689  * Direct read side procedure capable of dealing with chains. GLDv3 based
14690  * drivers call this function directly with mblk chains while STREAMS
14691  * read side procedure ip_rput() calls this for single packet with ip_ring
14692  * set to NULL to process one packet at a time.
14693  *
14694  * The ill will always be valid if this function is called directly from
14695  * the driver.
14696  *
14697  * If ip_input() is called from GLDv3:
14698  *
14699  *   - This must be a non-VLAN IP stream.
14700  *   - 'mp' is either an untagged or a special priority-tagged packet.
14701  *   - Any VLAN tag that was in the MAC header has been stripped.
14702  *
14703  * If the IP header in packet is not 32-bit aligned, every message in the
14704  * chain will be aligned before further operations. This is required on SPARC
14705  * platform.
14706  */
14707 /* ARGSUSED */
14708 void
14709 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14710     struct mac_header_info_s *mhip)
14711 {
14712 	ipaddr_t		dst = NULL;
14713 	ipaddr_t		prev_dst;
14714 	ire_t			*ire = NULL;
14715 	ipha_t			*ipha;
14716 	uint_t			pkt_len;
14717 	ssize_t			len;
14718 	uint_t			opt_len;
14719 	int			ll_multicast;
14720 	int			cgtp_flt_pkt;
14721 	queue_t			*q = ill->ill_rq;
14722 	squeue_t		*curr_sqp = NULL;
14723 	mblk_t 			*head = NULL;
14724 	mblk_t			*tail = NULL;
14725 	mblk_t			*first_mp;
14726 	int			cnt = 0;
14727 	ip_stack_t		*ipst = ill->ill_ipst;
14728 	mblk_t			*mp;
14729 	mblk_t			*dmp;
14730 	uint8_t			tag;
14731 
14732 	ASSERT(mp_chain != NULL);
14733 	ASSERT(ill != NULL);
14734 
14735 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14736 
14737 	tag = (ip_ring != NULL) ? SQTAG_IP_INPUT_RX_RING : SQTAG_IP_INPUT;
14738 
14739 #define	rptr	((uchar_t *)ipha)
14740 
14741 	while (mp_chain != NULL) {
14742 		mp = mp_chain;
14743 		mp_chain = mp_chain->b_next;
14744 		mp->b_next = NULL;
14745 		ll_multicast = 0;
14746 
14747 		/*
14748 		 * We do ire caching from one iteration to
14749 		 * another. In the event the packet chain contains
14750 		 * all packets from the same dst, this caching saves
14751 		 * an ire_cache_lookup for each of the succeeding
14752 		 * packets in a packet chain.
14753 		 */
14754 		prev_dst = dst;
14755 
14756 		/*
14757 		 * if db_ref > 1 then copymsg and free original. Packet
14758 		 * may be changed and we do not want the other entity
14759 		 * who has a reference to this message to trip over the
14760 		 * changes. This is a blind change because trying to
14761 		 * catch all places that might change the packet is too
14762 		 * difficult.
14763 		 *
14764 		 * This corresponds to the fast path case, where we have
14765 		 * a chain of M_DATA mblks.  We check the db_ref count
14766 		 * of only the 1st data block in the mblk chain. There
14767 		 * doesn't seem to be a reason why a device driver would
14768 		 * send up data with varying db_ref counts in the mblk
14769 		 * chain. In any case the Fast path is a private
14770 		 * interface, and our drivers don't do such a thing.
14771 		 * Given the above assumption, there is no need to walk
14772 		 * down the entire mblk chain (which could have a
14773 		 * potential performance problem)
14774 		 *
14775 		 * The "(DB_REF(mp) > 1)" check was moved from ip_rput()
14776 		 * to here because of exclusive ip stacks and vnics.
14777 		 * Packets transmitted from exclusive stack over vnic
14778 		 * can have db_ref > 1 and when it gets looped back to
14779 		 * another vnic in a different zone, you have ip_input()
14780 		 * getting dblks with db_ref > 1. So if someone
14781 		 * complains of TCP performance under this scenario,
14782 		 * take a serious look here on the impact of copymsg().
14783 		 */
14784 
14785 		if (DB_REF(mp) > 1) {
14786 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14787 				continue;
14788 		}
14789 
14790 		/*
14791 		 * Check and align the IP header.
14792 		 */
14793 		first_mp = mp;
14794 		if (DB_TYPE(mp) == M_DATA) {
14795 			dmp = mp;
14796 		} else if (DB_TYPE(mp) == M_PROTO &&
14797 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14798 			dmp = mp->b_cont;
14799 		} else {
14800 			dmp = NULL;
14801 		}
14802 		if (dmp != NULL) {
14803 			/*
14804 			 * IP header ptr not aligned?
14805 			 * OR IP header not complete in first mblk
14806 			 */
14807 			if (!OK_32PTR(dmp->b_rptr) ||
14808 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14809 				if (!ip_check_and_align_header(q, dmp, ipst))
14810 					continue;
14811 			}
14812 		}
14813 
14814 		/*
14815 		 * ip_input fast path
14816 		 */
14817 
14818 		/* mblk type is not M_DATA */
14819 		if (DB_TYPE(mp) != M_DATA) {
14820 			if (ip_rput_process_notdata(q, &first_mp, ill,
14821 			    &ll_multicast, &mp))
14822 				continue;
14823 
14824 			/*
14825 			 * The only way we can get here is if we had a
14826 			 * packet that was either a DL_UNITDATA_IND or
14827 			 * an M_CTL for an IPsec accelerated packet.
14828 			 *
14829 			 * In either case, the first_mp will point to
14830 			 * the leading M_PROTO or M_CTL.
14831 			 */
14832 			ASSERT(first_mp != NULL);
14833 		} else if (mhip != NULL) {
14834 			/*
14835 			 * ll_multicast is set here so that it is ready
14836 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
14837 			 * manipulates ll_multicast in the same fashion when
14838 			 * called from ip_rput_process_notdata.
14839 			 */
14840 			switch (mhip->mhi_dsttype) {
14841 			case MAC_ADDRTYPE_MULTICAST :
14842 				ll_multicast = HPE_MULTICAST;
14843 				break;
14844 			case MAC_ADDRTYPE_BROADCAST :
14845 				ll_multicast = HPE_BROADCAST;
14846 				break;
14847 			default :
14848 				break;
14849 			}
14850 		}
14851 
14852 		/* Only M_DATA can come here and it is always aligned */
14853 		ASSERT(DB_TYPE(mp) == M_DATA);
14854 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
14855 
14856 		ipha = (ipha_t *)mp->b_rptr;
14857 		len = mp->b_wptr - rptr;
14858 		pkt_len = ntohs(ipha->ipha_length);
14859 
14860 		/*
14861 		 * We must count all incoming packets, even if they end
14862 		 * up being dropped later on.
14863 		 */
14864 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
14865 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
14866 
14867 		/* multiple mblk or too short */
14868 		len -= pkt_len;
14869 		if (len != 0) {
14870 			/*
14871 			 * Make sure we have data length consistent
14872 			 * with the IP header.
14873 			 */
14874 			if (mp->b_cont == NULL) {
14875 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14876 					BUMP_MIB(ill->ill_ip_mib,
14877 					    ipIfStatsInHdrErrors);
14878 					ip2dbg(("ip_input: drop pkt\n"));
14879 					freemsg(mp);
14880 					continue;
14881 				}
14882 				mp->b_wptr = rptr + pkt_len;
14883 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
14884 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14885 					BUMP_MIB(ill->ill_ip_mib,
14886 					    ipIfStatsInHdrErrors);
14887 					ip2dbg(("ip_input: drop pkt\n"));
14888 					freemsg(mp);
14889 					continue;
14890 				}
14891 				(void) adjmsg(mp, -len);
14892 				IP_STAT(ipst, ip_multimblk3);
14893 			}
14894 		}
14895 
14896 		/* Obtain the dst of the current packet */
14897 		dst = ipha->ipha_dst;
14898 
14899 		DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL,
14900 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *,
14901 		    ipha, ip6_t *, NULL, int, 0);
14902 
14903 		/*
14904 		 * The following test for loopback is faster than
14905 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
14906 		 * operations.
14907 		 * Note that these addresses are always in network byte order
14908 		 */
14909 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
14910 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
14911 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
14912 			freemsg(mp);
14913 			continue;
14914 		}
14915 
14916 		/*
14917 		 * The event for packets being received from a 'physical'
14918 		 * interface is placed after validation of the source and/or
14919 		 * destination address as being local so that packets can be
14920 		 * redirected to loopback addresses using ipnat.
14921 		 */
14922 		DTRACE_PROBE4(ip4__physical__in__start,
14923 		    ill_t *, ill, ill_t *, NULL,
14924 		    ipha_t *, ipha, mblk_t *, first_mp);
14925 
14926 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
14927 		    ipst->ips_ipv4firewall_physical_in,
14928 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
14929 
14930 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
14931 
14932 		if (first_mp == NULL) {
14933 			continue;
14934 		}
14935 		dst = ipha->ipha_dst;
14936 		/*
14937 		 * Attach any necessary label information to
14938 		 * this packet
14939 		 */
14940 		if (is_system_labeled() &&
14941 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
14942 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14943 			freemsg(mp);
14944 			continue;
14945 		}
14946 
14947 		if (ipst->ips_ipobs_enabled) {
14948 			zoneid_t dzone;
14949 
14950 			/*
14951 			 * On the inbound path the src zone will be unknown as
14952 			 * this packet has come from the wire.
14953 			 */
14954 			dzone = ip_get_zoneid_v4(dst, mp, ipst, ALL_ZONES);
14955 			ipobs_hook(mp, IPOBS_HOOK_INBOUND, ALL_ZONES, dzone,
14956 			    ill, IPV4_VERSION, 0, ipst);
14957 		}
14958 
14959 		/*
14960 		 * Reuse the cached ire only if the ipha_dst of the previous
14961 		 * packet is the same as the current packet AND it is not
14962 		 * INADDR_ANY.
14963 		 */
14964 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
14965 		    (ire != NULL)) {
14966 			ire_refrele(ire);
14967 			ire = NULL;
14968 		}
14969 
14970 		opt_len = ipha->ipha_version_and_hdr_length -
14971 		    IP_SIMPLE_HDR_VERSION;
14972 
14973 		/*
14974 		 * Check to see if we can take the fastpath.
14975 		 * That is possible if the following conditions are met
14976 		 *	o Tsol disabled
14977 		 *	o CGTP disabled
14978 		 *	o ipp_action_count is 0
14979 		 *	o no options in the packet
14980 		 *	o not a RSVP packet
14981 		 * 	o not a multicast packet
14982 		 *	o ill not in IP_DHCPINIT_IF mode
14983 		 */
14984 		if (!is_system_labeled() &&
14985 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
14986 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
14987 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
14988 			if (ire == NULL)
14989 				ire = ire_cache_lookup_simple(dst, ipst);
14990 			/*
14991 			 * Unless forwarding is enabled, dont call
14992 			 * ip_fast_forward(). Incoming packet is for forwarding
14993 			 */
14994 			if ((ill->ill_flags & ILLF_ROUTER) &&
14995 			    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
14996 				ire = ip_fast_forward(ire, dst, ill, mp);
14997 				continue;
14998 			}
14999 			/* incoming packet is for local consumption */
15000 			if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15001 				goto local;
15002 		}
15003 
15004 		/*
15005 		 * Disable ire caching for anything more complex
15006 		 * than the simple fast path case we checked for above.
15007 		 */
15008 		if (ire != NULL) {
15009 			ire_refrele(ire);
15010 			ire = NULL;
15011 		}
15012 
15013 		/*
15014 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15015 		 * server to unicast DHCP packets to a DHCP client using the
15016 		 * IP address it is offering to the client.  This can be
15017 		 * disabled through the "broadcast bit", but not all DHCP
15018 		 * servers honor that bit.  Therefore, to interoperate with as
15019 		 * many DHCP servers as possible, the DHCP client allows the
15020 		 * server to unicast, but we treat those packets as broadcast
15021 		 * here.  Note that we don't rewrite the packet itself since
15022 		 * (a) that would mess up the checksums and (b) the DHCP
15023 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15024 		 * hand it the packet regardless.
15025 		 */
15026 		if (ill->ill_dhcpinit != 0 &&
15027 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15028 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15029 			udpha_t *udpha;
15030 
15031 			/*
15032 			 * Reload ipha since pullupmsg() can change b_rptr.
15033 			 */
15034 			ipha = (ipha_t *)mp->b_rptr;
15035 			udpha = (udpha_t *)&ipha[1];
15036 
15037 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15038 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15039 				    mblk_t *, mp);
15040 				dst = INADDR_BROADCAST;
15041 			}
15042 		}
15043 
15044 		/* Full-blown slow path */
15045 		if (opt_len != 0) {
15046 			if (len != 0)
15047 				IP_STAT(ipst, ip_multimblk4);
15048 			else
15049 				IP_STAT(ipst, ip_ipoptions);
15050 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15051 			    &dst, ipst))
15052 				continue;
15053 		}
15054 
15055 		/*
15056 		 * Invoke the CGTP (multirouting) filtering module to process
15057 		 * the incoming packet. Packets identified as duplicates
15058 		 * must be discarded. Filtering is active only if the
15059 		 * the ip_cgtp_filter ndd variable is non-zero.
15060 		 */
15061 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15062 		if (ipst->ips_ip_cgtp_filter &&
15063 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15064 			netstackid_t stackid;
15065 
15066 			stackid = ipst->ips_netstack->netstack_stackid;
15067 			cgtp_flt_pkt =
15068 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15069 			    ill->ill_phyint->phyint_ifindex, mp);
15070 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15071 				freemsg(first_mp);
15072 				continue;
15073 			}
15074 		}
15075 
15076 		/*
15077 		 * If rsvpd is running, let RSVP daemon handle its processing
15078 		 * and forwarding of RSVP multicast/unicast packets.
15079 		 * If rsvpd is not running but mrouted is running, RSVP
15080 		 * multicast packets are forwarded as multicast traffic
15081 		 * and RSVP unicast packets are forwarded by unicast router.
15082 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15083 		 * packets are not forwarded, but the unicast packets are
15084 		 * forwarded like unicast traffic.
15085 		 */
15086 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15087 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15088 		    NULL) {
15089 			/* RSVP packet and rsvpd running. Treat as ours */
15090 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15091 			/*
15092 			 * This assumes that we deliver to all streams for
15093 			 * multicast and broadcast packets.
15094 			 * We have to force ll_multicast to 1 to handle the
15095 			 * M_DATA messages passed in from ip_mroute_decap.
15096 			 */
15097 			dst = INADDR_BROADCAST;
15098 			ll_multicast = 1;
15099 		} else if (CLASSD(dst)) {
15100 			/* packet is multicast */
15101 			mp->b_next = NULL;
15102 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15103 			    &ll_multicast, &dst))
15104 				continue;
15105 		}
15106 
15107 		if (ire == NULL) {
15108 			ire = ire_cache_lookup(dst, ALL_ZONES,
15109 			    MBLK_GETLABEL(mp), ipst);
15110 		}
15111 
15112 		if (ire != NULL && ire->ire_stq != NULL &&
15113 		    ire->ire_zoneid != GLOBAL_ZONEID &&
15114 		    ire->ire_zoneid != ALL_ZONES) {
15115 			/*
15116 			 * Should only use IREs that are visible from the
15117 			 * global zone for forwarding.
15118 			 */
15119 			ire_refrele(ire);
15120 			ire = ire_cache_lookup(dst, GLOBAL_ZONEID,
15121 			    MBLK_GETLABEL(mp), ipst);
15122 		}
15123 
15124 		if (ire == NULL) {
15125 			/*
15126 			 * No IRE for this destination, so it can't be for us.
15127 			 * Unless we are forwarding, drop the packet.
15128 			 * We have to let source routed packets through
15129 			 * since we don't yet know if they are 'ping -l'
15130 			 * packets i.e. if they will go out over the
15131 			 * same interface as they came in on.
15132 			 */
15133 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15134 			if (ire == NULL)
15135 				continue;
15136 		}
15137 
15138 		/*
15139 		 * Broadcast IRE may indicate either broadcast or
15140 		 * multicast packet
15141 		 */
15142 		if (ire->ire_type == IRE_BROADCAST) {
15143 			/*
15144 			 * Skip broadcast checks if packet is UDP multicast;
15145 			 * we'd rather not enter ip_rput_process_broadcast()
15146 			 * unless the packet is broadcast for real, since
15147 			 * that routine is a no-op for multicast.
15148 			 */
15149 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15150 			    !CLASSD(ipha->ipha_dst)) {
15151 				ire = ip_rput_process_broadcast(&q, mp,
15152 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15153 				    ll_multicast);
15154 				if (ire == NULL)
15155 					continue;
15156 			}
15157 		} else if (ire->ire_stq != NULL) {
15158 			/* fowarding? */
15159 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15160 			    ll_multicast, B_FALSE);
15161 			/* ip_rput_process_forward consumed the packet */
15162 			continue;
15163 		}
15164 
15165 local:
15166 		/*
15167 		 * If the queue in the ire is different to the ingress queue
15168 		 * then we need to check to see if we can accept the packet.
15169 		 * Note that for multicast packets and broadcast packets sent
15170 		 * to a broadcast address which is shared between multiple
15171 		 * interfaces we should not do this since we just got a random
15172 		 * broadcast ire.
15173 		 */
15174 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15175 			ire = ip_check_multihome(&ipha->ipha_dst, ire, ill);
15176 			if (ire == NULL) {
15177 				/* Drop packet */
15178 				BUMP_MIB(ill->ill_ip_mib,
15179 				    ipIfStatsForwProhibits);
15180 				freemsg(mp);
15181 				continue;
15182 			}
15183 			if (ire->ire_rfq != NULL)
15184 				q = ire->ire_rfq;
15185 		}
15186 
15187 		switch (ipha->ipha_protocol) {
15188 		case IPPROTO_TCP:
15189 			ASSERT(first_mp == mp);
15190 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15191 			    mp, 0, q, ip_ring)) != NULL) {
15192 				if (curr_sqp == NULL) {
15193 					curr_sqp = GET_SQUEUE(mp);
15194 					ASSERT(cnt == 0);
15195 					cnt++;
15196 					head = tail = mp;
15197 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15198 					ASSERT(tail != NULL);
15199 					cnt++;
15200 					tail->b_next = mp;
15201 					tail = mp;
15202 				} else {
15203 					/*
15204 					 * A different squeue. Send the
15205 					 * chain for the previous squeue on
15206 					 * its way. This shouldn't happen
15207 					 * often unless interrupt binding
15208 					 * changes.
15209 					 */
15210 					IP_STAT(ipst, ip_input_multi_squeue);
15211 					SQUEUE_ENTER(curr_sqp, head,
15212 					    tail, cnt, SQ_PROCESS, tag);
15213 					curr_sqp = GET_SQUEUE(mp);
15214 					head = mp;
15215 					tail = mp;
15216 					cnt = 1;
15217 				}
15218 			}
15219 			continue;
15220 		case IPPROTO_UDP:
15221 			ASSERT(first_mp == mp);
15222 			ip_udp_input(q, mp, ipha, ire, ill);
15223 			continue;
15224 		case IPPROTO_SCTP:
15225 			ASSERT(first_mp == mp);
15226 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15227 			    q, dst);
15228 			/* ire has been released by ip_sctp_input */
15229 			ire = NULL;
15230 			continue;
15231 		default:
15232 			ip_proto_input(q, first_mp, ipha, ire, ill, 0);
15233 			continue;
15234 		}
15235 	}
15236 
15237 	if (ire != NULL)
15238 		ire_refrele(ire);
15239 
15240 	if (head != NULL)
15241 		SQUEUE_ENTER(curr_sqp, head, tail, cnt, SQ_PROCESS, tag);
15242 
15243 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15244 	    "ip_input_end: q %p (%S)", q, "end");
15245 #undef  rptr
15246 }
15247 
15248 /*
15249  * ip_accept_tcp() - This function is called by the squeue when it retrieves
15250  * a chain of packets in the poll mode. The packets have gone through the
15251  * data link processing but not IP processing. For performance and latency
15252  * reasons, the squeue wants to process the chain in line instead of feeding
15253  * it back via ip_input path.
15254  *
15255  * So this is a light weight function which checks to see if the packets
15256  * retrived are indeed TCP packets (TCP squeue always polls TCP soft ring
15257  * but we still do the paranoid check) meant for local machine and we don't
15258  * have labels etc enabled. Packets that meet the criterion are returned to
15259  * the squeue and processed inline while the rest go via ip_input path.
15260  */
15261 /*ARGSUSED*/
15262 mblk_t *
15263 ip_accept_tcp(ill_t *ill, ill_rx_ring_t *ip_ring, squeue_t *target_sqp,
15264     mblk_t *mp_chain, mblk_t **last, uint_t *cnt)
15265 {
15266 	mblk_t 		*mp;
15267 	ipaddr_t	dst = NULL;
15268 	ipaddr_t	prev_dst;
15269 	ire_t		*ire = NULL;
15270 	ipha_t		*ipha;
15271 	uint_t		pkt_len;
15272 	ssize_t		len;
15273 	uint_t		opt_len;
15274 	queue_t		*q = ill->ill_rq;
15275 	squeue_t	*curr_sqp;
15276 	mblk_t 		*ahead = NULL;	/* Accepted head */
15277 	mblk_t		*atail = NULL;	/* Accepted tail */
15278 	uint_t		acnt = 0;	/* Accepted count */
15279 	mblk_t		*utail = NULL;	/* Unaccepted head */
15280 	mblk_t		*uhead = NULL;	/* Unaccepted tail */
15281 	uint_t		ucnt = 0;	/* Unaccepted cnt */
15282 	ip_stack_t	*ipst = ill->ill_ipst;
15283 
15284 	*cnt = 0;
15285 
15286 	ASSERT(ill != NULL);
15287 	ASSERT(ip_ring != NULL);
15288 
15289 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_accept_tcp: q %p", q);
15290 
15291 #define	rptr	((uchar_t *)ipha)
15292 
15293 	while (mp_chain != NULL) {
15294 		mp = mp_chain;
15295 		mp_chain = mp_chain->b_next;
15296 		mp->b_next = NULL;
15297 
15298 		/*
15299 		 * We do ire caching from one iteration to
15300 		 * another. In the event the packet chain contains
15301 		 * all packets from the same dst, this caching saves
15302 		 * an ire_cache_lookup for each of the succeeding
15303 		 * packets in a packet chain.
15304 		 */
15305 		prev_dst = dst;
15306 
15307 		ipha = (ipha_t *)mp->b_rptr;
15308 		len = mp->b_wptr - rptr;
15309 
15310 		ASSERT(!MBLK_RX_FANOUT_SLOWPATH(mp, ipha));
15311 
15312 		/*
15313 		 * If it is a non TCP packet, or doesn't have H/W cksum,
15314 		 * or doesn't have min len, reject.
15315 		 */
15316 		if ((ipha->ipha_protocol != IPPROTO_TCP) || (len <
15317 		    (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH))) {
15318 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15319 			continue;
15320 		}
15321 
15322 		pkt_len = ntohs(ipha->ipha_length);
15323 		if (len != pkt_len) {
15324 			if (len > pkt_len) {
15325 				mp->b_wptr = rptr + pkt_len;
15326 			} else {
15327 				ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15328 				continue;
15329 			}
15330 		}
15331 
15332 		opt_len = ipha->ipha_version_and_hdr_length -
15333 		    IP_SIMPLE_HDR_VERSION;
15334 		dst = ipha->ipha_dst;
15335 
15336 		/* IP version bad or there are IP options */
15337 		if (opt_len && (!ip_rput_multimblk_ipoptions(q, ill,
15338 		    mp, &ipha, &dst, ipst)))
15339 			continue;
15340 
15341 		if (is_system_labeled() || (ill->ill_dhcpinit != 0) ||
15342 		    (ipst->ips_ip_cgtp_filter &&
15343 		    ipst->ips_ip_cgtp_filter_ops != NULL)) {
15344 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15345 			continue;
15346 		}
15347 
15348 		/*
15349 		 * Reuse the cached ire only if the ipha_dst of the previous
15350 		 * packet is the same as the current packet AND it is not
15351 		 * INADDR_ANY.
15352 		 */
15353 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15354 		    (ire != NULL)) {
15355 			ire_refrele(ire);
15356 			ire = NULL;
15357 		}
15358 
15359 		if (ire == NULL)
15360 			ire = ire_cache_lookup_simple(dst, ipst);
15361 
15362 		/*
15363 		 * Unless forwarding is enabled, dont call
15364 		 * ip_fast_forward(). Incoming packet is for forwarding
15365 		 */
15366 		if ((ill->ill_flags & ILLF_ROUTER) &&
15367 		    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15368 
15369 			DTRACE_PROBE4(ip4__physical__in__start,
15370 			    ill_t *, ill, ill_t *, NULL,
15371 			    ipha_t *, ipha, mblk_t *, mp);
15372 
15373 			FW_HOOKS(ipst->ips_ip4_physical_in_event,
15374 			    ipst->ips_ipv4firewall_physical_in,
15375 			    ill, NULL, ipha, mp, mp, 0, ipst);
15376 
15377 			DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15378 
15379 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15380 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets,
15381 			    pkt_len);
15382 
15383 			ire = ip_fast_forward(ire, dst, ill, mp);
15384 			continue;
15385 		}
15386 
15387 		/* incoming packet is for local consumption */
15388 		if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15389 			goto local_accept;
15390 
15391 		/*
15392 		 * Disable ire caching for anything more complex
15393 		 * than the simple fast path case we checked for above.
15394 		 */
15395 		if (ire != NULL) {
15396 			ire_refrele(ire);
15397 			ire = NULL;
15398 		}
15399 
15400 		ire = ire_cache_lookup(dst, ALL_ZONES, MBLK_GETLABEL(mp),
15401 		    ipst);
15402 		if (ire == NULL || ire->ire_type == IRE_BROADCAST ||
15403 		    ire->ire_stq != NULL) {
15404 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15405 			if (ire != NULL) {
15406 				ire_refrele(ire);
15407 				ire = NULL;
15408 			}
15409 			continue;
15410 		}
15411 
15412 local_accept:
15413 
15414 		if (ire->ire_rfq != q) {
15415 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15416 			if (ire != NULL) {
15417 				ire_refrele(ire);
15418 				ire = NULL;
15419 			}
15420 			continue;
15421 		}
15422 
15423 		/*
15424 		 * The event for packets being received from a 'physical'
15425 		 * interface is placed after validation of the source and/or
15426 		 * destination address as being local so that packets can be
15427 		 * redirected to loopback addresses using ipnat.
15428 		 */
15429 		DTRACE_PROBE4(ip4__physical__in__start,
15430 		    ill_t *, ill, ill_t *, NULL,
15431 		    ipha_t *, ipha, mblk_t *, mp);
15432 
15433 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15434 		    ipst->ips_ipv4firewall_physical_in,
15435 		    ill, NULL, ipha, mp, mp, 0, ipst);
15436 
15437 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15438 
15439 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15440 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15441 
15442 		if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire, mp,
15443 		    0, q, ip_ring)) != NULL) {
15444 			if ((curr_sqp = GET_SQUEUE(mp)) == target_sqp) {
15445 				ADD_TO_CHAIN(ahead, atail, acnt, mp);
15446 			} else {
15447 				SQUEUE_ENTER(curr_sqp, mp, mp, 1,
15448 				    SQ_FILL, SQTAG_IP_INPUT);
15449 			}
15450 		}
15451 	}
15452 
15453 	if (ire != NULL)
15454 		ire_refrele(ire);
15455 
15456 	if (uhead != NULL)
15457 		ip_input(ill, ip_ring, uhead, NULL);
15458 
15459 	if (ahead != NULL) {
15460 		*last = atail;
15461 		*cnt = acnt;
15462 		return (ahead);
15463 	}
15464 
15465 	return (NULL);
15466 #undef  rptr
15467 }
15468 
15469 static void
15470 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15471     t_uscalar_t err)
15472 {
15473 	if (dl_err == DL_SYSERR) {
15474 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15475 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15476 		    ill->ill_name, dl_primstr(prim), err);
15477 		return;
15478 	}
15479 
15480 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15481 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15482 	    dl_errstr(dl_err));
15483 }
15484 
15485 /*
15486  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15487  * than DL_UNITDATA_IND messages. If we need to process this message
15488  * exclusively, we call qwriter_ip, in which case we also need to call
15489  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15490  */
15491 void
15492 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15493 {
15494 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15495 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15496 	ill_t		*ill = q->q_ptr;
15497 	t_uscalar_t	prim = dloa->dl_primitive;
15498 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
15499 
15500 	ip1dbg(("ip_rput_dlpi"));
15501 
15502 	/*
15503 	 * If we received an ACK but didn't send a request for it, then it
15504 	 * can't be part of any pending operation; discard up-front.
15505 	 */
15506 	switch (prim) {
15507 	case DL_ERROR_ACK:
15508 		reqprim = dlea->dl_error_primitive;
15509 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
15510 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
15511 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
15512 		    dlea->dl_unix_errno));
15513 		break;
15514 	case DL_OK_ACK:
15515 		reqprim = dloa->dl_correct_primitive;
15516 		break;
15517 	case DL_INFO_ACK:
15518 		reqprim = DL_INFO_REQ;
15519 		break;
15520 	case DL_BIND_ACK:
15521 		reqprim = DL_BIND_REQ;
15522 		break;
15523 	case DL_PHYS_ADDR_ACK:
15524 		reqprim = DL_PHYS_ADDR_REQ;
15525 		break;
15526 	case DL_NOTIFY_ACK:
15527 		reqprim = DL_NOTIFY_REQ;
15528 		break;
15529 	case DL_CONTROL_ACK:
15530 		reqprim = DL_CONTROL_REQ;
15531 		break;
15532 	case DL_CAPABILITY_ACK:
15533 		reqprim = DL_CAPABILITY_REQ;
15534 		break;
15535 	}
15536 
15537 	if (prim != DL_NOTIFY_IND) {
15538 		if (reqprim == DL_PRIM_INVAL ||
15539 		    !ill_dlpi_pending(ill, reqprim)) {
15540 			/* Not a DLPI message we support or expected */
15541 			freemsg(mp);
15542 			return;
15543 		}
15544 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
15545 		    dl_primstr(reqprim)));
15546 	}
15547 
15548 	switch (reqprim) {
15549 	case DL_UNBIND_REQ:
15550 		/*
15551 		 * NOTE: we mark the unbind as complete even if we got a
15552 		 * DL_ERROR_ACK, since there's not much else we can do.
15553 		 */
15554 		mutex_enter(&ill->ill_lock);
15555 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15556 		cv_signal(&ill->ill_cv);
15557 		mutex_exit(&ill->ill_lock);
15558 		break;
15559 
15560 	case DL_ENABMULTI_REQ:
15561 		if (prim == DL_OK_ACK) {
15562 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15563 				ill->ill_dlpi_multicast_state = IDS_OK;
15564 		}
15565 		break;
15566 	}
15567 
15568 	/*
15569 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
15570 	 * need to become writer to continue to process it.  Because an
15571 	 * exclusive operation doesn't complete until replies to all queued
15572 	 * DLPI messages have been received, we know we're in the middle of an
15573 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
15574 	 *
15575 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15576 	 * Since this is on the ill stream we unconditionally bump up the
15577 	 * refcount without doing ILL_CAN_LOOKUP().
15578 	 */
15579 	ill_refhold(ill);
15580 	if (prim == DL_NOTIFY_IND)
15581 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15582 	else
15583 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15584 }
15585 
15586 /*
15587  * Handling of DLPI messages that require exclusive access to the ipsq.
15588  *
15589  * Need to do ill_pending_mp_release on ioctl completion, which could
15590  * happen here. (along with mi_copy_done)
15591  */
15592 /* ARGSUSED */
15593 static void
15594 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15595 {
15596 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15597 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15598 	int		err = 0;
15599 	ill_t		*ill;
15600 	ipif_t		*ipif = NULL;
15601 	mblk_t		*mp1 = NULL;
15602 	conn_t		*connp = NULL;
15603 	t_uscalar_t	paddrreq;
15604 	mblk_t		*mp_hw;
15605 	boolean_t	success;
15606 	boolean_t	ioctl_aborted = B_FALSE;
15607 	boolean_t	log = B_TRUE;
15608 	ip_stack_t		*ipst;
15609 
15610 	ip1dbg(("ip_rput_dlpi_writer .."));
15611 	ill = (ill_t *)q->q_ptr;
15612 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
15613 	ASSERT(IAM_WRITER_ILL(ill));
15614 
15615 	ipst = ill->ill_ipst;
15616 
15617 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
15618 	/*
15619 	 * The current ioctl could have been aborted by the user and a new
15620 	 * ioctl to bring up another ill could have started. We could still
15621 	 * get a response from the driver later.
15622 	 */
15623 	if (ipif != NULL && ipif->ipif_ill != ill)
15624 		ioctl_aborted = B_TRUE;
15625 
15626 	switch (dloa->dl_primitive) {
15627 	case DL_ERROR_ACK:
15628 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15629 		    dl_primstr(dlea->dl_error_primitive)));
15630 
15631 		switch (dlea->dl_error_primitive) {
15632 		case DL_DISABMULTI_REQ:
15633 			if (!ill->ill_isv6)
15634 				ipsq_current_finish(ipsq);
15635 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15636 			break;
15637 		case DL_PROMISCON_REQ:
15638 		case DL_PROMISCOFF_REQ:
15639 		case DL_UNBIND_REQ:
15640 		case DL_ATTACH_REQ:
15641 		case DL_INFO_REQ:
15642 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15643 			break;
15644 		case DL_NOTIFY_REQ:
15645 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15646 			log = B_FALSE;
15647 			break;
15648 		case DL_PHYS_ADDR_REQ:
15649 			/*
15650 			 * For IPv6 only, there are two additional
15651 			 * phys_addr_req's sent to the driver to get the
15652 			 * IPv6 token and lla. This allows IP to acquire
15653 			 * the hardware address format for a given interface
15654 			 * without having built in knowledge of the hardware
15655 			 * address. ill_phys_addr_pend keeps track of the last
15656 			 * DL_PAR sent so we know which response we are
15657 			 * dealing with. ill_dlpi_done will update
15658 			 * ill_phys_addr_pend when it sends the next req.
15659 			 * We don't complete the IOCTL until all three DL_PARs
15660 			 * have been attempted, so set *_len to 0 and break.
15661 			 */
15662 			paddrreq = ill->ill_phys_addr_pend;
15663 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15664 			if (paddrreq == DL_IPV6_TOKEN) {
15665 				ill->ill_token_length = 0;
15666 				log = B_FALSE;
15667 				break;
15668 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15669 				ill->ill_nd_lla_len = 0;
15670 				log = B_FALSE;
15671 				break;
15672 			}
15673 			/*
15674 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15675 			 * We presumably have an IOCTL hanging out waiting
15676 			 * for completion. Find it and complete the IOCTL
15677 			 * with the error noted.
15678 			 * However, ill_dl_phys was called on an ill queue
15679 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15680 			 * set. But the ioctl is known to be pending on ill_wq.
15681 			 */
15682 			if (!ill->ill_ifname_pending)
15683 				break;
15684 			ill->ill_ifname_pending = 0;
15685 			if (!ioctl_aborted)
15686 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15687 			if (mp1 != NULL) {
15688 				/*
15689 				 * This operation (SIOCSLIFNAME) must have
15690 				 * happened on the ill. Assert there is no conn
15691 				 */
15692 				ASSERT(connp == NULL);
15693 				q = ill->ill_wq;
15694 			}
15695 			break;
15696 		case DL_BIND_REQ:
15697 			ill_dlpi_done(ill, DL_BIND_REQ);
15698 			if (ill->ill_ifname_pending)
15699 				break;
15700 			/*
15701 			 * Something went wrong with the bind.  We presumably
15702 			 * have an IOCTL hanging out waiting for completion.
15703 			 * Find it, take down the interface that was coming
15704 			 * up, and complete the IOCTL with the error noted.
15705 			 */
15706 			if (!ioctl_aborted)
15707 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15708 			if (mp1 != NULL) {
15709 				/*
15710 				 * This operation (SIOCSLIFFLAGS) must have
15711 				 * happened from a conn.
15712 				 */
15713 				ASSERT(connp != NULL);
15714 				q = CONNP_TO_WQ(connp);
15715 				(void) ipif_down(ipif, NULL, NULL);
15716 				/* error is set below the switch */
15717 			}
15718 			break;
15719 		case DL_ENABMULTI_REQ:
15720 			if (!ill->ill_isv6)
15721 				ipsq_current_finish(ipsq);
15722 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15723 
15724 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15725 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15726 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15727 				ipif_t *ipif;
15728 
15729 				printf("ip: joining multicasts failed (%d)"
15730 				    " on %s - will use link layer "
15731 				    "broadcasts for multicast\n",
15732 				    dlea->dl_errno, ill->ill_name);
15733 
15734 				/*
15735 				 * Set up the multicast mapping alone.
15736 				 * writer, so ok to access ill->ill_ipif
15737 				 * without any lock.
15738 				 */
15739 				ipif = ill->ill_ipif;
15740 				mutex_enter(&ill->ill_phyint->phyint_lock);
15741 				ill->ill_phyint->phyint_flags |=
15742 				    PHYI_MULTI_BCAST;
15743 				mutex_exit(&ill->ill_phyint->phyint_lock);
15744 
15745 				if (!ill->ill_isv6) {
15746 					(void) ipif_arp_setup_multicast(ipif,
15747 					    NULL);
15748 				} else {
15749 					(void) ipif_ndp_setup_multicast(ipif,
15750 					    NULL);
15751 				}
15752 			}
15753 			freemsg(mp);	/* Don't want to pass this up */
15754 			return;
15755 		case DL_CONTROL_REQ:
15756 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15757 			    "DL_CONTROL_REQ\n"));
15758 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15759 			freemsg(mp);
15760 			return;
15761 		case DL_CAPABILITY_REQ:
15762 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15763 			    "DL_CAPABILITY REQ\n"));
15764 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
15765 				ill->ill_dlpi_capab_state = IDCS_FAILED;
15766 			ill_capability_done(ill);
15767 			freemsg(mp);
15768 			return;
15769 		}
15770 		/*
15771 		 * Note the error for IOCTL completion (mp1 is set when
15772 		 * ready to complete ioctl). If ill_ifname_pending_err is
15773 		 * set, an error occured during plumbing (ill_ifname_pending),
15774 		 * so we want to report that error.
15775 		 *
15776 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15777 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15778 		 * expected to get errack'd if the driver doesn't support
15779 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15780 		 * if these error conditions are encountered.
15781 		 */
15782 		if (mp1 != NULL) {
15783 			if (ill->ill_ifname_pending_err != 0)  {
15784 				err = ill->ill_ifname_pending_err;
15785 				ill->ill_ifname_pending_err = 0;
15786 			} else {
15787 				err = dlea->dl_unix_errno ?
15788 				    dlea->dl_unix_errno : ENXIO;
15789 			}
15790 		/*
15791 		 * If we're plumbing an interface and an error hasn't already
15792 		 * been saved, set ill_ifname_pending_err to the error passed
15793 		 * up. Ignore the error if log is B_FALSE (see comment above).
15794 		 */
15795 		} else if (log && ill->ill_ifname_pending &&
15796 		    ill->ill_ifname_pending_err == 0) {
15797 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15798 			    dlea->dl_unix_errno : ENXIO;
15799 		}
15800 
15801 		if (log)
15802 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15803 			    dlea->dl_errno, dlea->dl_unix_errno);
15804 		break;
15805 	case DL_CAPABILITY_ACK:
15806 		ill_capability_ack(ill, mp);
15807 		/*
15808 		 * The message has been handed off to ill_capability_ack
15809 		 * and must not be freed below
15810 		 */
15811 		mp = NULL;
15812 		break;
15813 
15814 	case DL_CONTROL_ACK:
15815 		/* We treat all of these as "fire and forget" */
15816 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15817 		break;
15818 	case DL_INFO_ACK:
15819 		/* Call a routine to handle this one. */
15820 		ill_dlpi_done(ill, DL_INFO_REQ);
15821 		ip_ll_subnet_defaults(ill, mp);
15822 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15823 		return;
15824 	case DL_BIND_ACK:
15825 		/*
15826 		 * We should have an IOCTL waiting on this unless
15827 		 * sent by ill_dl_phys, in which case just return
15828 		 */
15829 		ill_dlpi_done(ill, DL_BIND_REQ);
15830 		if (ill->ill_ifname_pending)
15831 			break;
15832 
15833 		if (!ioctl_aborted)
15834 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15835 		if (mp1 == NULL)
15836 			break;
15837 		/*
15838 		 * Because mp1 was added by ill_dl_up(), and it always
15839 		 * passes a valid connp, connp must be valid here.
15840 		 */
15841 		ASSERT(connp != NULL);
15842 		q = CONNP_TO_WQ(connp);
15843 
15844 		/*
15845 		 * We are exclusive. So nothing can change even after
15846 		 * we get the pending mp. If need be we can put it back
15847 		 * and restart, as in calling ipif_arp_up()  below.
15848 		 */
15849 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15850 
15851 		mutex_enter(&ill->ill_lock);
15852 		ill->ill_dl_up = 1;
15853 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
15854 		mutex_exit(&ill->ill_lock);
15855 
15856 		/*
15857 		 * Now bring up the resolver; when that is complete, we'll
15858 		 * create IREs.  Note that we intentionally mirror what
15859 		 * ipif_up() would have done, because we got here by way of
15860 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15861 		 */
15862 		if (ill->ill_isv6) {
15863 			if (ill->ill_flags & ILLF_XRESOLV) {
15864 				mutex_enter(&connp->conn_lock);
15865 				mutex_enter(&ill->ill_lock);
15866 				success = ipsq_pending_mp_add(connp, ipif, q,
15867 				    mp1, 0);
15868 				mutex_exit(&ill->ill_lock);
15869 				mutex_exit(&connp->conn_lock);
15870 				if (success) {
15871 					err = ipif_resolver_up(ipif,
15872 					    Res_act_initial);
15873 					if (err == EINPROGRESS) {
15874 						freemsg(mp);
15875 						return;
15876 					}
15877 					ASSERT(err != 0);
15878 					mp1 = ipsq_pending_mp_get(ipsq, &connp);
15879 					ASSERT(mp1 != NULL);
15880 				} else {
15881 					/* conn has started closing */
15882 					err = EINTR;
15883 				}
15884 			} else { /* Non XRESOLV interface */
15885 				(void) ipif_resolver_up(ipif, Res_act_initial);
15886 				if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
15887 					err = ipif_up_done_v6(ipif);
15888 			}
15889 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15890 			/*
15891 			 * ARP and other v4 external resolvers.
15892 			 * Leave the pending mblk intact so that
15893 			 * the ioctl completes in ip_rput().
15894 			 */
15895 			mutex_enter(&connp->conn_lock);
15896 			mutex_enter(&ill->ill_lock);
15897 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15898 			mutex_exit(&ill->ill_lock);
15899 			mutex_exit(&connp->conn_lock);
15900 			if (success) {
15901 				err = ipif_resolver_up(ipif, Res_act_initial);
15902 				if (err == EINPROGRESS) {
15903 					freemsg(mp);
15904 					return;
15905 				}
15906 				ASSERT(err != 0);
15907 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15908 			} else {
15909 				/* The conn has started closing */
15910 				err = EINTR;
15911 			}
15912 		} else {
15913 			/*
15914 			 * This one is complete. Reply to pending ioctl.
15915 			 */
15916 			(void) ipif_resolver_up(ipif, Res_act_initial);
15917 			err = ipif_up_done(ipif);
15918 		}
15919 
15920 		if ((err == 0) && (ill->ill_up_ipifs)) {
15921 			err = ill_up_ipifs(ill, q, mp1);
15922 			if (err == EINPROGRESS) {
15923 				freemsg(mp);
15924 				return;
15925 			}
15926 		}
15927 
15928 		/*
15929 		 * If we have a moved ipif to bring up, and everything has
15930 		 * succeeded to this point, bring it up on the IPMP ill.
15931 		 * Otherwise, leave it down -- the admin can try to bring it
15932 		 * up by hand if need be.
15933 		 */
15934 		if (ill->ill_move_ipif != NULL) {
15935 			if (err != 0) {
15936 				ill->ill_move_ipif = NULL;
15937 			} else {
15938 				ipif = ill->ill_move_ipif;
15939 				ill->ill_move_ipif = NULL;
15940 				err = ipif_up(ipif, q, mp1);
15941 				if (err == EINPROGRESS) {
15942 					freemsg(mp);
15943 					return;
15944 				}
15945 			}
15946 		}
15947 		break;
15948 
15949 	case DL_NOTIFY_IND: {
15950 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15951 		ire_t *ire;
15952 		uint_t orig_mtu;
15953 		boolean_t need_ire_walk_v4 = B_FALSE;
15954 		boolean_t need_ire_walk_v6 = B_FALSE;
15955 
15956 		switch (notify->dl_notification) {
15957 		case DL_NOTE_PHYS_ADDR:
15958 			err = ill_set_phys_addr(ill, mp);
15959 			break;
15960 
15961 		case DL_NOTE_FASTPATH_FLUSH:
15962 			ill_fastpath_flush(ill);
15963 			break;
15964 
15965 		case DL_NOTE_SDU_SIZE:
15966 			/*
15967 			 * Change the MTU size of the interface, of all
15968 			 * attached ipif's, and of all relevant ire's.  The
15969 			 * new value's a uint32_t at notify->dl_data.
15970 			 * Mtu change Vs. new ire creation - protocol below.
15971 			 *
15972 			 * a Mark the ipif as IPIF_CHANGING.
15973 			 * b Set the new mtu in the ipif.
15974 			 * c Change the ire_max_frag on all affected ires
15975 			 * d Unmark the IPIF_CHANGING
15976 			 *
15977 			 * To see how the protocol works, assume an interface
15978 			 * route is also being added simultaneously by
15979 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15980 			 * the ire. If the ire is created before step a,
15981 			 * it will be cleaned up by step c. If the ire is
15982 			 * created after step d, it will see the new value of
15983 			 * ipif_mtu. Any attempt to create the ire between
15984 			 * steps a to d will fail because of the IPIF_CHANGING
15985 			 * flag. Note that ire_create() is passed a pointer to
15986 			 * the ipif_mtu, and not the value. During ire_add
15987 			 * under the bucket lock, the ire_max_frag of the
15988 			 * new ire being created is set from the ipif/ire from
15989 			 * which it is being derived.
15990 			 */
15991 			mutex_enter(&ill->ill_lock);
15992 
15993 			orig_mtu = ill->ill_max_mtu;
15994 			ill->ill_max_frag = (uint_t)notify->dl_data;
15995 			ill->ill_max_mtu = (uint_t)notify->dl_data;
15996 
15997 			/*
15998 			 * If ill_user_mtu was set (via SIOCSLIFLNKINFO),
15999 			 * clamp ill_max_mtu at it.
16000 			 */
16001 			if (ill->ill_user_mtu != 0 &&
16002 			    ill->ill_user_mtu < ill->ill_max_mtu)
16003 				ill->ill_max_mtu = ill->ill_user_mtu;
16004 
16005 			/*
16006 			 * If the MTU is unchanged, we're done.
16007 			 */
16008 			if (orig_mtu == ill->ill_max_mtu) {
16009 				mutex_exit(&ill->ill_lock);
16010 				break;
16011 			}
16012 
16013 			if (ill->ill_isv6) {
16014 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16015 					ill->ill_max_mtu = IPV6_MIN_MTU;
16016 			} else {
16017 				if (ill->ill_max_mtu < IP_MIN_MTU)
16018 					ill->ill_max_mtu = IP_MIN_MTU;
16019 			}
16020 			for (ipif = ill->ill_ipif; ipif != NULL;
16021 			    ipif = ipif->ipif_next) {
16022 				/*
16023 				 * Don't override the mtu if the user
16024 				 * has explicitly set it.
16025 				 */
16026 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16027 					continue;
16028 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16029 				if (ipif->ipif_isv6)
16030 					ire = ipif_to_ire_v6(ipif);
16031 				else
16032 					ire = ipif_to_ire(ipif);
16033 				if (ire != NULL) {
16034 					ire->ire_max_frag = ipif->ipif_mtu;
16035 					ire_refrele(ire);
16036 				}
16037 				if (ipif->ipif_flags & IPIF_UP) {
16038 					if (ill->ill_isv6)
16039 						need_ire_walk_v6 = B_TRUE;
16040 					else
16041 						need_ire_walk_v4 = B_TRUE;
16042 				}
16043 			}
16044 			mutex_exit(&ill->ill_lock);
16045 			if (need_ire_walk_v4)
16046 				ire_walk_v4(ill_mtu_change, (char *)ill,
16047 				    ALL_ZONES, ipst);
16048 			if (need_ire_walk_v6)
16049 				ire_walk_v6(ill_mtu_change, (char *)ill,
16050 				    ALL_ZONES, ipst);
16051 
16052 			/*
16053 			 * Refresh IPMP meta-interface MTU if necessary.
16054 			 */
16055 			if (IS_UNDER_IPMP(ill))
16056 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
16057 			break;
16058 
16059 		case DL_NOTE_LINK_UP:
16060 		case DL_NOTE_LINK_DOWN: {
16061 			/*
16062 			 * We are writer. ill / phyint / ipsq assocs stable.
16063 			 * The RUNNING flag reflects the state of the link.
16064 			 */
16065 			phyint_t *phyint = ill->ill_phyint;
16066 			uint64_t new_phyint_flags;
16067 			boolean_t changed = B_FALSE;
16068 			boolean_t went_up;
16069 
16070 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16071 			mutex_enter(&phyint->phyint_lock);
16072 
16073 			new_phyint_flags = went_up ?
16074 			    phyint->phyint_flags | PHYI_RUNNING :
16075 			    phyint->phyint_flags & ~PHYI_RUNNING;
16076 
16077 			if (IS_IPMP(ill)) {
16078 				new_phyint_flags = went_up ?
16079 				    new_phyint_flags & ~PHYI_FAILED :
16080 				    new_phyint_flags | PHYI_FAILED;
16081 			}
16082 
16083 			if (new_phyint_flags != phyint->phyint_flags) {
16084 				phyint->phyint_flags = new_phyint_flags;
16085 				changed = B_TRUE;
16086 			}
16087 			mutex_exit(&phyint->phyint_lock);
16088 			/*
16089 			 * ill_restart_dad handles the DAD restart and routing
16090 			 * socket notification logic.
16091 			 */
16092 			if (changed) {
16093 				ill_restart_dad(phyint->phyint_illv4, went_up);
16094 				ill_restart_dad(phyint->phyint_illv6, went_up);
16095 			}
16096 			break;
16097 		}
16098 		case DL_NOTE_PROMISC_ON_PHYS:
16099 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16100 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16101 			mutex_enter(&ill->ill_lock);
16102 			ill->ill_promisc_on_phys = B_TRUE;
16103 			mutex_exit(&ill->ill_lock);
16104 			break;
16105 		case DL_NOTE_PROMISC_OFF_PHYS:
16106 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16107 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16108 			mutex_enter(&ill->ill_lock);
16109 			ill->ill_promisc_on_phys = B_FALSE;
16110 			mutex_exit(&ill->ill_lock);
16111 			break;
16112 		case DL_NOTE_CAPAB_RENEG:
16113 			/*
16114 			 * Something changed on the driver side.
16115 			 * It wants us to renegotiate the capabilities
16116 			 * on this ill. One possible cause is the aggregation
16117 			 * interface under us where a port got added or
16118 			 * went away.
16119 			 *
16120 			 * If the capability negotiation is already done
16121 			 * or is in progress, reset the capabilities and
16122 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16123 			 * so that when the ack comes back, we can start
16124 			 * the renegotiation process.
16125 			 *
16126 			 * Note that if ill_capab_reneg is already B_TRUE
16127 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16128 			 * the capability resetting request has been sent
16129 			 * and the renegotiation has not been started yet;
16130 			 * nothing needs to be done in this case.
16131 			 */
16132 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
16133 			ill_capability_reset(ill, B_TRUE);
16134 			ipsq_current_finish(ipsq);
16135 			break;
16136 		default:
16137 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16138 			    "type 0x%x for DL_NOTIFY_IND\n",
16139 			    notify->dl_notification));
16140 			break;
16141 		}
16142 
16143 		/*
16144 		 * As this is an asynchronous operation, we
16145 		 * should not call ill_dlpi_done
16146 		 */
16147 		break;
16148 	}
16149 	case DL_NOTIFY_ACK: {
16150 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16151 
16152 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16153 			ill->ill_note_link = 1;
16154 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16155 		break;
16156 	}
16157 	case DL_PHYS_ADDR_ACK: {
16158 		/*
16159 		 * As part of plumbing the interface via SIOCSLIFNAME,
16160 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16161 		 * whose answers we receive here.  As each answer is received,
16162 		 * we call ill_dlpi_done() to dispatch the next request as
16163 		 * we're processing the current one.  Once all answers have
16164 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16165 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16166 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16167 		 * available, but we know the ioctl is pending on ill_wq.)
16168 		 */
16169 		uint_t	paddrlen, paddroff;
16170 
16171 		paddrreq = ill->ill_phys_addr_pend;
16172 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16173 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16174 
16175 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16176 		if (paddrreq == DL_IPV6_TOKEN) {
16177 			/*
16178 			 * bcopy to low-order bits of ill_token
16179 			 *
16180 			 * XXX Temporary hack - currently, all known tokens
16181 			 * are 64 bits, so I'll cheat for the moment.
16182 			 */
16183 			bcopy(mp->b_rptr + paddroff,
16184 			    &ill->ill_token.s6_addr32[2], paddrlen);
16185 			ill->ill_token_length = paddrlen;
16186 			break;
16187 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16188 			ASSERT(ill->ill_nd_lla_mp == NULL);
16189 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16190 			mp = NULL;
16191 			break;
16192 		}
16193 
16194 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16195 		ASSERT(ill->ill_phys_addr_mp == NULL);
16196 		if (!ill->ill_ifname_pending)
16197 			break;
16198 		ill->ill_ifname_pending = 0;
16199 		if (!ioctl_aborted)
16200 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16201 		if (mp1 != NULL) {
16202 			ASSERT(connp == NULL);
16203 			q = ill->ill_wq;
16204 		}
16205 		/*
16206 		 * If any error acks received during the plumbing sequence,
16207 		 * ill_ifname_pending_err will be set. Break out and send up
16208 		 * the error to the pending ioctl.
16209 		 */
16210 		if (ill->ill_ifname_pending_err != 0) {
16211 			err = ill->ill_ifname_pending_err;
16212 			ill->ill_ifname_pending_err = 0;
16213 			break;
16214 		}
16215 
16216 		ill->ill_phys_addr_mp = mp;
16217 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16218 		mp = NULL;
16219 
16220 		/*
16221 		 * If paddrlen is zero, the DLPI provider doesn't support
16222 		 * physical addresses.  The other two tests were historical
16223 		 * workarounds for bugs in our former PPP implementation, but
16224 		 * now other things have grown dependencies on them -- e.g.,
16225 		 * the tun module specifies a dl_addr_length of zero in its
16226 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16227 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16228 		 * but only after careful testing ensures that all dependent
16229 		 * broken DLPI providers have been fixed.
16230 		 */
16231 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16232 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16233 			ill->ill_phys_addr = NULL;
16234 		} else if (paddrlen != ill->ill_phys_addr_length) {
16235 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16236 			    paddrlen, ill->ill_phys_addr_length));
16237 			err = EINVAL;
16238 			break;
16239 		}
16240 
16241 		if (ill->ill_nd_lla_mp == NULL) {
16242 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16243 				err = ENOMEM;
16244 				break;
16245 			}
16246 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16247 		}
16248 
16249 		/*
16250 		 * Set the interface token.  If the zeroth interface address
16251 		 * is unspecified, then set it to the link local address.
16252 		 */
16253 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16254 			(void) ill_setdefaulttoken(ill);
16255 
16256 		ASSERT(ill->ill_ipif->ipif_id == 0);
16257 		if (ipif != NULL &&
16258 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16259 			(void) ipif_setlinklocal(ipif);
16260 		}
16261 		break;
16262 	}
16263 	case DL_OK_ACK:
16264 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16265 		    dl_primstr((int)dloa->dl_correct_primitive),
16266 		    dloa->dl_correct_primitive));
16267 		switch (dloa->dl_correct_primitive) {
16268 		case DL_ENABMULTI_REQ:
16269 		case DL_DISABMULTI_REQ:
16270 			if (!ill->ill_isv6)
16271 				ipsq_current_finish(ipsq);
16272 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16273 			break;
16274 		case DL_PROMISCON_REQ:
16275 		case DL_PROMISCOFF_REQ:
16276 		case DL_UNBIND_REQ:
16277 		case DL_ATTACH_REQ:
16278 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16279 			break;
16280 		}
16281 		break;
16282 	default:
16283 		break;
16284 	}
16285 
16286 	freemsg(mp);
16287 	if (mp1 == NULL)
16288 		return;
16289 
16290 	/*
16291 	 * The operation must complete without EINPROGRESS since
16292 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
16293 	 * the operation will be stuck forever inside the IPSQ.
16294 	 */
16295 	ASSERT(err != EINPROGRESS);
16296 
16297 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
16298 	case 0:
16299 		ipsq_current_finish(ipsq);
16300 		break;
16301 
16302 	case SIOCSLIFNAME:
16303 	case IF_UNITSEL: {
16304 		ill_t *ill_other = ILL_OTHER(ill);
16305 
16306 		/*
16307 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
16308 		 * ill has a peer which is in an IPMP group, then place ill
16309 		 * into the same group.  One catch: although ifconfig plumbs
16310 		 * the appropriate IPMP meta-interface prior to plumbing this
16311 		 * ill, it is possible for multiple ifconfig applications to
16312 		 * race (or for another application to adjust plumbing), in
16313 		 * which case the IPMP meta-interface we need will be missing.
16314 		 * If so, kick the phyint out of the group.
16315 		 */
16316 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
16317 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
16318 			ipmp_illgrp_t	*illg;
16319 
16320 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
16321 			if (illg == NULL)
16322 				ipmp_phyint_leave_grp(ill->ill_phyint);
16323 			else
16324 				ipmp_ill_join_illgrp(ill, illg);
16325 		}
16326 
16327 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
16328 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16329 		else
16330 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16331 		break;
16332 	}
16333 	case SIOCLIFADDIF:
16334 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16335 		break;
16336 
16337 	default:
16338 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16339 		break;
16340 	}
16341 }
16342 
16343 /*
16344  * ip_rput_other is called by ip_rput to handle messages modifying the global
16345  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16346  */
16347 /* ARGSUSED */
16348 void
16349 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16350 {
16351 	ill_t		*ill = q->q_ptr;
16352 	struct iocblk	*iocp;
16353 	mblk_t		*mp1;
16354 	conn_t		*connp = NULL;
16355 
16356 	ip1dbg(("ip_rput_other "));
16357 	if (ipsq != NULL) {
16358 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16359 		ASSERT(ipsq->ipsq_xop ==
16360 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
16361 	}
16362 
16363 	switch (mp->b_datap->db_type) {
16364 	case M_ERROR:
16365 	case M_HANGUP:
16366 		/*
16367 		 * The device has a problem.  We force the ILL down.  It can
16368 		 * be brought up again manually using SIOCSIFFLAGS (via
16369 		 * ifconfig or equivalent).
16370 		 */
16371 		ASSERT(ipsq != NULL);
16372 		if (mp->b_rptr < mp->b_wptr)
16373 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16374 		if (ill->ill_error == 0)
16375 			ill->ill_error = ENXIO;
16376 		if (!ill_down_start(q, mp))
16377 			return;
16378 		ipif_all_down_tail(ipsq, q, mp, NULL);
16379 		break;
16380 	case M_IOCACK:
16381 		iocp = (struct iocblk *)mp->b_rptr;
16382 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16383 		switch (iocp->ioc_cmd) {
16384 		case SIOCSTUNPARAM:
16385 		case OSIOCSTUNPARAM:
16386 			ASSERT(ipsq != NULL);
16387 			/*
16388 			 * Finish socket ioctl passed through to tun.
16389 			 * We should have an IOCTL waiting on this.
16390 			 */
16391 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16392 			if (ill->ill_isv6) {
16393 				struct iftun_req *ta;
16394 
16395 				/*
16396 				 * if a source or destination is
16397 				 * being set, try and set the link
16398 				 * local address for the tunnel
16399 				 */
16400 				ta = (struct iftun_req *)mp->b_cont->
16401 				    b_cont->b_rptr;
16402 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16403 					ipif_set_tun_llink(ill, ta);
16404 				}
16405 
16406 			}
16407 			if (mp1 != NULL) {
16408 				/*
16409 				 * Now copy back the b_next/b_prev used by
16410 				 * mi code for the mi_copy* functions.
16411 				 * See ip_sioctl_tunparam() for the reason.
16412 				 * Also protect against missing b_cont.
16413 				 */
16414 				if (mp->b_cont != NULL) {
16415 					mp->b_cont->b_next =
16416 					    mp1->b_cont->b_next;
16417 					mp->b_cont->b_prev =
16418 					    mp1->b_cont->b_prev;
16419 				}
16420 				inet_freemsg(mp1);
16421 				ASSERT(connp != NULL);
16422 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16423 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16424 			} else {
16425 				ASSERT(connp == NULL);
16426 				putnext(q, mp);
16427 			}
16428 			break;
16429 		case SIOCGTUNPARAM:
16430 		case OSIOCGTUNPARAM:
16431 			/*
16432 			 * This is really M_IOCDATA from the tunnel driver.
16433 			 * convert back and complete the ioctl.
16434 			 * We should have an IOCTL waiting on this.
16435 			 */
16436 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16437 			if (mp1) {
16438 				/*
16439 				 * Now copy back the b_next/b_prev used by
16440 				 * mi code for the mi_copy* functions.
16441 				 * See ip_sioctl_tunparam() for the reason.
16442 				 * Also protect against missing b_cont.
16443 				 */
16444 				if (mp->b_cont != NULL) {
16445 					mp->b_cont->b_next =
16446 					    mp1->b_cont->b_next;
16447 					mp->b_cont->b_prev =
16448 					    mp1->b_cont->b_prev;
16449 				}
16450 				inet_freemsg(mp1);
16451 				if (iocp->ioc_error == 0)
16452 					mp->b_datap->db_type = M_IOCDATA;
16453 				ASSERT(connp != NULL);
16454 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16455 				    iocp->ioc_error, COPYOUT, NULL);
16456 			} else {
16457 				ASSERT(connp == NULL);
16458 				putnext(q, mp);
16459 			}
16460 			break;
16461 		default:
16462 			break;
16463 		}
16464 		break;
16465 	case M_IOCNAK:
16466 		iocp = (struct iocblk *)mp->b_rptr;
16467 
16468 		switch (iocp->ioc_cmd) {
16469 			int mode;
16470 
16471 		case DL_IOC_HDR_INFO:
16472 			/*
16473 			 * If this was the first attempt, turn off the
16474 			 * fastpath probing.
16475 			 */
16476 			mutex_enter(&ill->ill_lock);
16477 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16478 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16479 				mutex_exit(&ill->ill_lock);
16480 				ill_fastpath_nack(ill);
16481 				ip1dbg(("ip_rput: DLPI fastpath off on "
16482 				    "interface %s\n",
16483 				    ill->ill_name));
16484 			} else {
16485 				mutex_exit(&ill->ill_lock);
16486 			}
16487 			freemsg(mp);
16488 			break;
16489 			case SIOCSTUNPARAM:
16490 		case OSIOCSTUNPARAM:
16491 			ASSERT(ipsq != NULL);
16492 			/*
16493 			 * Finish socket ioctl passed through to tun
16494 			 * We should have an IOCTL waiting on this.
16495 			 */
16496 			/* FALLTHRU */
16497 		case SIOCGTUNPARAM:
16498 		case OSIOCGTUNPARAM:
16499 			/*
16500 			 * This is really M_IOCDATA from the tunnel driver.
16501 			 * convert back and complete the ioctl.
16502 			 * We should have an IOCTL waiting on this.
16503 			 */
16504 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16505 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16506 				mp1 = ill_pending_mp_get(ill, &connp,
16507 				    iocp->ioc_id);
16508 				mode = COPYOUT;
16509 				ipsq = NULL;
16510 			} else {
16511 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16512 				mode = NO_COPYOUT;
16513 			}
16514 			if (mp1 != NULL) {
16515 				/*
16516 				 * Now copy back the b_next/b_prev used by
16517 				 * mi code for the mi_copy* functions.
16518 				 * See ip_sioctl_tunparam() for the reason.
16519 				 * Also protect against missing b_cont.
16520 				 */
16521 				if (mp->b_cont != NULL) {
16522 					mp->b_cont->b_next =
16523 					    mp1->b_cont->b_next;
16524 					mp->b_cont->b_prev =
16525 					    mp1->b_cont->b_prev;
16526 				}
16527 				inet_freemsg(mp1);
16528 				if (iocp->ioc_error == 0)
16529 					iocp->ioc_error = EINVAL;
16530 				ASSERT(connp != NULL);
16531 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16532 				    iocp->ioc_error, mode, ipsq);
16533 			} else {
16534 				ASSERT(connp == NULL);
16535 				putnext(q, mp);
16536 			}
16537 			break;
16538 		default:
16539 			break;
16540 		}
16541 	default:
16542 		break;
16543 	}
16544 }
16545 
16546 /*
16547  * NOTE : This function does not ire_refrele the ire argument passed in.
16548  *
16549  * IPQoS notes
16550  * IP policy is invoked twice for a forwarded packet, once on the read side
16551  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16552  * enabled. An additional parameter, in_ill, has been added for this purpose.
16553  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16554  * because ip_mroute drops this information.
16555  *
16556  */
16557 void
16558 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16559 {
16560 	uint32_t	old_pkt_len;
16561 	uint32_t	pkt_len;
16562 	queue_t	*q;
16563 	uint32_t	sum;
16564 #define	rptr	((uchar_t *)ipha)
16565 	uint32_t	max_frag;
16566 	uint32_t	ill_index;
16567 	ill_t		*out_ill;
16568 	mib2_ipIfStatsEntry_t *mibptr;
16569 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16570 
16571 	/* Get the ill_index of the incoming ILL */
16572 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16573 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16574 
16575 	/* Initiate Read side IPPF processing */
16576 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16577 		ip_process(IPP_FWD_IN, &mp, ill_index);
16578 		if (mp == NULL) {
16579 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16580 			    "during IPPF processing\n"));
16581 			return;
16582 		}
16583 	}
16584 
16585 	/* Adjust the checksum to reflect the ttl decrement. */
16586 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16587 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16588 
16589 	if (ipha->ipha_ttl-- <= 1) {
16590 		if (ip_csum_hdr(ipha)) {
16591 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16592 			goto drop_pkt;
16593 		}
16594 		/*
16595 		 * Note: ire_stq this will be NULL for multicast
16596 		 * datagrams using the long path through arp (the IRE
16597 		 * is not an IRE_CACHE). This should not cause
16598 		 * problems since we don't generate ICMP errors for
16599 		 * multicast packets.
16600 		 */
16601 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16602 		q = ire->ire_stq;
16603 		if (q != NULL) {
16604 			/* Sent by forwarding path, and router is global zone */
16605 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16606 			    GLOBAL_ZONEID, ipst);
16607 		} else
16608 			freemsg(mp);
16609 		return;
16610 	}
16611 
16612 	/*
16613 	 * Don't forward if the interface is down
16614 	 */
16615 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16616 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16617 		ip2dbg(("ip_rput_forward:interface is down\n"));
16618 		goto drop_pkt;
16619 	}
16620 
16621 	/* Get the ill_index of the outgoing ILL */
16622 	out_ill = ire_to_ill(ire);
16623 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16624 
16625 	DTRACE_PROBE4(ip4__forwarding__start,
16626 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16627 
16628 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16629 	    ipst->ips_ipv4firewall_forwarding,
16630 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16631 
16632 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16633 
16634 	if (mp == NULL)
16635 		return;
16636 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16637 
16638 	if (is_system_labeled()) {
16639 		mblk_t *mp1;
16640 
16641 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16642 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16643 			goto drop_pkt;
16644 		}
16645 		/* Size may have changed */
16646 		mp = mp1;
16647 		ipha = (ipha_t *)mp->b_rptr;
16648 		pkt_len = ntohs(ipha->ipha_length);
16649 	}
16650 
16651 	/* Check if there are options to update */
16652 	if (!IS_SIMPLE_IPH(ipha)) {
16653 		if (ip_csum_hdr(ipha)) {
16654 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16655 			goto drop_pkt;
16656 		}
16657 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16658 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16659 			return;
16660 		}
16661 
16662 		ipha->ipha_hdr_checksum = 0;
16663 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16664 	}
16665 	max_frag = ire->ire_max_frag;
16666 	if (pkt_len > max_frag) {
16667 		/*
16668 		 * It needs fragging on its way out.  We haven't
16669 		 * verified the header checksum yet.  Since we
16670 		 * are going to put a surely good checksum in the
16671 		 * outgoing header, we have to make sure that it
16672 		 * was good coming in.
16673 		 */
16674 		if (ip_csum_hdr(ipha)) {
16675 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16676 			goto drop_pkt;
16677 		}
16678 		/* Initiate Write side IPPF processing */
16679 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16680 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16681 			if (mp == NULL) {
16682 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16683 				    " during IPPF processing\n"));
16684 				return;
16685 			}
16686 		}
16687 		/*
16688 		 * Handle labeled packet resizing.
16689 		 *
16690 		 * If we have added a label, inform ip_wput_frag() of its
16691 		 * effect on the MTU for ICMP messages.
16692 		 */
16693 		if (pkt_len > old_pkt_len) {
16694 			uint32_t secopt_size;
16695 
16696 			secopt_size = pkt_len - old_pkt_len;
16697 			if (secopt_size < max_frag)
16698 				max_frag -= secopt_size;
16699 		}
16700 
16701 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0,
16702 		    GLOBAL_ZONEID, ipst, NULL);
16703 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16704 		return;
16705 	}
16706 
16707 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16708 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16709 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16710 	    ipst->ips_ipv4firewall_physical_out,
16711 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16712 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16713 	if (mp == NULL)
16714 		return;
16715 
16716 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16717 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16718 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE, NULL);
16719 	/* ip_xmit_v4 always consumes the packet */
16720 	return;
16721 
16722 drop_pkt:;
16723 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16724 	freemsg(mp);
16725 #undef	rptr
16726 }
16727 
16728 void
16729 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16730 {
16731 	ire_t	*ire;
16732 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16733 
16734 	ASSERT(!ipif->ipif_isv6);
16735 	/*
16736 	 * Find an IRE which matches the destination and the outgoing
16737 	 * queue in the cache table. All we need is an IRE_CACHE which
16738 	 * is pointing at ipif->ipif_ill.
16739 	 */
16740 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16741 		dst = ipif->ipif_pp_dst_addr;
16742 
16743 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16744 	    MATCH_IRE_ILL | MATCH_IRE_SECATTR, ipst);
16745 	if (ire == NULL) {
16746 		/*
16747 		 * Mark this packet to make it be delivered to
16748 		 * ip_rput_forward after the new ire has been
16749 		 * created.
16750 		 */
16751 		mp->b_prev = NULL;
16752 		mp->b_next = mp;
16753 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16754 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16755 	} else {
16756 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16757 		IRE_REFRELE(ire);
16758 	}
16759 }
16760 
16761 /* Update any source route, record route or timestamp options */
16762 static int
16763 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16764 {
16765 	ipoptp_t	opts;
16766 	uchar_t		*opt;
16767 	uint8_t		optval;
16768 	uint8_t		optlen;
16769 	ipaddr_t	dst;
16770 	uint32_t	ts;
16771 	ire_t		*dst_ire = NULL;
16772 	ire_t		*tmp_ire = NULL;
16773 	timestruc_t	now;
16774 
16775 	ip2dbg(("ip_rput_forward_options\n"));
16776 	dst = ipha->ipha_dst;
16777 	for (optval = ipoptp_first(&opts, ipha);
16778 	    optval != IPOPT_EOL;
16779 	    optval = ipoptp_next(&opts)) {
16780 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16781 		opt = opts.ipoptp_cur;
16782 		optlen = opts.ipoptp_len;
16783 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16784 		    optval, opts.ipoptp_len));
16785 		switch (optval) {
16786 			uint32_t off;
16787 		case IPOPT_SSRR:
16788 		case IPOPT_LSRR:
16789 			/* Check if adminstratively disabled */
16790 			if (!ipst->ips_ip_forward_src_routed) {
16791 				if (ire->ire_stq != NULL) {
16792 					/*
16793 					 * Sent by forwarding path, and router
16794 					 * is global zone
16795 					 */
16796 					icmp_unreachable(ire->ire_stq, mp,
16797 					    ICMP_SOURCE_ROUTE_FAILED,
16798 					    GLOBAL_ZONEID, ipst);
16799 				} else {
16800 					ip0dbg(("ip_rput_forward_options: "
16801 					    "unable to send unreach\n"));
16802 					freemsg(mp);
16803 				}
16804 				return (-1);
16805 			}
16806 
16807 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16808 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16809 			if (dst_ire == NULL) {
16810 				/*
16811 				 * Must be partial since ip_rput_options
16812 				 * checked for strict.
16813 				 */
16814 				break;
16815 			}
16816 			off = opt[IPOPT_OFFSET];
16817 			off--;
16818 		redo_srr:
16819 			if (optlen < IP_ADDR_LEN ||
16820 			    off > optlen - IP_ADDR_LEN) {
16821 				/* End of source route */
16822 				ip1dbg((
16823 				    "ip_rput_forward_options: end of SR\n"));
16824 				ire_refrele(dst_ire);
16825 				break;
16826 			}
16827 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16828 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16829 			    IP_ADDR_LEN);
16830 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16831 			    ntohl(dst)));
16832 
16833 			/*
16834 			 * Check if our address is present more than
16835 			 * once as consecutive hops in source route.
16836 			 */
16837 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16838 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16839 			if (tmp_ire != NULL) {
16840 				ire_refrele(tmp_ire);
16841 				off += IP_ADDR_LEN;
16842 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16843 				goto redo_srr;
16844 			}
16845 			ipha->ipha_dst = dst;
16846 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16847 			ire_refrele(dst_ire);
16848 			break;
16849 		case IPOPT_RR:
16850 			off = opt[IPOPT_OFFSET];
16851 			off--;
16852 			if (optlen < IP_ADDR_LEN ||
16853 			    off > optlen - IP_ADDR_LEN) {
16854 				/* No more room - ignore */
16855 				ip1dbg((
16856 				    "ip_rput_forward_options: end of RR\n"));
16857 				break;
16858 			}
16859 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16860 			    IP_ADDR_LEN);
16861 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16862 			break;
16863 		case IPOPT_TS:
16864 			/* Insert timestamp if there is room */
16865 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16866 			case IPOPT_TS_TSONLY:
16867 				off = IPOPT_TS_TIMELEN;
16868 				break;
16869 			case IPOPT_TS_PRESPEC:
16870 			case IPOPT_TS_PRESPEC_RFC791:
16871 				/* Verify that the address matched */
16872 				off = opt[IPOPT_OFFSET] - 1;
16873 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16874 				dst_ire = ire_ctable_lookup(dst, 0,
16875 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16876 				    MATCH_IRE_TYPE, ipst);
16877 				if (dst_ire == NULL) {
16878 					/* Not for us */
16879 					break;
16880 				}
16881 				ire_refrele(dst_ire);
16882 				/* FALLTHRU */
16883 			case IPOPT_TS_TSANDADDR:
16884 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16885 				break;
16886 			default:
16887 				/*
16888 				 * ip_*put_options should have already
16889 				 * dropped this packet.
16890 				 */
16891 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16892 				    "unknown IT - bug in ip_rput_options?\n");
16893 				return (0);	/* Keep "lint" happy */
16894 			}
16895 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16896 				/* Increase overflow counter */
16897 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16898 				opt[IPOPT_POS_OV_FLG] =
16899 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16900 				    (off << 4));
16901 				break;
16902 			}
16903 			off = opt[IPOPT_OFFSET] - 1;
16904 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16905 			case IPOPT_TS_PRESPEC:
16906 			case IPOPT_TS_PRESPEC_RFC791:
16907 			case IPOPT_TS_TSANDADDR:
16908 				bcopy(&ire->ire_src_addr,
16909 				    (char *)opt + off, IP_ADDR_LEN);
16910 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16911 				/* FALLTHRU */
16912 			case IPOPT_TS_TSONLY:
16913 				off = opt[IPOPT_OFFSET] - 1;
16914 				/* Compute # of milliseconds since midnight */
16915 				gethrestime(&now);
16916 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16917 				    now.tv_nsec / (NANOSEC / MILLISEC);
16918 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16919 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16920 				break;
16921 			}
16922 			break;
16923 		}
16924 	}
16925 	return (0);
16926 }
16927 
16928 /*
16929  * This is called after processing at least one of AH/ESP headers.
16930  *
16931  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16932  * the actual, physical interface on which the packet was received,
16933  * but, when ip_strict_dst_multihoming is set to 1, could be the
16934  * interface which had the ipha_dst configured when the packet went
16935  * through ip_rput. The ill_index corresponding to the recv_ill
16936  * is saved in ipsec_in_rill_index
16937  *
16938  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16939  * cannot assume "ire" points to valid data for any IPv6 cases.
16940  */
16941 void
16942 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16943 {
16944 	mblk_t *mp;
16945 	ipaddr_t dst;
16946 	in6_addr_t *v6dstp;
16947 	ipha_t *ipha;
16948 	ip6_t *ip6h;
16949 	ipsec_in_t *ii;
16950 	boolean_t ill_need_rele = B_FALSE;
16951 	boolean_t rill_need_rele = B_FALSE;
16952 	boolean_t ire_need_rele = B_FALSE;
16953 	netstack_t	*ns;
16954 	ip_stack_t	*ipst;
16955 
16956 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16957 	ASSERT(ii->ipsec_in_ill_index != 0);
16958 	ns = ii->ipsec_in_ns;
16959 	ASSERT(ii->ipsec_in_ns != NULL);
16960 	ipst = ns->netstack_ip;
16961 
16962 	mp = ipsec_mp->b_cont;
16963 	ASSERT(mp != NULL);
16964 
16965 	if (ill == NULL) {
16966 		ASSERT(recv_ill == NULL);
16967 		/*
16968 		 * We need to get the original queue on which ip_rput_local
16969 		 * or ip_rput_data_v6 was called.
16970 		 */
16971 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16972 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16973 		ill_need_rele = B_TRUE;
16974 
16975 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16976 			recv_ill = ill_lookup_on_ifindex(
16977 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16978 			    NULL, NULL, NULL, NULL, ipst);
16979 			rill_need_rele = B_TRUE;
16980 		} else {
16981 			recv_ill = ill;
16982 		}
16983 
16984 		if ((ill == NULL) || (recv_ill == NULL)) {
16985 			ip0dbg(("ip_fanout_proto_again: interface "
16986 			    "disappeared\n"));
16987 			if (ill != NULL)
16988 				ill_refrele(ill);
16989 			if (recv_ill != NULL)
16990 				ill_refrele(recv_ill);
16991 			freemsg(ipsec_mp);
16992 			return;
16993 		}
16994 	}
16995 
16996 	ASSERT(ill != NULL && recv_ill != NULL);
16997 
16998 	if (mp->b_datap->db_type == M_CTL) {
16999 		/*
17000 		 * AH/ESP is returning the ICMP message after
17001 		 * removing their headers. Fanout again till
17002 		 * it gets to the right protocol.
17003 		 */
17004 		if (ii->ipsec_in_v4) {
17005 			icmph_t *icmph;
17006 			int iph_hdr_length;
17007 			int hdr_length;
17008 
17009 			ipha = (ipha_t *)mp->b_rptr;
17010 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17011 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17012 			ipha = (ipha_t *)&icmph[1];
17013 			hdr_length = IPH_HDR_LENGTH(ipha);
17014 			/*
17015 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17016 			 * Reset the type to M_DATA.
17017 			 */
17018 			mp->b_datap->db_type = M_DATA;
17019 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17020 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17021 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17022 		} else {
17023 			icmp6_t *icmp6;
17024 			int hdr_length;
17025 
17026 			ip6h = (ip6_t *)mp->b_rptr;
17027 			/* Don't call hdr_length_v6() unless you have to. */
17028 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17029 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17030 			else
17031 				hdr_length = IPV6_HDR_LEN;
17032 
17033 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17034 			/*
17035 			 * icmp_inbound_error_fanout_v6 may need to do
17036 			 * pullupmsg.  Reset the type to M_DATA.
17037 			 */
17038 			mp->b_datap->db_type = M_DATA;
17039 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17040 			    ip6h, icmp6, ill, recv_ill, B_TRUE,
17041 			    ii->ipsec_in_zoneid);
17042 		}
17043 		if (ill_need_rele)
17044 			ill_refrele(ill);
17045 		if (rill_need_rele)
17046 			ill_refrele(recv_ill);
17047 		return;
17048 	}
17049 
17050 	if (ii->ipsec_in_v4) {
17051 		ipha = (ipha_t *)mp->b_rptr;
17052 		dst = ipha->ipha_dst;
17053 		if (CLASSD(dst)) {
17054 			/*
17055 			 * Multicast has to be delivered to all streams.
17056 			 */
17057 			dst = INADDR_BROADCAST;
17058 		}
17059 
17060 		if (ire == NULL) {
17061 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17062 			    MBLK_GETLABEL(mp), ipst);
17063 			if (ire == NULL) {
17064 				if (ill_need_rele)
17065 					ill_refrele(ill);
17066 				if (rill_need_rele)
17067 					ill_refrele(recv_ill);
17068 				ip1dbg(("ip_fanout_proto_again: "
17069 				    "IRE not found"));
17070 				freemsg(ipsec_mp);
17071 				return;
17072 			}
17073 			ire_need_rele = B_TRUE;
17074 		}
17075 
17076 		switch (ipha->ipha_protocol) {
17077 		case IPPROTO_UDP:
17078 			ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17079 			    recv_ill);
17080 			if (ire_need_rele)
17081 				ire_refrele(ire);
17082 			break;
17083 		case IPPROTO_TCP:
17084 			if (!ire_need_rele)
17085 				IRE_REFHOLD(ire);
17086 			mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17087 			    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17088 			IRE_REFRELE(ire);
17089 			if (mp != NULL) {
17090 				SQUEUE_ENTER(GET_SQUEUE(mp), mp,
17091 				    mp, 1, SQ_PROCESS,
17092 				    SQTAG_IP_PROTO_AGAIN);
17093 			}
17094 			break;
17095 		case IPPROTO_SCTP:
17096 			if (!ire_need_rele)
17097 				IRE_REFHOLD(ire);
17098 			ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17099 			    ipsec_mp, 0, ill->ill_rq, dst);
17100 			break;
17101 		default:
17102 			ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17103 			    recv_ill, 0);
17104 			if (ire_need_rele)
17105 				ire_refrele(ire);
17106 			break;
17107 		}
17108 	} else {
17109 		uint32_t rput_flags = 0;
17110 
17111 		ip6h = (ip6_t *)mp->b_rptr;
17112 		v6dstp = &ip6h->ip6_dst;
17113 		/*
17114 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17115 		 * address.
17116 		 *
17117 		 * Currently, we don't store that state in the IPSEC_IN
17118 		 * message, and we may need to.
17119 		 */
17120 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17121 		    IP6_IN_LLMCAST : 0);
17122 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17123 		    NULL, NULL);
17124 	}
17125 	if (ill_need_rele)
17126 		ill_refrele(ill);
17127 	if (rill_need_rele)
17128 		ill_refrele(recv_ill);
17129 }
17130 
17131 /*
17132  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17133  * returns 'true' if there are still fragments left on the queue, in
17134  * which case we restart the timer.
17135  */
17136 void
17137 ill_frag_timer(void *arg)
17138 {
17139 	ill_t	*ill = (ill_t *)arg;
17140 	boolean_t frag_pending;
17141 	ip_stack_t	*ipst = ill->ill_ipst;
17142 
17143 	mutex_enter(&ill->ill_lock);
17144 	ASSERT(!ill->ill_fragtimer_executing);
17145 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17146 		ill->ill_frag_timer_id = 0;
17147 		mutex_exit(&ill->ill_lock);
17148 		return;
17149 	}
17150 	ill->ill_fragtimer_executing = 1;
17151 	mutex_exit(&ill->ill_lock);
17152 
17153 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17154 
17155 	/*
17156 	 * Restart the timer, if we have fragments pending or if someone
17157 	 * wanted us to be scheduled again.
17158 	 */
17159 	mutex_enter(&ill->ill_lock);
17160 	ill->ill_fragtimer_executing = 0;
17161 	ill->ill_frag_timer_id = 0;
17162 	if (frag_pending || ill->ill_fragtimer_needrestart)
17163 		ill_frag_timer_start(ill);
17164 	mutex_exit(&ill->ill_lock);
17165 }
17166 
17167 void
17168 ill_frag_timer_start(ill_t *ill)
17169 {
17170 	ip_stack_t	*ipst = ill->ill_ipst;
17171 
17172 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17173 
17174 	/* If the ill is closing or opening don't proceed */
17175 	if (ill->ill_state_flags & ILL_CONDEMNED)
17176 		return;
17177 
17178 	if (ill->ill_fragtimer_executing) {
17179 		/*
17180 		 * ill_frag_timer is currently executing. Just record the
17181 		 * the fact that we want the timer to be restarted.
17182 		 * ill_frag_timer will post a timeout before it returns,
17183 		 * ensuring it will be called again.
17184 		 */
17185 		ill->ill_fragtimer_needrestart = 1;
17186 		return;
17187 	}
17188 
17189 	if (ill->ill_frag_timer_id == 0) {
17190 		/*
17191 		 * The timer is neither running nor is the timeout handler
17192 		 * executing. Post a timeout so that ill_frag_timer will be
17193 		 * called
17194 		 */
17195 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17196 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17197 		ill->ill_fragtimer_needrestart = 0;
17198 	}
17199 }
17200 
17201 /*
17202  * This routine is needed for loopback when forwarding multicasts.
17203  *
17204  * IPQoS Notes:
17205  * IPPF processing is done in fanout routines.
17206  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17207  * processing for IPsec packets is done when it comes back in clear.
17208  * NOTE : The callers of this function need to do the ire_refrele for the
17209  *	  ire that is being passed in.
17210  */
17211 void
17212 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17213     ill_t *recv_ill, uint32_t esp_udp_ports)
17214 {
17215 	boolean_t esp_in_udp_packet = (esp_udp_ports != 0);
17216 	ill_t	*ill = (ill_t *)q->q_ptr;
17217 	uint32_t	sum;
17218 	uint32_t	u1;
17219 	uint32_t	u2;
17220 	int		hdr_length;
17221 	boolean_t	mctl_present;
17222 	mblk_t		*first_mp = mp;
17223 	mblk_t		*hada_mp = NULL;
17224 	ipha_t		*inner_ipha;
17225 	ip_stack_t	*ipst;
17226 
17227 	ASSERT(recv_ill != NULL);
17228 	ipst = recv_ill->ill_ipst;
17229 
17230 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17231 	    "ip_rput_locl_start: q %p", q);
17232 
17233 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17234 	ASSERT(ill != NULL);
17235 
17236 #define	rptr	((uchar_t *)ipha)
17237 #define	iphs	((uint16_t *)ipha)
17238 
17239 	/*
17240 	 * no UDP or TCP packet should come here anymore.
17241 	 */
17242 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17243 	    ipha->ipha_protocol != IPPROTO_UDP);
17244 
17245 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17246 	if (mctl_present &&
17247 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17248 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17249 
17250 		/*
17251 		 * It's an IPsec accelerated packet.
17252 		 * Keep a pointer to the data attributes around until
17253 		 * we allocate the ipsec_info_t.
17254 		 */
17255 		IPSECHW_DEBUG(IPSECHW_PKT,
17256 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17257 		hada_mp = first_mp;
17258 		hada_mp->b_cont = NULL;
17259 		/*
17260 		 * Since it is accelerated, it comes directly from
17261 		 * the ill and the data attributes is followed by
17262 		 * the packet data.
17263 		 */
17264 		ASSERT(mp->b_datap->db_type != M_CTL);
17265 		first_mp = mp;
17266 		mctl_present = B_FALSE;
17267 	}
17268 
17269 	/*
17270 	 * IF M_CTL is not present, then ipsec_in_is_secure
17271 	 * should return B_TRUE. There is a case where loopback
17272 	 * packets has an M_CTL in the front with all the
17273 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17274 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17275 	 * packets never comes here, it is safe to ASSERT the
17276 	 * following.
17277 	 */
17278 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17279 
17280 	/*
17281 	 * Also, we should never have an mctl_present if this is an
17282 	 * ESP-in-UDP packet.
17283 	 */
17284 	ASSERT(!mctl_present || !esp_in_udp_packet);
17285 
17286 	/* u1 is # words of IP options */
17287 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17288 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17289 
17290 	/*
17291 	 * Don't verify header checksum if we just removed UDP header or
17292 	 * packet is coming back from AH/ESP.
17293 	 */
17294 	if (!esp_in_udp_packet && !mctl_present) {
17295 		if (u1) {
17296 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17297 				if (hada_mp != NULL)
17298 					freemsg(hada_mp);
17299 				return;
17300 			}
17301 		} else {
17302 			/* Check the IP header checksum.  */
17303 #define	uph	((uint16_t *)ipha)
17304 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17305 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17306 #undef  uph
17307 			/* finish doing IP checksum */
17308 			sum = (sum & 0xFFFF) + (sum >> 16);
17309 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17310 			if (sum && sum != 0xFFFF) {
17311 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17312 				goto drop_pkt;
17313 			}
17314 		}
17315 	}
17316 
17317 	/*
17318 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17319 	 * might be called more than once for secure packets, count only
17320 	 * the first time.
17321 	 */
17322 	if (!mctl_present) {
17323 		UPDATE_IB_PKT_COUNT(ire);
17324 		ire->ire_last_used_time = lbolt;
17325 	}
17326 
17327 	/* Check for fragmentation offset. */
17328 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17329 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17330 	if (u1) {
17331 		/*
17332 		 * We re-assemble fragments before we do the AH/ESP
17333 		 * processing. Thus, M_CTL should not be present
17334 		 * while we are re-assembling.
17335 		 */
17336 		ASSERT(!mctl_present);
17337 		ASSERT(first_mp == mp);
17338 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
17339 			return;
17340 
17341 		/*
17342 		 * Make sure that first_mp points back to mp as
17343 		 * the mp we came in with could have changed in
17344 		 * ip_rput_fragment().
17345 		 */
17346 		ipha = (ipha_t *)mp->b_rptr;
17347 		first_mp = mp;
17348 	}
17349 
17350 	/*
17351 	 * Clear hardware checksumming flag as it is currently only
17352 	 * used by TCP and UDP.
17353 	 */
17354 	DB_CKSUMFLAGS(mp) = 0;
17355 
17356 	/* Now we have a complete datagram, destined for this machine. */
17357 	u1 = IPH_HDR_LENGTH(ipha);
17358 	switch (ipha->ipha_protocol) {
17359 	case IPPROTO_ICMP: {
17360 		ire_t		*ire_zone;
17361 		ilm_t		*ilm;
17362 		mblk_t		*mp1;
17363 		zoneid_t	last_zoneid;
17364 		ilm_walker_t	ilw;
17365 
17366 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17367 			ASSERT(ire->ire_type == IRE_BROADCAST);
17368 
17369 			/*
17370 			 * In the multicast case, applications may have joined
17371 			 * the group from different zones, so we need to deliver
17372 			 * the packet to each of them. Loop through the
17373 			 * multicast memberships structures (ilm) on the receive
17374 			 * ill and send a copy of the packet up each matching
17375 			 * one. However, we don't do this for multicasts sent on
17376 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17377 			 * they must stay in the sender's zone.
17378 			 *
17379 			 * ilm_add_v6() ensures that ilms in the same zone are
17380 			 * contiguous in the ill_ilm list. We use this property
17381 			 * to avoid sending duplicates needed when two
17382 			 * applications in the same zone join the same group on
17383 			 * different logical interfaces: we ignore the ilm if
17384 			 * its zoneid is the same as the last matching one.
17385 			 * In addition, the sending of the packet for
17386 			 * ire_zoneid is delayed until all of the other ilms
17387 			 * have been exhausted.
17388 			 */
17389 			last_zoneid = -1;
17390 			ilm = ilm_walker_start(&ilw, recv_ill);
17391 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
17392 				if (ipha->ipha_dst != ilm->ilm_addr ||
17393 				    ilm->ilm_zoneid == last_zoneid ||
17394 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17395 				    ilm->ilm_zoneid == ALL_ZONES ||
17396 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17397 					continue;
17398 				mp1 = ip_copymsg(first_mp);
17399 				if (mp1 == NULL)
17400 					continue;
17401 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
17402 				    0, sum, mctl_present, B_TRUE,
17403 				    recv_ill, ilm->ilm_zoneid);
17404 				last_zoneid = ilm->ilm_zoneid;
17405 			}
17406 			ilm_walker_finish(&ilw);
17407 		} else if (ire->ire_type == IRE_BROADCAST) {
17408 			/*
17409 			 * In the broadcast case, there may be many zones
17410 			 * which need a copy of the packet delivered to them.
17411 			 * There is one IRE_BROADCAST per broadcast address
17412 			 * and per zone; we walk those using a helper function.
17413 			 * In addition, the sending of the packet for ire is
17414 			 * delayed until all of the other ires have been
17415 			 * processed.
17416 			 */
17417 			IRB_REFHOLD(ire->ire_bucket);
17418 			ire_zone = NULL;
17419 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17420 			    ire)) != NULL) {
17421 				mp1 = ip_copymsg(first_mp);
17422 				if (mp1 == NULL)
17423 					continue;
17424 
17425 				UPDATE_IB_PKT_COUNT(ire_zone);
17426 				ire_zone->ire_last_used_time = lbolt;
17427 				icmp_inbound(q, mp1, B_TRUE, ill,
17428 				    0, sum, mctl_present, B_TRUE,
17429 				    recv_ill, ire_zone->ire_zoneid);
17430 			}
17431 			IRB_REFRELE(ire->ire_bucket);
17432 		}
17433 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17434 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17435 		    ire->ire_zoneid);
17436 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17437 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17438 		return;
17439 	}
17440 	case IPPROTO_IGMP:
17441 		/*
17442 		 * If we are not willing to accept IGMP packets in clear,
17443 		 * then check with global policy.
17444 		 */
17445 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17446 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17447 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17448 			if (first_mp == NULL)
17449 				return;
17450 		}
17451 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17452 			freemsg(first_mp);
17453 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17454 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17455 			return;
17456 		}
17457 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17458 			/* Bad packet - discarded by igmp_input */
17459 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17460 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17461 			if (mctl_present)
17462 				freeb(first_mp);
17463 			return;
17464 		}
17465 		/*
17466 		 * igmp_input() may have returned the pulled up message.
17467 		 * So first_mp and ipha need to be reinitialized.
17468 		 */
17469 		ipha = (ipha_t *)mp->b_rptr;
17470 		if (mctl_present)
17471 			first_mp->b_cont = mp;
17472 		else
17473 			first_mp = mp;
17474 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17475 		    connf_head != NULL) {
17476 			/* No user-level listener for IGMP packets */
17477 			goto drop_pkt;
17478 		}
17479 		/* deliver to local raw users */
17480 		break;
17481 	case IPPROTO_PIM:
17482 		/*
17483 		 * If we are not willing to accept PIM packets in clear,
17484 		 * then check with global policy.
17485 		 */
17486 		if (ipst->ips_pim_accept_clear_messages == 0) {
17487 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17488 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17489 			if (first_mp == NULL)
17490 				return;
17491 		}
17492 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17493 			freemsg(first_mp);
17494 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17495 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17496 			return;
17497 		}
17498 		if (pim_input(q, mp, ill) != 0) {
17499 			/* Bad packet - discarded by pim_input */
17500 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17501 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17502 			if (mctl_present)
17503 				freeb(first_mp);
17504 			return;
17505 		}
17506 
17507 		/*
17508 		 * pim_input() may have pulled up the message so ipha needs to
17509 		 * be reinitialized.
17510 		 */
17511 		ipha = (ipha_t *)mp->b_rptr;
17512 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17513 		    connf_head != NULL) {
17514 			/* No user-level listener for PIM packets */
17515 			goto drop_pkt;
17516 		}
17517 		/* deliver to local raw users */
17518 		break;
17519 	case IPPROTO_ENCAP:
17520 		/*
17521 		 * Handle self-encapsulated packets (IP-in-IP where
17522 		 * the inner addresses == the outer addresses).
17523 		 */
17524 		hdr_length = IPH_HDR_LENGTH(ipha);
17525 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17526 		    mp->b_wptr) {
17527 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17528 			    sizeof (ipha_t) - mp->b_rptr)) {
17529 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17530 				freemsg(first_mp);
17531 				return;
17532 			}
17533 			ipha = (ipha_t *)mp->b_rptr;
17534 		}
17535 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17536 		/*
17537 		 * Check the sanity of the inner IP header.
17538 		 */
17539 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17540 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17541 			freemsg(first_mp);
17542 			return;
17543 		}
17544 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17545 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17546 			freemsg(first_mp);
17547 			return;
17548 		}
17549 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17550 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17551 			ipsec_in_t *ii;
17552 
17553 			/*
17554 			 * Self-encapsulated tunnel packet. Remove
17555 			 * the outer IP header and fanout again.
17556 			 * We also need to make sure that the inner
17557 			 * header is pulled up until options.
17558 			 */
17559 			mp->b_rptr = (uchar_t *)inner_ipha;
17560 			ipha = inner_ipha;
17561 			hdr_length = IPH_HDR_LENGTH(ipha);
17562 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17563 				if (!pullupmsg(mp, (uchar_t *)ipha +
17564 				    + hdr_length - mp->b_rptr)) {
17565 					freemsg(first_mp);
17566 					return;
17567 				}
17568 				ipha = (ipha_t *)mp->b_rptr;
17569 			}
17570 			if (hdr_length > sizeof (ipha_t)) {
17571 				/* We got options on the inner packet. */
17572 				ipaddr_t dst = ipha->ipha_dst;
17573 
17574 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17575 				    -1) {
17576 					/* Bad options! */
17577 					return;
17578 				}
17579 				if (dst != ipha->ipha_dst) {
17580 					/*
17581 					 * Someone put a source-route in
17582 					 * the inside header of a self-
17583 					 * encapsulated packet.  Drop it
17584 					 * with extreme prejudice and let
17585 					 * the sender know.
17586 					 */
17587 					icmp_unreachable(q, first_mp,
17588 					    ICMP_SOURCE_ROUTE_FAILED,
17589 					    recv_ill->ill_zoneid, ipst);
17590 					return;
17591 				}
17592 			}
17593 			if (!mctl_present) {
17594 				ASSERT(first_mp == mp);
17595 				/*
17596 				 * This means that somebody is sending
17597 				 * Self-encapsualted packets without AH/ESP.
17598 				 * If AH/ESP was present, we would have already
17599 				 * allocated the first_mp.
17600 				 *
17601 				 * Send this packet to find a tunnel endpoint.
17602 				 * if I can't find one, an ICMP
17603 				 * PROTOCOL_UNREACHABLE will get sent.
17604 				 */
17605 				goto fanout;
17606 			}
17607 			/*
17608 			 * We generally store the ill_index if we need to
17609 			 * do IPsec processing as we lose the ill queue when
17610 			 * we come back. But in this case, we never should
17611 			 * have to store the ill_index here as it should have
17612 			 * been stored previously when we processed the
17613 			 * AH/ESP header in this routine or for non-ipsec
17614 			 * cases, we still have the queue. But for some bad
17615 			 * packets from the wire, we can get to IPsec after
17616 			 * this and we better store the index for that case.
17617 			 */
17618 			ill = (ill_t *)q->q_ptr;
17619 			ii = (ipsec_in_t *)first_mp->b_rptr;
17620 			ii->ipsec_in_ill_index =
17621 			    ill->ill_phyint->phyint_ifindex;
17622 			ii->ipsec_in_rill_index =
17623 			    recv_ill->ill_phyint->phyint_ifindex;
17624 			if (ii->ipsec_in_decaps) {
17625 				/*
17626 				 * This packet is self-encapsulated multiple
17627 				 * times. We don't want to recurse infinitely.
17628 				 * To keep it simple, drop the packet.
17629 				 */
17630 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17631 				freemsg(first_mp);
17632 				return;
17633 			}
17634 			ii->ipsec_in_decaps = B_TRUE;
17635 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17636 			    ire);
17637 			return;
17638 		}
17639 		break;
17640 	case IPPROTO_AH:
17641 	case IPPROTO_ESP: {
17642 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17643 
17644 		/*
17645 		 * Fast path for AH/ESP. If this is the first time
17646 		 * we are sending a datagram to AH/ESP, allocate
17647 		 * a IPSEC_IN message and prepend it. Otherwise,
17648 		 * just fanout.
17649 		 */
17650 
17651 		int ipsec_rc;
17652 		ipsec_in_t *ii;
17653 		netstack_t *ns = ipst->ips_netstack;
17654 
17655 		IP_STAT(ipst, ipsec_proto_ahesp);
17656 		if (!mctl_present) {
17657 			ASSERT(first_mp == mp);
17658 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17659 			if (first_mp == NULL) {
17660 				ip1dbg(("ip_proto_input: IPSEC_IN "
17661 				    "allocation failure.\n"));
17662 				freemsg(hada_mp); /* okay ifnull */
17663 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17664 				freemsg(mp);
17665 				return;
17666 			}
17667 			/*
17668 			 * Store the ill_index so that when we come back
17669 			 * from IPsec we ride on the same queue.
17670 			 */
17671 			ill = (ill_t *)q->q_ptr;
17672 			ii = (ipsec_in_t *)first_mp->b_rptr;
17673 			ii->ipsec_in_ill_index =
17674 			    ill->ill_phyint->phyint_ifindex;
17675 			ii->ipsec_in_rill_index =
17676 			    recv_ill->ill_phyint->phyint_ifindex;
17677 			first_mp->b_cont = mp;
17678 			/*
17679 			 * Cache hardware acceleration info.
17680 			 */
17681 			if (hada_mp != NULL) {
17682 				IPSECHW_DEBUG(IPSECHW_PKT,
17683 				    ("ip_rput_local: caching data attr.\n"));
17684 				ii->ipsec_in_accelerated = B_TRUE;
17685 				ii->ipsec_in_da = hada_mp;
17686 				hada_mp = NULL;
17687 			}
17688 		} else {
17689 			ii = (ipsec_in_t *)first_mp->b_rptr;
17690 		}
17691 
17692 		ii->ipsec_in_esp_udp_ports = esp_udp_ports;
17693 
17694 		if (!ipsec_loaded(ipss)) {
17695 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17696 			    ire->ire_zoneid, ipst);
17697 			return;
17698 		}
17699 
17700 		ns = ipst->ips_netstack;
17701 		/* select inbound SA and have IPsec process the pkt */
17702 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17703 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17704 			boolean_t esp_in_udp_sa;
17705 			if (esph == NULL)
17706 				return;
17707 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17708 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17709 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17710 			    IPSA_F_NATT) != 0);
17711 			/*
17712 			 * The following is a fancy, but quick, way of saying:
17713 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17714 			 *    OR
17715 			 * ESP SA and ESP-in-UDP packet --> drop
17716 			 */
17717 			if (esp_in_udp_sa != esp_in_udp_packet) {
17718 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17719 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17720 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17721 				    &ns->netstack_ipsec->ipsec_dropper);
17722 				return;
17723 			}
17724 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17725 			    first_mp, esph);
17726 		} else {
17727 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17728 			if (ah == NULL)
17729 				return;
17730 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17731 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17732 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17733 			    first_mp, ah);
17734 		}
17735 
17736 		switch (ipsec_rc) {
17737 		case IPSEC_STATUS_SUCCESS:
17738 			break;
17739 		case IPSEC_STATUS_FAILED:
17740 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17741 			/* FALLTHRU */
17742 		case IPSEC_STATUS_PENDING:
17743 			return;
17744 		}
17745 		/* we're done with IPsec processing, send it up */
17746 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17747 		return;
17748 	}
17749 	default:
17750 		break;
17751 	}
17752 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17753 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17754 		    ire->ire_zoneid));
17755 		goto drop_pkt;
17756 	}
17757 	/*
17758 	 * Handle protocols with which IP is less intimate.  There
17759 	 * can be more than one stream bound to a particular
17760 	 * protocol.  When this is the case, each one gets a copy
17761 	 * of any incoming packets.
17762 	 */
17763 fanout:
17764 	ip_fanout_proto(q, first_mp, ill, ipha,
17765 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17766 	    B_TRUE, recv_ill, ire->ire_zoneid);
17767 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17768 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17769 	return;
17770 
17771 drop_pkt:
17772 	freemsg(first_mp);
17773 	if (hada_mp != NULL)
17774 		freeb(hada_mp);
17775 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17776 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17777 #undef	rptr
17778 #undef  iphs
17779 
17780 }
17781 
17782 /*
17783  * Update any source route, record route or timestamp options.
17784  * Check that we are at end of strict source route.
17785  * The options have already been checked for sanity in ip_rput_options().
17786  */
17787 static boolean_t
17788 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17789     ip_stack_t *ipst)
17790 {
17791 	ipoptp_t	opts;
17792 	uchar_t		*opt;
17793 	uint8_t		optval;
17794 	uint8_t		optlen;
17795 	ipaddr_t	dst;
17796 	uint32_t	ts;
17797 	ire_t		*dst_ire;
17798 	timestruc_t	now;
17799 	zoneid_t	zoneid;
17800 	ill_t		*ill;
17801 
17802 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17803 
17804 	ip2dbg(("ip_rput_local_options\n"));
17805 
17806 	for (optval = ipoptp_first(&opts, ipha);
17807 	    optval != IPOPT_EOL;
17808 	    optval = ipoptp_next(&opts)) {
17809 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17810 		opt = opts.ipoptp_cur;
17811 		optlen = opts.ipoptp_len;
17812 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17813 		    optval, optlen));
17814 		switch (optval) {
17815 			uint32_t off;
17816 		case IPOPT_SSRR:
17817 		case IPOPT_LSRR:
17818 			off = opt[IPOPT_OFFSET];
17819 			off--;
17820 			if (optlen < IP_ADDR_LEN ||
17821 			    off > optlen - IP_ADDR_LEN) {
17822 				/* End of source route */
17823 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17824 				break;
17825 			}
17826 			/*
17827 			 * This will only happen if two consecutive entries
17828 			 * in the source route contains our address or if
17829 			 * it is a packet with a loose source route which
17830 			 * reaches us before consuming the whole source route
17831 			 */
17832 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17833 			if (optval == IPOPT_SSRR) {
17834 				goto bad_src_route;
17835 			}
17836 			/*
17837 			 * Hack: instead of dropping the packet truncate the
17838 			 * source route to what has been used by filling the
17839 			 * rest with IPOPT_NOP.
17840 			 */
17841 			opt[IPOPT_OLEN] = (uint8_t)off;
17842 			while (off < optlen) {
17843 				opt[off++] = IPOPT_NOP;
17844 			}
17845 			break;
17846 		case IPOPT_RR:
17847 			off = opt[IPOPT_OFFSET];
17848 			off--;
17849 			if (optlen < IP_ADDR_LEN ||
17850 			    off > optlen - IP_ADDR_LEN) {
17851 				/* No more room - ignore */
17852 				ip1dbg((
17853 				    "ip_rput_local_options: end of RR\n"));
17854 				break;
17855 			}
17856 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17857 			    IP_ADDR_LEN);
17858 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17859 			break;
17860 		case IPOPT_TS:
17861 			/* Insert timestamp if there is romm */
17862 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17863 			case IPOPT_TS_TSONLY:
17864 				off = IPOPT_TS_TIMELEN;
17865 				break;
17866 			case IPOPT_TS_PRESPEC:
17867 			case IPOPT_TS_PRESPEC_RFC791:
17868 				/* Verify that the address matched */
17869 				off = opt[IPOPT_OFFSET] - 1;
17870 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17871 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17872 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17873 				    ipst);
17874 				if (dst_ire == NULL) {
17875 					/* Not for us */
17876 					break;
17877 				}
17878 				ire_refrele(dst_ire);
17879 				/* FALLTHRU */
17880 			case IPOPT_TS_TSANDADDR:
17881 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17882 				break;
17883 			default:
17884 				/*
17885 				 * ip_*put_options should have already
17886 				 * dropped this packet.
17887 				 */
17888 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17889 				    "unknown IT - bug in ip_rput_options?\n");
17890 				return (B_TRUE);	/* Keep "lint" happy */
17891 			}
17892 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17893 				/* Increase overflow counter */
17894 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17895 				opt[IPOPT_POS_OV_FLG] =
17896 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17897 				    (off << 4));
17898 				break;
17899 			}
17900 			off = opt[IPOPT_OFFSET] - 1;
17901 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17902 			case IPOPT_TS_PRESPEC:
17903 			case IPOPT_TS_PRESPEC_RFC791:
17904 			case IPOPT_TS_TSANDADDR:
17905 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17906 				    IP_ADDR_LEN);
17907 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17908 				/* FALLTHRU */
17909 			case IPOPT_TS_TSONLY:
17910 				off = opt[IPOPT_OFFSET] - 1;
17911 				/* Compute # of milliseconds since midnight */
17912 				gethrestime(&now);
17913 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17914 				    now.tv_nsec / (NANOSEC / MILLISEC);
17915 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17916 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17917 				break;
17918 			}
17919 			break;
17920 		}
17921 	}
17922 	return (B_TRUE);
17923 
17924 bad_src_route:
17925 	q = WR(q);
17926 	if (q->q_next != NULL)
17927 		ill = q->q_ptr;
17928 	else
17929 		ill = NULL;
17930 
17931 	/* make sure we clear any indication of a hardware checksum */
17932 	DB_CKSUMFLAGS(mp) = 0;
17933 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17934 	if (zoneid == ALL_ZONES)
17935 		freemsg(mp);
17936 	else
17937 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17938 	return (B_FALSE);
17939 
17940 }
17941 
17942 /*
17943  * Process IP options in an inbound packet.  If an option affects the
17944  * effective destination address, return the next hop address via dstp.
17945  * Returns -1 if something fails in which case an ICMP error has been sent
17946  * and mp freed.
17947  */
17948 static int
17949 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17950     ip_stack_t *ipst)
17951 {
17952 	ipoptp_t	opts;
17953 	uchar_t		*opt;
17954 	uint8_t		optval;
17955 	uint8_t		optlen;
17956 	ipaddr_t	dst;
17957 	intptr_t	code = 0;
17958 	ire_t		*ire = NULL;
17959 	zoneid_t	zoneid;
17960 	ill_t		*ill;
17961 
17962 	ip2dbg(("ip_rput_options\n"));
17963 	dst = ipha->ipha_dst;
17964 	for (optval = ipoptp_first(&opts, ipha);
17965 	    optval != IPOPT_EOL;
17966 	    optval = ipoptp_next(&opts)) {
17967 		opt = opts.ipoptp_cur;
17968 		optlen = opts.ipoptp_len;
17969 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17970 		    optval, optlen));
17971 		/*
17972 		 * Note: we need to verify the checksum before we
17973 		 * modify anything thus this routine only extracts the next
17974 		 * hop dst from any source route.
17975 		 */
17976 		switch (optval) {
17977 			uint32_t off;
17978 		case IPOPT_SSRR:
17979 		case IPOPT_LSRR:
17980 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17981 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17982 			if (ire == NULL) {
17983 				if (optval == IPOPT_SSRR) {
17984 					ip1dbg(("ip_rput_options: not next"
17985 					    " strict source route 0x%x\n",
17986 					    ntohl(dst)));
17987 					code = (char *)&ipha->ipha_dst -
17988 					    (char *)ipha;
17989 					goto param_prob; /* RouterReq's */
17990 				}
17991 				ip2dbg(("ip_rput_options: "
17992 				    "not next source route 0x%x\n",
17993 				    ntohl(dst)));
17994 				break;
17995 			}
17996 			ire_refrele(ire);
17997 
17998 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17999 				ip1dbg((
18000 				    "ip_rput_options: bad option offset\n"));
18001 				code = (char *)&opt[IPOPT_OLEN] -
18002 				    (char *)ipha;
18003 				goto param_prob;
18004 			}
18005 			off = opt[IPOPT_OFFSET];
18006 			off--;
18007 		redo_srr:
18008 			if (optlen < IP_ADDR_LEN ||
18009 			    off > optlen - IP_ADDR_LEN) {
18010 				/* End of source route */
18011 				ip1dbg(("ip_rput_options: end of SR\n"));
18012 				break;
18013 			}
18014 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18015 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18016 			    ntohl(dst)));
18017 
18018 			/*
18019 			 * Check if our address is present more than
18020 			 * once as consecutive hops in source route.
18021 			 * XXX verify per-interface ip_forwarding
18022 			 * for source route?
18023 			 */
18024 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18025 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18026 
18027 			if (ire != NULL) {
18028 				ire_refrele(ire);
18029 				off += IP_ADDR_LEN;
18030 				goto redo_srr;
18031 			}
18032 
18033 			if (dst == htonl(INADDR_LOOPBACK)) {
18034 				ip1dbg(("ip_rput_options: loopback addr in "
18035 				    "source route!\n"));
18036 				goto bad_src_route;
18037 			}
18038 			/*
18039 			 * For strict: verify that dst is directly
18040 			 * reachable.
18041 			 */
18042 			if (optval == IPOPT_SSRR) {
18043 				ire = ire_ftable_lookup(dst, 0, 0,
18044 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18045 				    MBLK_GETLABEL(mp),
18046 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18047 				if (ire == NULL) {
18048 					ip1dbg(("ip_rput_options: SSRR not "
18049 					    "directly reachable: 0x%x\n",
18050 					    ntohl(dst)));
18051 					goto bad_src_route;
18052 				}
18053 				ire_refrele(ire);
18054 			}
18055 			/*
18056 			 * Defer update of the offset and the record route
18057 			 * until the packet is forwarded.
18058 			 */
18059 			break;
18060 		case IPOPT_RR:
18061 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18062 				ip1dbg((
18063 				    "ip_rput_options: bad option offset\n"));
18064 				code = (char *)&opt[IPOPT_OLEN] -
18065 				    (char *)ipha;
18066 				goto param_prob;
18067 			}
18068 			break;
18069 		case IPOPT_TS:
18070 			/*
18071 			 * Verify that length >= 5 and that there is either
18072 			 * room for another timestamp or that the overflow
18073 			 * counter is not maxed out.
18074 			 */
18075 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18076 			if (optlen < IPOPT_MINLEN_IT) {
18077 				goto param_prob;
18078 			}
18079 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18080 				ip1dbg((
18081 				    "ip_rput_options: bad option offset\n"));
18082 				code = (char *)&opt[IPOPT_OFFSET] -
18083 				    (char *)ipha;
18084 				goto param_prob;
18085 			}
18086 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18087 			case IPOPT_TS_TSONLY:
18088 				off = IPOPT_TS_TIMELEN;
18089 				break;
18090 			case IPOPT_TS_TSANDADDR:
18091 			case IPOPT_TS_PRESPEC:
18092 			case IPOPT_TS_PRESPEC_RFC791:
18093 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18094 				break;
18095 			default:
18096 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18097 				    (char *)ipha;
18098 				goto param_prob;
18099 			}
18100 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18101 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18102 				/*
18103 				 * No room and the overflow counter is 15
18104 				 * already.
18105 				 */
18106 				goto param_prob;
18107 			}
18108 			break;
18109 		}
18110 	}
18111 
18112 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18113 		*dstp = dst;
18114 		return (0);
18115 	}
18116 
18117 	ip1dbg(("ip_rput_options: error processing IP options."));
18118 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18119 
18120 param_prob:
18121 	q = WR(q);
18122 	if (q->q_next != NULL)
18123 		ill = q->q_ptr;
18124 	else
18125 		ill = NULL;
18126 
18127 	/* make sure we clear any indication of a hardware checksum */
18128 	DB_CKSUMFLAGS(mp) = 0;
18129 	/* Don't know whether this is for non-global or global/forwarding */
18130 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18131 	if (zoneid == ALL_ZONES)
18132 		freemsg(mp);
18133 	else
18134 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18135 	return (-1);
18136 
18137 bad_src_route:
18138 	q = WR(q);
18139 	if (q->q_next != NULL)
18140 		ill = q->q_ptr;
18141 	else
18142 		ill = NULL;
18143 
18144 	/* make sure we clear any indication of a hardware checksum */
18145 	DB_CKSUMFLAGS(mp) = 0;
18146 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18147 	if (zoneid == ALL_ZONES)
18148 		freemsg(mp);
18149 	else
18150 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18151 	return (-1);
18152 }
18153 
18154 /*
18155  * IP & ICMP info in >=14 msg's ...
18156  *  - ip fixed part (mib2_ip_t)
18157  *  - icmp fixed part (mib2_icmp_t)
18158  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18159  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18160  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18161  *  - ipRouteAttributeTable (ip 102)	labeled routes
18162  *  - ip multicast membership (ip_member_t)
18163  *  - ip multicast source filtering (ip_grpsrc_t)
18164  *  - igmp fixed part (struct igmpstat)
18165  *  - multicast routing stats (struct mrtstat)
18166  *  - multicast routing vifs (array of struct vifctl)
18167  *  - multicast routing routes (array of struct mfcctl)
18168  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18169  *					One per ill plus one generic
18170  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18171  *					One per ill plus one generic
18172  *  - ipv6RouteEntry			all IPv6 IREs
18173  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18174  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18175  *  - ipv6AddrEntry			all IPv6 ipifs
18176  *  - ipv6 multicast membership (ipv6_member_t)
18177  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18178  *
18179  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18180  *
18181  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18182  * already filled in by the caller.
18183  * Return value of 0 indicates that no messages were sent and caller
18184  * should free mpctl.
18185  */
18186 int
18187 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18188 {
18189 	ip_stack_t *ipst;
18190 	sctp_stack_t *sctps;
18191 
18192 	if (q->q_next != NULL) {
18193 		ipst = ILLQ_TO_IPST(q);
18194 	} else {
18195 		ipst = CONNQ_TO_IPST(q);
18196 	}
18197 	ASSERT(ipst != NULL);
18198 	sctps = ipst->ips_netstack->netstack_sctp;
18199 
18200 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18201 		return (0);
18202 	}
18203 
18204 	/*
18205 	 * For the purposes of the (broken) packet shell use
18206 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18207 	 * to make TCP and UDP appear first in the list of mib items.
18208 	 * TBD: We could expand this and use it in netstat so that
18209 	 * the kernel doesn't have to produce large tables (connections,
18210 	 * routes, etc) when netstat only wants the statistics or a particular
18211 	 * table.
18212 	 */
18213 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18214 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18215 			return (1);
18216 		}
18217 	}
18218 
18219 	if (level != MIB2_TCP) {
18220 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18221 			return (1);
18222 		}
18223 	}
18224 
18225 	if (level != MIB2_UDP) {
18226 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18227 			return (1);
18228 		}
18229 	}
18230 
18231 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18232 	    ipst)) == NULL) {
18233 		return (1);
18234 	}
18235 
18236 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18237 		return (1);
18238 	}
18239 
18240 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18241 		return (1);
18242 	}
18243 
18244 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18245 		return (1);
18246 	}
18247 
18248 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18249 		return (1);
18250 	}
18251 
18252 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18253 		return (1);
18254 	}
18255 
18256 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18257 		return (1);
18258 	}
18259 
18260 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18261 		return (1);
18262 	}
18263 
18264 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18265 		return (1);
18266 	}
18267 
18268 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18269 		return (1);
18270 	}
18271 
18272 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18273 		return (1);
18274 	}
18275 
18276 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18277 		return (1);
18278 	}
18279 
18280 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18281 		return (1);
18282 	}
18283 
18284 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18285 		return (1);
18286 	}
18287 
18288 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
18289 	if (mpctl == NULL)
18290 		return (1);
18291 
18292 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
18293 	if (mpctl == NULL)
18294 		return (1);
18295 
18296 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18297 		return (1);
18298 	}
18299 	freemsg(mpctl);
18300 	return (1);
18301 }
18302 
18303 /* Get global (legacy) IPv4 statistics */
18304 static mblk_t *
18305 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18306     ip_stack_t *ipst)
18307 {
18308 	mib2_ip_t		old_ip_mib;
18309 	struct opthdr		*optp;
18310 	mblk_t			*mp2ctl;
18311 
18312 	/*
18313 	 * make a copy of the original message
18314 	 */
18315 	mp2ctl = copymsg(mpctl);
18316 
18317 	/* fixed length IP structure... */
18318 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18319 	optp->level = MIB2_IP;
18320 	optp->name = 0;
18321 	SET_MIB(old_ip_mib.ipForwarding,
18322 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18323 	SET_MIB(old_ip_mib.ipDefaultTTL,
18324 	    (uint32_t)ipst->ips_ip_def_ttl);
18325 	SET_MIB(old_ip_mib.ipReasmTimeout,
18326 	    ipst->ips_ip_g_frag_timeout);
18327 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18328 	    sizeof (mib2_ipAddrEntry_t));
18329 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18330 	    sizeof (mib2_ipRouteEntry_t));
18331 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18332 	    sizeof (mib2_ipNetToMediaEntry_t));
18333 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18334 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18335 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18336 	    sizeof (mib2_ipAttributeEntry_t));
18337 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18338 
18339 	/*
18340 	 * Grab the statistics from the new IP MIB
18341 	 */
18342 	SET_MIB(old_ip_mib.ipInReceives,
18343 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18344 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18345 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18346 	SET_MIB(old_ip_mib.ipForwDatagrams,
18347 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18348 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18349 	    ipmib->ipIfStatsInUnknownProtos);
18350 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18351 	SET_MIB(old_ip_mib.ipInDelivers,
18352 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18353 	SET_MIB(old_ip_mib.ipOutRequests,
18354 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18355 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18356 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18357 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18358 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18359 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18360 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18361 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18362 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18363 
18364 	/* ipRoutingDiscards is not being used */
18365 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18366 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18367 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18368 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18369 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18370 	    ipmib->ipIfStatsReasmDuplicates);
18371 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18372 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18373 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18374 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18375 	SET_MIB(old_ip_mib.rawipInOverflows,
18376 	    ipmib->rawipIfStatsInOverflows);
18377 
18378 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18379 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18380 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18381 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18382 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18383 	    ipmib->ipIfStatsOutSwitchIPVersion);
18384 
18385 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18386 	    (int)sizeof (old_ip_mib))) {
18387 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18388 		    (uint_t)sizeof (old_ip_mib)));
18389 	}
18390 
18391 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18392 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18393 	    (int)optp->level, (int)optp->name, (int)optp->len));
18394 	qreply(q, mpctl);
18395 	return (mp2ctl);
18396 }
18397 
18398 /* Per interface IPv4 statistics */
18399 static mblk_t *
18400 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18401 {
18402 	struct opthdr		*optp;
18403 	mblk_t			*mp2ctl;
18404 	ill_t			*ill;
18405 	ill_walk_context_t	ctx;
18406 	mblk_t			*mp_tail = NULL;
18407 	mib2_ipIfStatsEntry_t	global_ip_mib;
18408 
18409 	/*
18410 	 * Make a copy of the original message
18411 	 */
18412 	mp2ctl = copymsg(mpctl);
18413 
18414 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18415 	optp->level = MIB2_IP;
18416 	optp->name = MIB2_IP_TRAFFIC_STATS;
18417 	/* Include "unknown interface" ip_mib */
18418 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18419 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18420 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18421 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18422 	    (ipst->ips_ip_g_forward ? 1 : 2));
18423 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18424 	    (uint32_t)ipst->ips_ip_def_ttl);
18425 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18426 	    sizeof (mib2_ipIfStatsEntry_t));
18427 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18428 	    sizeof (mib2_ipAddrEntry_t));
18429 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18430 	    sizeof (mib2_ipRouteEntry_t));
18431 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18432 	    sizeof (mib2_ipNetToMediaEntry_t));
18433 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18434 	    sizeof (ip_member_t));
18435 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18436 	    sizeof (ip_grpsrc_t));
18437 
18438 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18439 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18440 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18441 		    "failed to allocate %u bytes\n",
18442 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18443 	}
18444 
18445 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18446 
18447 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18448 	ill = ILL_START_WALK_V4(&ctx, ipst);
18449 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18450 		ill->ill_ip_mib->ipIfStatsIfIndex =
18451 		    ill->ill_phyint->phyint_ifindex;
18452 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18453 		    (ipst->ips_ip_g_forward ? 1 : 2));
18454 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18455 		    (uint32_t)ipst->ips_ip_def_ttl);
18456 
18457 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18458 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18459 		    (char *)ill->ill_ip_mib,
18460 		    (int)sizeof (*ill->ill_ip_mib))) {
18461 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18462 			    "failed to allocate %u bytes\n",
18463 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18464 		}
18465 	}
18466 	rw_exit(&ipst->ips_ill_g_lock);
18467 
18468 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18469 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18470 	    "level %d, name %d, len %d\n",
18471 	    (int)optp->level, (int)optp->name, (int)optp->len));
18472 	qreply(q, mpctl);
18473 
18474 	if (mp2ctl == NULL)
18475 		return (NULL);
18476 
18477 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18478 }
18479 
18480 /* Global IPv4 ICMP statistics */
18481 static mblk_t *
18482 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18483 {
18484 	struct opthdr		*optp;
18485 	mblk_t			*mp2ctl;
18486 
18487 	/*
18488 	 * Make a copy of the original message
18489 	 */
18490 	mp2ctl = copymsg(mpctl);
18491 
18492 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18493 	optp->level = MIB2_ICMP;
18494 	optp->name = 0;
18495 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18496 	    (int)sizeof (ipst->ips_icmp_mib))) {
18497 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18498 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18499 	}
18500 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18501 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18502 	    (int)optp->level, (int)optp->name, (int)optp->len));
18503 	qreply(q, mpctl);
18504 	return (mp2ctl);
18505 }
18506 
18507 /* Global IPv4 IGMP statistics */
18508 static mblk_t *
18509 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18510 {
18511 	struct opthdr		*optp;
18512 	mblk_t			*mp2ctl;
18513 
18514 	/*
18515 	 * make a copy of the original message
18516 	 */
18517 	mp2ctl = copymsg(mpctl);
18518 
18519 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18520 	optp->level = EXPER_IGMP;
18521 	optp->name = 0;
18522 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18523 	    (int)sizeof (ipst->ips_igmpstat))) {
18524 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18525 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18526 	}
18527 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18528 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18529 	    (int)optp->level, (int)optp->name, (int)optp->len));
18530 	qreply(q, mpctl);
18531 	return (mp2ctl);
18532 }
18533 
18534 /* Global IPv4 Multicast Routing statistics */
18535 static mblk_t *
18536 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18537 {
18538 	struct opthdr		*optp;
18539 	mblk_t			*mp2ctl;
18540 
18541 	/*
18542 	 * make a copy of the original message
18543 	 */
18544 	mp2ctl = copymsg(mpctl);
18545 
18546 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18547 	optp->level = EXPER_DVMRP;
18548 	optp->name = 0;
18549 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18550 		ip0dbg(("ip_mroute_stats: failed\n"));
18551 	}
18552 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18553 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18554 	    (int)optp->level, (int)optp->name, (int)optp->len));
18555 	qreply(q, mpctl);
18556 	return (mp2ctl);
18557 }
18558 
18559 /* IPv4 address information */
18560 static mblk_t *
18561 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18562 {
18563 	struct opthdr		*optp;
18564 	mblk_t			*mp2ctl;
18565 	mblk_t			*mp_tail = NULL;
18566 	ill_t			*ill;
18567 	ipif_t			*ipif;
18568 	uint_t			bitval;
18569 	mib2_ipAddrEntry_t	mae;
18570 	zoneid_t		zoneid;
18571 	ill_walk_context_t ctx;
18572 
18573 	/*
18574 	 * make a copy of the original message
18575 	 */
18576 	mp2ctl = copymsg(mpctl);
18577 
18578 	/* ipAddrEntryTable */
18579 
18580 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18581 	optp->level = MIB2_IP;
18582 	optp->name = MIB2_IP_ADDR;
18583 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18584 
18585 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18586 	ill = ILL_START_WALK_V4(&ctx, ipst);
18587 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18588 		for (ipif = ill->ill_ipif; ipif != NULL;
18589 		    ipif = ipif->ipif_next) {
18590 			if (ipif->ipif_zoneid != zoneid &&
18591 			    ipif->ipif_zoneid != ALL_ZONES)
18592 				continue;
18593 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18594 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18595 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18596 
18597 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18598 			    OCTET_LENGTH);
18599 			mae.ipAdEntIfIndex.o_length =
18600 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18601 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18602 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18603 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18604 			mae.ipAdEntInfo.ae_subnet_len =
18605 			    ip_mask_to_plen(ipif->ipif_net_mask);
18606 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18607 			for (bitval = 1;
18608 			    bitval &&
18609 			    !(bitval & ipif->ipif_brd_addr);
18610 			    bitval <<= 1)
18611 				noop;
18612 			mae.ipAdEntBcastAddr = bitval;
18613 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18614 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18615 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18616 			mae.ipAdEntInfo.ae_broadcast_addr =
18617 			    ipif->ipif_brd_addr;
18618 			mae.ipAdEntInfo.ae_pp_dst_addr =
18619 			    ipif->ipif_pp_dst_addr;
18620 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18621 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18622 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18623 
18624 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18625 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18626 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18627 				    "allocate %u bytes\n",
18628 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18629 			}
18630 		}
18631 	}
18632 	rw_exit(&ipst->ips_ill_g_lock);
18633 
18634 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18635 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18636 	    (int)optp->level, (int)optp->name, (int)optp->len));
18637 	qreply(q, mpctl);
18638 	return (mp2ctl);
18639 }
18640 
18641 /* IPv6 address information */
18642 static mblk_t *
18643 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18644 {
18645 	struct opthdr		*optp;
18646 	mblk_t			*mp2ctl;
18647 	mblk_t			*mp_tail = NULL;
18648 	ill_t			*ill;
18649 	ipif_t			*ipif;
18650 	mib2_ipv6AddrEntry_t	mae6;
18651 	zoneid_t		zoneid;
18652 	ill_walk_context_t	ctx;
18653 
18654 	/*
18655 	 * make a copy of the original message
18656 	 */
18657 	mp2ctl = copymsg(mpctl);
18658 
18659 	/* ipv6AddrEntryTable */
18660 
18661 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18662 	optp->level = MIB2_IP6;
18663 	optp->name = MIB2_IP6_ADDR;
18664 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18665 
18666 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18667 	ill = ILL_START_WALK_V6(&ctx, ipst);
18668 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18669 		for (ipif = ill->ill_ipif; ipif != NULL;
18670 		    ipif = ipif->ipif_next) {
18671 			if (ipif->ipif_zoneid != zoneid &&
18672 			    ipif->ipif_zoneid != ALL_ZONES)
18673 				continue;
18674 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18675 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18676 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18677 
18678 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18679 			    OCTET_LENGTH);
18680 			mae6.ipv6AddrIfIndex.o_length =
18681 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18682 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18683 			mae6.ipv6AddrPfxLength =
18684 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18685 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18686 			mae6.ipv6AddrInfo.ae_subnet_len =
18687 			    mae6.ipv6AddrPfxLength;
18688 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18689 
18690 			/* Type: stateless(1), stateful(2), unknown(3) */
18691 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18692 				mae6.ipv6AddrType = 1;
18693 			else
18694 				mae6.ipv6AddrType = 2;
18695 			/* Anycast: true(1), false(2) */
18696 			if (ipif->ipif_flags & IPIF_ANYCAST)
18697 				mae6.ipv6AddrAnycastFlag = 1;
18698 			else
18699 				mae6.ipv6AddrAnycastFlag = 2;
18700 
18701 			/*
18702 			 * Address status: preferred(1), deprecated(2),
18703 			 * invalid(3), inaccessible(4), unknown(5)
18704 			 */
18705 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18706 				mae6.ipv6AddrStatus = 3;
18707 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18708 				mae6.ipv6AddrStatus = 2;
18709 			else
18710 				mae6.ipv6AddrStatus = 1;
18711 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18712 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18713 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18714 			    ipif->ipif_v6pp_dst_addr;
18715 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18716 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18717 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18718 			mae6.ipv6AddrIdentifier = ill->ill_token;
18719 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18720 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18721 			mae6.ipv6AddrRetransmitTime =
18722 			    ill->ill_reachable_retrans_time;
18723 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18724 			    (char *)&mae6,
18725 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18726 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18727 				    "allocate %u bytes\n",
18728 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18729 			}
18730 		}
18731 	}
18732 	rw_exit(&ipst->ips_ill_g_lock);
18733 
18734 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18735 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18736 	    (int)optp->level, (int)optp->name, (int)optp->len));
18737 	qreply(q, mpctl);
18738 	return (mp2ctl);
18739 }
18740 
18741 /* IPv4 multicast group membership. */
18742 static mblk_t *
18743 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18744 {
18745 	struct opthdr		*optp;
18746 	mblk_t			*mp2ctl;
18747 	ill_t			*ill;
18748 	ipif_t			*ipif;
18749 	ilm_t			*ilm;
18750 	ip_member_t		ipm;
18751 	mblk_t			*mp_tail = NULL;
18752 	ill_walk_context_t	ctx;
18753 	zoneid_t		zoneid;
18754 	ilm_walker_t		ilw;
18755 
18756 	/*
18757 	 * make a copy of the original message
18758 	 */
18759 	mp2ctl = copymsg(mpctl);
18760 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18761 
18762 	/* ipGroupMember table */
18763 	optp = (struct opthdr *)&mpctl->b_rptr[
18764 	    sizeof (struct T_optmgmt_ack)];
18765 	optp->level = MIB2_IP;
18766 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18767 
18768 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18769 	ill = ILL_START_WALK_V4(&ctx, ipst);
18770 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18771 		if (IS_UNDER_IPMP(ill))
18772 			continue;
18773 
18774 		ilm = ilm_walker_start(&ilw, ill);
18775 		for (ipif = ill->ill_ipif; ipif != NULL;
18776 		    ipif = ipif->ipif_next) {
18777 			if (ipif->ipif_zoneid != zoneid &&
18778 			    ipif->ipif_zoneid != ALL_ZONES)
18779 				continue;	/* not this zone */
18780 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18781 			    OCTET_LENGTH);
18782 			ipm.ipGroupMemberIfIndex.o_length =
18783 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18784 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18785 				ASSERT(ilm->ilm_ipif != NULL);
18786 				ASSERT(ilm->ilm_ill == NULL);
18787 				if (ilm->ilm_ipif != ipif)
18788 					continue;
18789 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18790 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18791 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18792 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18793 				    (char *)&ipm, (int)sizeof (ipm))) {
18794 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18795 					    "failed to allocate %u bytes\n",
18796 					    (uint_t)sizeof (ipm)));
18797 				}
18798 			}
18799 		}
18800 		ilm_walker_finish(&ilw);
18801 	}
18802 	rw_exit(&ipst->ips_ill_g_lock);
18803 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18804 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18805 	    (int)optp->level, (int)optp->name, (int)optp->len));
18806 	qreply(q, mpctl);
18807 	return (mp2ctl);
18808 }
18809 
18810 /* IPv6 multicast group membership. */
18811 static mblk_t *
18812 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18813 {
18814 	struct opthdr		*optp;
18815 	mblk_t			*mp2ctl;
18816 	ill_t			*ill;
18817 	ilm_t			*ilm;
18818 	ipv6_member_t		ipm6;
18819 	mblk_t			*mp_tail = NULL;
18820 	ill_walk_context_t	ctx;
18821 	zoneid_t		zoneid;
18822 	ilm_walker_t		ilw;
18823 
18824 	/*
18825 	 * make a copy of the original message
18826 	 */
18827 	mp2ctl = copymsg(mpctl);
18828 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18829 
18830 	/* ip6GroupMember table */
18831 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18832 	optp->level = MIB2_IP6;
18833 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18834 
18835 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18836 	ill = ILL_START_WALK_V6(&ctx, ipst);
18837 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18838 		if (IS_UNDER_IPMP(ill))
18839 			continue;
18840 
18841 		ilm = ilm_walker_start(&ilw, ill);
18842 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18843 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18844 			ASSERT(ilm->ilm_ipif == NULL);
18845 			ASSERT(ilm->ilm_ill != NULL);
18846 			if (ilm->ilm_zoneid != zoneid)
18847 				continue;	/* not this zone */
18848 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18849 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18850 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18851 			if (!snmp_append_data2(mpctl->b_cont,
18852 			    &mp_tail,
18853 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18854 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18855 				    "failed to allocate %u bytes\n",
18856 				    (uint_t)sizeof (ipm6)));
18857 			}
18858 		}
18859 		ilm_walker_finish(&ilw);
18860 	}
18861 	rw_exit(&ipst->ips_ill_g_lock);
18862 
18863 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18864 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18865 	    (int)optp->level, (int)optp->name, (int)optp->len));
18866 	qreply(q, mpctl);
18867 	return (mp2ctl);
18868 }
18869 
18870 /* IP multicast filtered sources */
18871 static mblk_t *
18872 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18873 {
18874 	struct opthdr		*optp;
18875 	mblk_t			*mp2ctl;
18876 	ill_t			*ill;
18877 	ipif_t			*ipif;
18878 	ilm_t			*ilm;
18879 	ip_grpsrc_t		ips;
18880 	mblk_t			*mp_tail = NULL;
18881 	ill_walk_context_t	ctx;
18882 	zoneid_t		zoneid;
18883 	int			i;
18884 	slist_t			*sl;
18885 	ilm_walker_t		ilw;
18886 
18887 	/*
18888 	 * make a copy of the original message
18889 	 */
18890 	mp2ctl = copymsg(mpctl);
18891 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18892 
18893 	/* ipGroupSource table */
18894 	optp = (struct opthdr *)&mpctl->b_rptr[
18895 	    sizeof (struct T_optmgmt_ack)];
18896 	optp->level = MIB2_IP;
18897 	optp->name = EXPER_IP_GROUP_SOURCES;
18898 
18899 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18900 	ill = ILL_START_WALK_V4(&ctx, ipst);
18901 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18902 		if (IS_UNDER_IPMP(ill))
18903 			continue;
18904 
18905 		ilm = ilm_walker_start(&ilw, ill);
18906 		for (ipif = ill->ill_ipif; ipif != NULL;
18907 		    ipif = ipif->ipif_next) {
18908 			if (ipif->ipif_zoneid != zoneid)
18909 				continue;	/* not this zone */
18910 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18911 			    OCTET_LENGTH);
18912 			ips.ipGroupSourceIfIndex.o_length =
18913 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18914 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18915 				ASSERT(ilm->ilm_ipif != NULL);
18916 				ASSERT(ilm->ilm_ill == NULL);
18917 				sl = ilm->ilm_filter;
18918 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18919 					continue;
18920 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18921 				for (i = 0; i < sl->sl_numsrc; i++) {
18922 					if (!IN6_IS_ADDR_V4MAPPED(
18923 					    &sl->sl_addr[i]))
18924 						continue;
18925 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18926 					    ips.ipGroupSourceAddress);
18927 					if (snmp_append_data2(mpctl->b_cont,
18928 					    &mp_tail, (char *)&ips,
18929 					    (int)sizeof (ips)) == 0) {
18930 						ip1dbg(("ip_snmp_get_mib2_"
18931 						    "ip_group_src: failed to "
18932 						    "allocate %u bytes\n",
18933 						    (uint_t)sizeof (ips)));
18934 					}
18935 				}
18936 			}
18937 		}
18938 		ilm_walker_finish(&ilw);
18939 	}
18940 	rw_exit(&ipst->ips_ill_g_lock);
18941 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18942 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18943 	    (int)optp->level, (int)optp->name, (int)optp->len));
18944 	qreply(q, mpctl);
18945 	return (mp2ctl);
18946 }
18947 
18948 /* IPv6 multicast filtered sources. */
18949 static mblk_t *
18950 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18951 {
18952 	struct opthdr		*optp;
18953 	mblk_t			*mp2ctl;
18954 	ill_t			*ill;
18955 	ilm_t			*ilm;
18956 	ipv6_grpsrc_t		ips6;
18957 	mblk_t			*mp_tail = NULL;
18958 	ill_walk_context_t	ctx;
18959 	zoneid_t		zoneid;
18960 	int			i;
18961 	slist_t			*sl;
18962 	ilm_walker_t		ilw;
18963 
18964 	/*
18965 	 * make a copy of the original message
18966 	 */
18967 	mp2ctl = copymsg(mpctl);
18968 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18969 
18970 	/* ip6GroupMember table */
18971 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18972 	optp->level = MIB2_IP6;
18973 	optp->name = EXPER_IP6_GROUP_SOURCES;
18974 
18975 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18976 	ill = ILL_START_WALK_V6(&ctx, ipst);
18977 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18978 		if (IS_UNDER_IPMP(ill))
18979 			continue;
18980 
18981 		ilm = ilm_walker_start(&ilw, ill);
18982 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18983 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18984 			ASSERT(ilm->ilm_ipif == NULL);
18985 			ASSERT(ilm->ilm_ill != NULL);
18986 			sl = ilm->ilm_filter;
18987 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18988 				continue;
18989 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18990 			for (i = 0; i < sl->sl_numsrc; i++) {
18991 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18992 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18993 				    (char *)&ips6, (int)sizeof (ips6))) {
18994 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18995 					    "group_src: failed to allocate "
18996 					    "%u bytes\n",
18997 					    (uint_t)sizeof (ips6)));
18998 				}
18999 			}
19000 		}
19001 		ilm_walker_finish(&ilw);
19002 	}
19003 	rw_exit(&ipst->ips_ill_g_lock);
19004 
19005 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19006 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19007 	    (int)optp->level, (int)optp->name, (int)optp->len));
19008 	qreply(q, mpctl);
19009 	return (mp2ctl);
19010 }
19011 
19012 /* Multicast routing virtual interface table. */
19013 static mblk_t *
19014 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19015 {
19016 	struct opthdr		*optp;
19017 	mblk_t			*mp2ctl;
19018 
19019 	/*
19020 	 * make a copy of the original message
19021 	 */
19022 	mp2ctl = copymsg(mpctl);
19023 
19024 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19025 	optp->level = EXPER_DVMRP;
19026 	optp->name = EXPER_DVMRP_VIF;
19027 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
19028 		ip0dbg(("ip_mroute_vif: failed\n"));
19029 	}
19030 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19031 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19032 	    (int)optp->level, (int)optp->name, (int)optp->len));
19033 	qreply(q, mpctl);
19034 	return (mp2ctl);
19035 }
19036 
19037 /* Multicast routing table. */
19038 static mblk_t *
19039 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19040 {
19041 	struct opthdr		*optp;
19042 	mblk_t			*mp2ctl;
19043 
19044 	/*
19045 	 * make a copy of the original message
19046 	 */
19047 	mp2ctl = copymsg(mpctl);
19048 
19049 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19050 	optp->level = EXPER_DVMRP;
19051 	optp->name = EXPER_DVMRP_MRT;
19052 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19053 		ip0dbg(("ip_mroute_mrt: failed\n"));
19054 	}
19055 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19056 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19057 	    (int)optp->level, (int)optp->name, (int)optp->len));
19058 	qreply(q, mpctl);
19059 	return (mp2ctl);
19060 }
19061 
19062 /*
19063  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19064  * in one IRE walk.
19065  */
19066 static mblk_t *
19067 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
19068     ip_stack_t *ipst)
19069 {
19070 	struct opthdr	*optp;
19071 	mblk_t		*mp2ctl;	/* Returned */
19072 	mblk_t		*mp3ctl;	/* nettomedia */
19073 	mblk_t		*mp4ctl;	/* routeattrs */
19074 	iproutedata_t	ird;
19075 	zoneid_t	zoneid;
19076 
19077 	/*
19078 	 * make copies of the original message
19079 	 *	- mp2ctl is returned unchanged to the caller for his use
19080 	 *	- mpctl is sent upstream as ipRouteEntryTable
19081 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19082 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19083 	 */
19084 	mp2ctl = copymsg(mpctl);
19085 	mp3ctl = copymsg(mpctl);
19086 	mp4ctl = copymsg(mpctl);
19087 	if (mp3ctl == NULL || mp4ctl == NULL) {
19088 		freemsg(mp4ctl);
19089 		freemsg(mp3ctl);
19090 		freemsg(mp2ctl);
19091 		freemsg(mpctl);
19092 		return (NULL);
19093 	}
19094 
19095 	bzero(&ird, sizeof (ird));
19096 
19097 	ird.ird_route.lp_head = mpctl->b_cont;
19098 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19099 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19100 	/*
19101 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19102 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19103 	 * intended a temporary solution until a proper MIB API is provided
19104 	 * that provides complete filtering/caller-opt-in.
19105 	 */
19106 	if (level == EXPER_IP_AND_TESTHIDDEN)
19107 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19108 
19109 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19110 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19111 
19112 	/* ipRouteEntryTable in mpctl */
19113 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19114 	optp->level = MIB2_IP;
19115 	optp->name = MIB2_IP_ROUTE;
19116 	optp->len = msgdsize(ird.ird_route.lp_head);
19117 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19118 	    (int)optp->level, (int)optp->name, (int)optp->len));
19119 	qreply(q, mpctl);
19120 
19121 	/* ipNetToMediaEntryTable in mp3ctl */
19122 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19123 	optp->level = MIB2_IP;
19124 	optp->name = MIB2_IP_MEDIA;
19125 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19126 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19127 	    (int)optp->level, (int)optp->name, (int)optp->len));
19128 	qreply(q, mp3ctl);
19129 
19130 	/* ipRouteAttributeTable in mp4ctl */
19131 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19132 	optp->level = MIB2_IP;
19133 	optp->name = EXPER_IP_RTATTR;
19134 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19135 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19136 	    (int)optp->level, (int)optp->name, (int)optp->len));
19137 	if (optp->len == 0)
19138 		freemsg(mp4ctl);
19139 	else
19140 		qreply(q, mp4ctl);
19141 
19142 	return (mp2ctl);
19143 }
19144 
19145 /*
19146  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19147  * ipv6NetToMediaEntryTable in an NDP walk.
19148  */
19149 static mblk_t *
19150 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
19151     ip_stack_t *ipst)
19152 {
19153 	struct opthdr	*optp;
19154 	mblk_t		*mp2ctl;	/* Returned */
19155 	mblk_t		*mp3ctl;	/* nettomedia */
19156 	mblk_t		*mp4ctl;	/* routeattrs */
19157 	iproutedata_t	ird;
19158 	zoneid_t	zoneid;
19159 
19160 	/*
19161 	 * make copies of the original message
19162 	 *	- mp2ctl is returned unchanged to the caller for his use
19163 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19164 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19165 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19166 	 */
19167 	mp2ctl = copymsg(mpctl);
19168 	mp3ctl = copymsg(mpctl);
19169 	mp4ctl = copymsg(mpctl);
19170 	if (mp3ctl == NULL || mp4ctl == NULL) {
19171 		freemsg(mp4ctl);
19172 		freemsg(mp3ctl);
19173 		freemsg(mp2ctl);
19174 		freemsg(mpctl);
19175 		return (NULL);
19176 	}
19177 
19178 	bzero(&ird, sizeof (ird));
19179 
19180 	ird.ird_route.lp_head = mpctl->b_cont;
19181 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19182 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19183 	/*
19184 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19185 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19186 	 * intended a temporary solution until a proper MIB API is provided
19187 	 * that provides complete filtering/caller-opt-in.
19188 	 */
19189 	if (level == EXPER_IP_AND_TESTHIDDEN)
19190 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19191 
19192 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19193 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19194 
19195 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19196 	optp->level = MIB2_IP6;
19197 	optp->name = MIB2_IP6_ROUTE;
19198 	optp->len = msgdsize(ird.ird_route.lp_head);
19199 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19200 	    (int)optp->level, (int)optp->name, (int)optp->len));
19201 	qreply(q, mpctl);
19202 
19203 	/* ipv6NetToMediaEntryTable in mp3ctl */
19204 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19205 
19206 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19207 	optp->level = MIB2_IP6;
19208 	optp->name = MIB2_IP6_MEDIA;
19209 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19210 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19211 	    (int)optp->level, (int)optp->name, (int)optp->len));
19212 	qreply(q, mp3ctl);
19213 
19214 	/* ipv6RouteAttributeTable in mp4ctl */
19215 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19216 	optp->level = MIB2_IP6;
19217 	optp->name = EXPER_IP_RTATTR;
19218 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19219 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19220 	    (int)optp->level, (int)optp->name, (int)optp->len));
19221 	if (optp->len == 0)
19222 		freemsg(mp4ctl);
19223 	else
19224 		qreply(q, mp4ctl);
19225 
19226 	return (mp2ctl);
19227 }
19228 
19229 /*
19230  * IPv6 mib: One per ill
19231  */
19232 static mblk_t *
19233 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19234 {
19235 	struct opthdr		*optp;
19236 	mblk_t			*mp2ctl;
19237 	ill_t			*ill;
19238 	ill_walk_context_t	ctx;
19239 	mblk_t			*mp_tail = NULL;
19240 
19241 	/*
19242 	 * Make a copy of the original message
19243 	 */
19244 	mp2ctl = copymsg(mpctl);
19245 
19246 	/* fixed length IPv6 structure ... */
19247 
19248 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19249 	optp->level = MIB2_IP6;
19250 	optp->name = 0;
19251 	/* Include "unknown interface" ip6_mib */
19252 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19253 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19254 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19255 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19256 	    ipst->ips_ipv6_forward ? 1 : 2);
19257 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19258 	    ipst->ips_ipv6_def_hops);
19259 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19260 	    sizeof (mib2_ipIfStatsEntry_t));
19261 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19262 	    sizeof (mib2_ipv6AddrEntry_t));
19263 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19264 	    sizeof (mib2_ipv6RouteEntry_t));
19265 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19266 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19267 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19268 	    sizeof (ipv6_member_t));
19269 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19270 	    sizeof (ipv6_grpsrc_t));
19271 
19272 	/*
19273 	 * Synchronize 64- and 32-bit counters
19274 	 */
19275 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19276 	    ipIfStatsHCInReceives);
19277 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19278 	    ipIfStatsHCInDelivers);
19279 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19280 	    ipIfStatsHCOutRequests);
19281 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19282 	    ipIfStatsHCOutForwDatagrams);
19283 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19284 	    ipIfStatsHCOutMcastPkts);
19285 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19286 	    ipIfStatsHCInMcastPkts);
19287 
19288 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19289 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19290 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19291 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19292 	}
19293 
19294 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19295 	ill = ILL_START_WALK_V6(&ctx, ipst);
19296 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19297 		ill->ill_ip_mib->ipIfStatsIfIndex =
19298 		    ill->ill_phyint->phyint_ifindex;
19299 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19300 		    ipst->ips_ipv6_forward ? 1 : 2);
19301 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19302 		    ill->ill_max_hops);
19303 
19304 		/*
19305 		 * Synchronize 64- and 32-bit counters
19306 		 */
19307 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19308 		    ipIfStatsHCInReceives);
19309 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19310 		    ipIfStatsHCInDelivers);
19311 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19312 		    ipIfStatsHCOutRequests);
19313 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19314 		    ipIfStatsHCOutForwDatagrams);
19315 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19316 		    ipIfStatsHCOutMcastPkts);
19317 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19318 		    ipIfStatsHCInMcastPkts);
19319 
19320 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19321 		    (char *)ill->ill_ip_mib,
19322 		    (int)sizeof (*ill->ill_ip_mib))) {
19323 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19324 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19325 		}
19326 	}
19327 	rw_exit(&ipst->ips_ill_g_lock);
19328 
19329 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19330 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19331 	    (int)optp->level, (int)optp->name, (int)optp->len));
19332 	qreply(q, mpctl);
19333 	return (mp2ctl);
19334 }
19335 
19336 /*
19337  * ICMPv6 mib: One per ill
19338  */
19339 static mblk_t *
19340 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19341 {
19342 	struct opthdr		*optp;
19343 	mblk_t			*mp2ctl;
19344 	ill_t			*ill;
19345 	ill_walk_context_t	ctx;
19346 	mblk_t			*mp_tail = NULL;
19347 	/*
19348 	 * Make a copy of the original message
19349 	 */
19350 	mp2ctl = copymsg(mpctl);
19351 
19352 	/* fixed length ICMPv6 structure ... */
19353 
19354 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19355 	optp->level = MIB2_ICMP6;
19356 	optp->name = 0;
19357 	/* Include "unknown interface" icmp6_mib */
19358 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19359 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19360 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19361 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19362 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19363 	    (char *)&ipst->ips_icmp6_mib,
19364 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19365 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19366 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19367 	}
19368 
19369 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19370 	ill = ILL_START_WALK_V6(&ctx, ipst);
19371 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19372 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19373 		    ill->ill_phyint->phyint_ifindex;
19374 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19375 		    (char *)ill->ill_icmp6_mib,
19376 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19377 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19378 			    "%u bytes\n",
19379 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19380 		}
19381 	}
19382 	rw_exit(&ipst->ips_ill_g_lock);
19383 
19384 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19385 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19386 	    (int)optp->level, (int)optp->name, (int)optp->len));
19387 	qreply(q, mpctl);
19388 	return (mp2ctl);
19389 }
19390 
19391 /*
19392  * ire_walk routine to create both ipRouteEntryTable and
19393  * ipRouteAttributeTable in one IRE walk
19394  */
19395 static void
19396 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19397 {
19398 	ill_t				*ill;
19399 	ipif_t				*ipif;
19400 	mib2_ipRouteEntry_t		*re;
19401 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19402 	ipaddr_t			gw_addr;
19403 	tsol_ire_gw_secattr_t		*attrp;
19404 	tsol_gc_t			*gc = NULL;
19405 	tsol_gcgrp_t			*gcgrp = NULL;
19406 	uint_t				sacnt = 0;
19407 	int				i;
19408 
19409 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19410 
19411 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19412 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19413 		return;
19414 	}
19415 
19416 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19417 		return;
19418 
19419 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19420 		mutex_enter(&attrp->igsa_lock);
19421 		if ((gc = attrp->igsa_gc) != NULL) {
19422 			gcgrp = gc->gc_grp;
19423 			ASSERT(gcgrp != NULL);
19424 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19425 			sacnt = 1;
19426 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19427 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19428 			gc = gcgrp->gcgrp_head;
19429 			sacnt = gcgrp->gcgrp_count;
19430 		}
19431 		mutex_exit(&attrp->igsa_lock);
19432 
19433 		/* do nothing if there's no gc to report */
19434 		if (gc == NULL) {
19435 			ASSERT(sacnt == 0);
19436 			if (gcgrp != NULL) {
19437 				/* we might as well drop the lock now */
19438 				rw_exit(&gcgrp->gcgrp_rwlock);
19439 				gcgrp = NULL;
19440 			}
19441 			attrp = NULL;
19442 		}
19443 
19444 		ASSERT(gc == NULL || (gcgrp != NULL &&
19445 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19446 	}
19447 	ASSERT(sacnt == 0 || gc != NULL);
19448 
19449 	if (sacnt != 0 &&
19450 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19451 		kmem_free(re, sizeof (*re));
19452 		rw_exit(&gcgrp->gcgrp_rwlock);
19453 		return;
19454 	}
19455 
19456 	/*
19457 	 * Return all IRE types for route table... let caller pick and choose
19458 	 */
19459 	re->ipRouteDest = ire->ire_addr;
19460 	ipif = ire->ire_ipif;
19461 	re->ipRouteIfIndex.o_length = 0;
19462 	if (ire->ire_type == IRE_CACHE) {
19463 		ill = (ill_t *)ire->ire_stq->q_ptr;
19464 		re->ipRouteIfIndex.o_length =
19465 		    ill->ill_name_length == 0 ? 0 :
19466 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19467 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19468 		    re->ipRouteIfIndex.o_length);
19469 	} else if (ipif != NULL) {
19470 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19471 		re->ipRouteIfIndex.o_length =
19472 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19473 	}
19474 	re->ipRouteMetric1 = -1;
19475 	re->ipRouteMetric2 = -1;
19476 	re->ipRouteMetric3 = -1;
19477 	re->ipRouteMetric4 = -1;
19478 
19479 	gw_addr = ire->ire_gateway_addr;
19480 
19481 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19482 		re->ipRouteNextHop = ire->ire_src_addr;
19483 	else
19484 		re->ipRouteNextHop = gw_addr;
19485 	/* indirect(4), direct(3), or invalid(2) */
19486 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19487 		re->ipRouteType = 2;
19488 	else
19489 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19490 	re->ipRouteProto = -1;
19491 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19492 	re->ipRouteMask = ire->ire_mask;
19493 	re->ipRouteMetric5 = -1;
19494 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19495 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19496 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19497 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19498 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19499 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19500 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19501 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19502 
19503 	if (ire->ire_flags & RTF_DYNAMIC) {
19504 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19505 	} else {
19506 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19507 	}
19508 
19509 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19510 	    (char *)re, (int)sizeof (*re))) {
19511 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19512 		    (uint_t)sizeof (*re)));
19513 	}
19514 
19515 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19516 		iaeptr->iae_routeidx = ird->ird_idx;
19517 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19518 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19519 	}
19520 
19521 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19522 	    (char *)iae, sacnt * sizeof (*iae))) {
19523 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19524 		    (unsigned)(sacnt * sizeof (*iae))));
19525 	}
19526 
19527 	/* bump route index for next pass */
19528 	ird->ird_idx++;
19529 
19530 	kmem_free(re, sizeof (*re));
19531 	if (sacnt != 0)
19532 		kmem_free(iae, sacnt * sizeof (*iae));
19533 
19534 	if (gcgrp != NULL)
19535 		rw_exit(&gcgrp->gcgrp_rwlock);
19536 }
19537 
19538 /*
19539  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19540  */
19541 static void
19542 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19543 {
19544 	ill_t				*ill;
19545 	ipif_t				*ipif;
19546 	mib2_ipv6RouteEntry_t		*re;
19547 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19548 	in6_addr_t			gw_addr_v6;
19549 	tsol_ire_gw_secattr_t		*attrp;
19550 	tsol_gc_t			*gc = NULL;
19551 	tsol_gcgrp_t			*gcgrp = NULL;
19552 	uint_t				sacnt = 0;
19553 	int				i;
19554 
19555 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19556 
19557 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19558 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19559 		return;
19560 	}
19561 
19562 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19563 		return;
19564 
19565 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19566 		mutex_enter(&attrp->igsa_lock);
19567 		if ((gc = attrp->igsa_gc) != NULL) {
19568 			gcgrp = gc->gc_grp;
19569 			ASSERT(gcgrp != NULL);
19570 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19571 			sacnt = 1;
19572 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19573 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19574 			gc = gcgrp->gcgrp_head;
19575 			sacnt = gcgrp->gcgrp_count;
19576 		}
19577 		mutex_exit(&attrp->igsa_lock);
19578 
19579 		/* do nothing if there's no gc to report */
19580 		if (gc == NULL) {
19581 			ASSERT(sacnt == 0);
19582 			if (gcgrp != NULL) {
19583 				/* we might as well drop the lock now */
19584 				rw_exit(&gcgrp->gcgrp_rwlock);
19585 				gcgrp = NULL;
19586 			}
19587 			attrp = NULL;
19588 		}
19589 
19590 		ASSERT(gc == NULL || (gcgrp != NULL &&
19591 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19592 	}
19593 	ASSERT(sacnt == 0 || gc != NULL);
19594 
19595 	if (sacnt != 0 &&
19596 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19597 		kmem_free(re, sizeof (*re));
19598 		rw_exit(&gcgrp->gcgrp_rwlock);
19599 		return;
19600 	}
19601 
19602 	/*
19603 	 * Return all IRE types for route table... let caller pick and choose
19604 	 */
19605 	re->ipv6RouteDest = ire->ire_addr_v6;
19606 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19607 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19608 	re->ipv6RouteIfIndex.o_length = 0;
19609 	ipif = ire->ire_ipif;
19610 	if (ire->ire_type == IRE_CACHE) {
19611 		ill = (ill_t *)ire->ire_stq->q_ptr;
19612 		re->ipv6RouteIfIndex.o_length =
19613 		    ill->ill_name_length == 0 ? 0 :
19614 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19615 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19616 		    re->ipv6RouteIfIndex.o_length);
19617 	} else if (ipif != NULL) {
19618 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19619 		re->ipv6RouteIfIndex.o_length =
19620 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19621 	}
19622 
19623 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19624 
19625 	mutex_enter(&ire->ire_lock);
19626 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19627 	mutex_exit(&ire->ire_lock);
19628 
19629 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19630 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19631 	else
19632 		re->ipv6RouteNextHop = gw_addr_v6;
19633 
19634 	/* remote(4), local(3), or discard(2) */
19635 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19636 		re->ipv6RouteType = 2;
19637 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19638 		re->ipv6RouteType = 3;
19639 	else
19640 		re->ipv6RouteType = 4;
19641 
19642 	re->ipv6RouteProtocol	= -1;
19643 	re->ipv6RoutePolicy	= 0;
19644 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19645 	re->ipv6RouteNextHopRDI	= 0;
19646 	re->ipv6RouteWeight	= 0;
19647 	re->ipv6RouteMetric	= 0;
19648 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19649 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19650 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19651 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19652 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19653 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19654 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19655 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19656 
19657 	if (ire->ire_flags & RTF_DYNAMIC) {
19658 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19659 	} else {
19660 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19661 	}
19662 
19663 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19664 	    (char *)re, (int)sizeof (*re))) {
19665 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19666 		    (uint_t)sizeof (*re)));
19667 	}
19668 
19669 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19670 		iaeptr->iae_routeidx = ird->ird_idx;
19671 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19672 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19673 	}
19674 
19675 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19676 	    (char *)iae, sacnt * sizeof (*iae))) {
19677 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19678 		    (unsigned)(sacnt * sizeof (*iae))));
19679 	}
19680 
19681 	/* bump route index for next pass */
19682 	ird->ird_idx++;
19683 
19684 	kmem_free(re, sizeof (*re));
19685 	if (sacnt != 0)
19686 		kmem_free(iae, sacnt * sizeof (*iae));
19687 
19688 	if (gcgrp != NULL)
19689 		rw_exit(&gcgrp->gcgrp_rwlock);
19690 }
19691 
19692 /*
19693  * ndp_walk routine to create ipv6NetToMediaEntryTable
19694  */
19695 static int
19696 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19697 {
19698 	ill_t				*ill;
19699 	mib2_ipv6NetToMediaEntry_t	ntme;
19700 	dl_unitdata_req_t		*dl;
19701 
19702 	ill = nce->nce_ill;
19703 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19704 		return (0);
19705 
19706 	/*
19707 	 * Neighbor cache entry attached to IRE with on-link
19708 	 * destination.
19709 	 */
19710 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19711 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19712 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19713 	    (nce->nce_res_mp != NULL)) {
19714 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19715 		ntme.ipv6NetToMediaPhysAddress.o_length =
19716 		    dl->dl_dest_addr_length;
19717 	} else {
19718 		ntme.ipv6NetToMediaPhysAddress.o_length =
19719 		    ill->ill_phys_addr_length;
19720 	}
19721 	if (nce->nce_res_mp != NULL) {
19722 		bcopy((char *)nce->nce_res_mp->b_rptr +
19723 		    NCE_LL_ADDR_OFFSET(ill),
19724 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19725 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19726 	} else {
19727 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19728 		    ill->ill_phys_addr_length);
19729 	}
19730 	/*
19731 	 * Note: Returns ND_* states. Should be:
19732 	 * reachable(1), stale(2), delay(3), probe(4),
19733 	 * invalid(5), unknown(6)
19734 	 */
19735 	ntme.ipv6NetToMediaState = nce->nce_state;
19736 	ntme.ipv6NetToMediaLastUpdated = 0;
19737 
19738 	/* other(1), dynamic(2), static(3), local(4) */
19739 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19740 		ntme.ipv6NetToMediaType = 4;
19741 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19742 		ntme.ipv6NetToMediaType = 1;
19743 	} else {
19744 		ntme.ipv6NetToMediaType = 2;
19745 	}
19746 
19747 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19748 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19749 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19750 		    (uint_t)sizeof (ntme)));
19751 	}
19752 	return (0);
19753 }
19754 
19755 /*
19756  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19757  */
19758 /* ARGSUSED */
19759 int
19760 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19761 {
19762 	switch (level) {
19763 	case MIB2_IP:
19764 	case MIB2_ICMP:
19765 		switch (name) {
19766 		default:
19767 			break;
19768 		}
19769 		return (1);
19770 	default:
19771 		return (1);
19772 	}
19773 }
19774 
19775 /*
19776  * When there exists both a 64- and 32-bit counter of a particular type
19777  * (i.e., InReceives), only the 64-bit counters are added.
19778  */
19779 void
19780 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19781 {
19782 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19783 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19784 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19785 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19786 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19787 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19788 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19789 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19790 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19791 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19792 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19793 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19794 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19795 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19796 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19797 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19798 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19799 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19800 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19801 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19802 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19803 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19804 	    o2->ipIfStatsInWrongIPVersion);
19805 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19806 	    o2->ipIfStatsInWrongIPVersion);
19807 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19808 	    o2->ipIfStatsOutSwitchIPVersion);
19809 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19810 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19811 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19812 	    o2->ipIfStatsHCInForwDatagrams);
19813 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19814 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19815 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19816 	    o2->ipIfStatsHCOutForwDatagrams);
19817 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19818 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19819 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19820 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19821 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19822 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19823 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19824 	    o2->ipIfStatsHCOutMcastOctets);
19825 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19826 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19827 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19828 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19829 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19830 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19831 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19832 }
19833 
19834 void
19835 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19836 {
19837 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19838 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19839 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19840 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19841 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19842 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19843 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19844 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19845 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19846 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19847 	    o2->ipv6IfIcmpInRouterSolicits);
19848 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19849 	    o2->ipv6IfIcmpInRouterAdvertisements);
19850 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19851 	    o2->ipv6IfIcmpInNeighborSolicits);
19852 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19853 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19854 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19855 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19856 	    o2->ipv6IfIcmpInGroupMembQueries);
19857 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19858 	    o2->ipv6IfIcmpInGroupMembResponses);
19859 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19860 	    o2->ipv6IfIcmpInGroupMembReductions);
19861 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19862 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19863 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19864 	    o2->ipv6IfIcmpOutDestUnreachs);
19865 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19866 	    o2->ipv6IfIcmpOutAdminProhibs);
19867 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19868 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19869 	    o2->ipv6IfIcmpOutParmProblems);
19870 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19871 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19872 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19873 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19874 	    o2->ipv6IfIcmpOutRouterSolicits);
19875 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19876 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19877 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19878 	    o2->ipv6IfIcmpOutNeighborSolicits);
19879 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19880 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19881 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19882 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19883 	    o2->ipv6IfIcmpOutGroupMembQueries);
19884 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19885 	    o2->ipv6IfIcmpOutGroupMembResponses);
19886 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19887 	    o2->ipv6IfIcmpOutGroupMembReductions);
19888 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19889 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19890 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19891 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19892 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19893 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19894 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19895 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19896 	    o2->ipv6IfIcmpInGroupMembTotal);
19897 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19898 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19899 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19900 	    o2->ipv6IfIcmpInGroupMembBadReports);
19901 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19902 	    o2->ipv6IfIcmpInGroupMembOurReports);
19903 }
19904 
19905 /*
19906  * Called before the options are updated to check if this packet will
19907  * be source routed from here.
19908  * This routine assumes that the options are well formed i.e. that they
19909  * have already been checked.
19910  */
19911 static boolean_t
19912 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19913 {
19914 	ipoptp_t	opts;
19915 	uchar_t		*opt;
19916 	uint8_t		optval;
19917 	uint8_t		optlen;
19918 	ipaddr_t	dst;
19919 	ire_t		*ire;
19920 
19921 	if (IS_SIMPLE_IPH(ipha)) {
19922 		ip2dbg(("not source routed\n"));
19923 		return (B_FALSE);
19924 	}
19925 	dst = ipha->ipha_dst;
19926 	for (optval = ipoptp_first(&opts, ipha);
19927 	    optval != IPOPT_EOL;
19928 	    optval = ipoptp_next(&opts)) {
19929 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19930 		opt = opts.ipoptp_cur;
19931 		optlen = opts.ipoptp_len;
19932 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19933 		    optval, optlen));
19934 		switch (optval) {
19935 			uint32_t off;
19936 		case IPOPT_SSRR:
19937 		case IPOPT_LSRR:
19938 			/*
19939 			 * If dst is one of our addresses and there are some
19940 			 * entries left in the source route return (true).
19941 			 */
19942 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19943 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19944 			if (ire == NULL) {
19945 				ip2dbg(("ip_source_routed: not next"
19946 				    " source route 0x%x\n",
19947 				    ntohl(dst)));
19948 				return (B_FALSE);
19949 			}
19950 			ire_refrele(ire);
19951 			off = opt[IPOPT_OFFSET];
19952 			off--;
19953 			if (optlen < IP_ADDR_LEN ||
19954 			    off > optlen - IP_ADDR_LEN) {
19955 				/* End of source route */
19956 				ip1dbg(("ip_source_routed: end of SR\n"));
19957 				return (B_FALSE);
19958 			}
19959 			return (B_TRUE);
19960 		}
19961 	}
19962 	ip2dbg(("not source routed\n"));
19963 	return (B_FALSE);
19964 }
19965 
19966 /*
19967  * Check if the packet contains any source route.
19968  */
19969 static boolean_t
19970 ip_source_route_included(ipha_t *ipha)
19971 {
19972 	ipoptp_t	opts;
19973 	uint8_t		optval;
19974 
19975 	if (IS_SIMPLE_IPH(ipha))
19976 		return (B_FALSE);
19977 	for (optval = ipoptp_first(&opts, ipha);
19978 	    optval != IPOPT_EOL;
19979 	    optval = ipoptp_next(&opts)) {
19980 		switch (optval) {
19981 		case IPOPT_SSRR:
19982 		case IPOPT_LSRR:
19983 			return (B_TRUE);
19984 		}
19985 	}
19986 	return (B_FALSE);
19987 }
19988 
19989 /*
19990  * Called when the IRE expiration timer fires.
19991  */
19992 void
19993 ip_trash_timer_expire(void *args)
19994 {
19995 	int			flush_flag = 0;
19996 	ire_expire_arg_t	iea;
19997 	ip_stack_t		*ipst = (ip_stack_t *)args;
19998 
19999 	iea.iea_ipst = ipst;	/* No netstack_hold */
20000 
20001 	/*
20002 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
20003 	 * This lock makes sure that a new invocation of this function
20004 	 * that occurs due to an almost immediate timer firing will not
20005 	 * progress beyond this point until the current invocation is done
20006 	 */
20007 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20008 	ipst->ips_ip_ire_expire_id = 0;
20009 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20010 
20011 	/* Periodic timer */
20012 	if (ipst->ips_ip_ire_arp_time_elapsed >=
20013 	    ipst->ips_ip_ire_arp_interval) {
20014 		/*
20015 		 * Remove all IRE_CACHE entries since they might
20016 		 * contain arp information.
20017 		 */
20018 		flush_flag |= FLUSH_ARP_TIME;
20019 		ipst->ips_ip_ire_arp_time_elapsed = 0;
20020 		IP_STAT(ipst, ip_ire_arp_timer_expired);
20021 	}
20022 	if (ipst->ips_ip_ire_rd_time_elapsed >=
20023 	    ipst->ips_ip_ire_redir_interval) {
20024 		/* Remove all redirects */
20025 		flush_flag |= FLUSH_REDIRECT_TIME;
20026 		ipst->ips_ip_ire_rd_time_elapsed = 0;
20027 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
20028 	}
20029 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
20030 	    ipst->ips_ip_ire_pathmtu_interval) {
20031 		/* Increase path mtu */
20032 		flush_flag |= FLUSH_MTU_TIME;
20033 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20034 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20035 	}
20036 
20037 	/*
20038 	 * Optimize for the case when there are no redirects in the
20039 	 * ftable, that is, no need to walk the ftable in that case.
20040 	 */
20041 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20042 		iea.iea_flush_flag = flush_flag;
20043 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20044 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20045 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20046 		    NULL, ALL_ZONES, ipst);
20047 	}
20048 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20049 	    ipst->ips_ip_redirect_cnt > 0) {
20050 		iea.iea_flush_flag = flush_flag;
20051 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20052 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20053 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20054 	}
20055 	if (flush_flag & FLUSH_MTU_TIME) {
20056 		/*
20057 		 * Walk all IPv6 IRE's and update them
20058 		 * Note that ARP and redirect timers are not
20059 		 * needed since NUD handles stale entries.
20060 		 */
20061 		flush_flag = FLUSH_MTU_TIME;
20062 		iea.iea_flush_flag = flush_flag;
20063 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20064 		    ALL_ZONES, ipst);
20065 	}
20066 
20067 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20068 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20069 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20070 
20071 	/*
20072 	 * Hold the lock to serialize timeout calls and prevent
20073 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20074 	 * for the timer to fire and a new invocation of this function
20075 	 * to start before the return value of timeout has been stored
20076 	 * in ip_ire_expire_id by the current invocation.
20077 	 */
20078 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20079 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20080 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20081 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20082 }
20083 
20084 /*
20085  * Called by the memory allocator subsystem directly, when the system
20086  * is running low on memory.
20087  */
20088 /* ARGSUSED */
20089 void
20090 ip_trash_ire_reclaim(void *args)
20091 {
20092 	netstack_handle_t nh;
20093 	netstack_t *ns;
20094 
20095 	netstack_next_init(&nh);
20096 	while ((ns = netstack_next(&nh)) != NULL) {
20097 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20098 		netstack_rele(ns);
20099 	}
20100 	netstack_next_fini(&nh);
20101 }
20102 
20103 static void
20104 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20105 {
20106 	ire_cache_count_t icc;
20107 	ire_cache_reclaim_t icr;
20108 	ncc_cache_count_t ncc;
20109 	nce_cache_reclaim_t ncr;
20110 	uint_t delete_cnt;
20111 	/*
20112 	 * Memory reclaim call back.
20113 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20114 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20115 	 * entries, determine what fraction to free for
20116 	 * each category of IRE_CACHE entries giving absolute priority
20117 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20118 	 * entry will be freed unless all offlink entries are freed).
20119 	 */
20120 	icc.icc_total = 0;
20121 	icc.icc_unused = 0;
20122 	icc.icc_offlink = 0;
20123 	icc.icc_pmtu = 0;
20124 	icc.icc_onlink = 0;
20125 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20126 
20127 	/*
20128 	 * Free NCEs for IPv6 like the onlink ires.
20129 	 */
20130 	ncc.ncc_total = 0;
20131 	ncc.ncc_host = 0;
20132 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20133 
20134 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20135 	    icc.icc_pmtu + icc.icc_onlink);
20136 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20137 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20138 	if (delete_cnt == 0)
20139 		return;
20140 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20141 	/* Always delete all unused offlink entries */
20142 	icr.icr_ipst = ipst;
20143 	icr.icr_unused = 1;
20144 	if (delete_cnt <= icc.icc_unused) {
20145 		/*
20146 		 * Only need to free unused entries.  In other words,
20147 		 * there are enough unused entries to free to meet our
20148 		 * target number of freed ire cache entries.
20149 		 */
20150 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20151 		ncr.ncr_host = 0;
20152 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20153 		/*
20154 		 * Only need to free unused entries, plus a fraction of offlink
20155 		 * entries.  It follows from the first if statement that
20156 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20157 		 */
20158 		delete_cnt -= icc.icc_unused;
20159 		/* Round up # deleted by truncating fraction */
20160 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20161 		icr.icr_pmtu = icr.icr_onlink = 0;
20162 		ncr.ncr_host = 0;
20163 	} else if (delete_cnt <=
20164 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20165 		/*
20166 		 * Free all unused and offlink entries, plus a fraction of
20167 		 * pmtu entries.  It follows from the previous if statement
20168 		 * that icc_pmtu is non-zero, and that
20169 		 * delete_cnt != icc_unused + icc_offlink.
20170 		 */
20171 		icr.icr_offlink = 1;
20172 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20173 		/* Round up # deleted by truncating fraction */
20174 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20175 		icr.icr_onlink = 0;
20176 		ncr.ncr_host = 0;
20177 	} else {
20178 		/*
20179 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20180 		 * of onlink entries.  If we're here, then we know that
20181 		 * icc_onlink is non-zero, and that
20182 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20183 		 */
20184 		icr.icr_offlink = icr.icr_pmtu = 1;
20185 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20186 		    icc.icc_pmtu;
20187 		/* Round up # deleted by truncating fraction */
20188 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20189 		/* Using the same delete fraction as for onlink IREs */
20190 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20191 	}
20192 #ifdef DEBUG
20193 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20194 	    "fractions %d/%d/%d/%d\n",
20195 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20196 	    icc.icc_unused, icc.icc_offlink,
20197 	    icc.icc_pmtu, icc.icc_onlink,
20198 	    icr.icr_unused, icr.icr_offlink,
20199 	    icr.icr_pmtu, icr.icr_onlink));
20200 #endif
20201 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20202 	if (ncr.ncr_host != 0)
20203 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20204 		    (uchar_t *)&ncr, ipst);
20205 #ifdef DEBUG
20206 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20207 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20208 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20209 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20210 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20211 	    icc.icc_pmtu, icc.icc_onlink));
20212 #endif
20213 }
20214 
20215 /*
20216  * ip_unbind is called when a copy of an unbind request is received from the
20217  * upper level protocol.  We remove this conn from any fanout hash list it is
20218  * on, and zero out the bind information.  No reply is expected up above.
20219  */
20220 void
20221 ip_unbind(conn_t *connp)
20222 {
20223 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20224 
20225 	if (is_system_labeled() && connp->conn_anon_port) {
20226 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20227 		    connp->conn_mlp_type, connp->conn_ulp,
20228 		    ntohs(connp->conn_lport), B_FALSE);
20229 		connp->conn_anon_port = 0;
20230 	}
20231 	connp->conn_mlp_type = mlptSingle;
20232 
20233 	ipcl_hash_remove(connp);
20234 
20235 }
20236 
20237 /*
20238  * Write side put procedure.  Outbound data, IOCTLs, responses from
20239  * resolvers, etc, come down through here.
20240  *
20241  * arg2 is always a queue_t *.
20242  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20243  * the zoneid.
20244  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20245  */
20246 void
20247 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20248 {
20249 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20250 }
20251 
20252 void
20253 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20254     ip_opt_info_t *infop)
20255 {
20256 	conn_t		*connp = NULL;
20257 	queue_t		*q = (queue_t *)arg2;
20258 	ipha_t		*ipha;
20259 #define	rptr	((uchar_t *)ipha)
20260 	ire_t		*ire = NULL;
20261 	ire_t		*sctp_ire = NULL;
20262 	uint32_t	v_hlen_tos_len;
20263 	ipaddr_t	dst;
20264 	mblk_t		*first_mp = NULL;
20265 	boolean_t	mctl_present;
20266 	ipsec_out_t	*io;
20267 	int		match_flags;
20268 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20269 	ipif_t		*dst_ipif;
20270 	boolean_t	multirt_need_resolve = B_FALSE;
20271 	mblk_t		*copy_mp = NULL;
20272 	int		err;
20273 	zoneid_t	zoneid;
20274 	boolean_t	need_decref = B_FALSE;
20275 	boolean_t	ignore_dontroute = B_FALSE;
20276 	boolean_t	ignore_nexthop = B_FALSE;
20277 	boolean_t	ip_nexthop = B_FALSE;
20278 	ipaddr_t	nexthop_addr;
20279 	ip_stack_t	*ipst;
20280 
20281 #ifdef	_BIG_ENDIAN
20282 #define	V_HLEN	(v_hlen_tos_len >> 24)
20283 #else
20284 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20285 #endif
20286 
20287 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20288 	    "ip_wput_start: q %p", q);
20289 
20290 	/*
20291 	 * ip_wput fast path
20292 	 */
20293 
20294 	/* is packet from ARP ? */
20295 	if (q->q_next != NULL) {
20296 		zoneid = (zoneid_t)(uintptr_t)arg;
20297 		goto qnext;
20298 	}
20299 
20300 	connp = (conn_t *)arg;
20301 	ASSERT(connp != NULL);
20302 	zoneid = connp->conn_zoneid;
20303 	ipst = connp->conn_netstack->netstack_ip;
20304 	ASSERT(ipst != NULL);
20305 
20306 	/* is queue flow controlled? */
20307 	if ((q->q_first != NULL || connp->conn_draining) &&
20308 	    (caller == IP_WPUT)) {
20309 		ASSERT(!need_decref);
20310 		ASSERT(!IP_FLOW_CONTROLLED_ULP(connp->conn_ulp));
20311 		(void) putq(q, mp);
20312 		return;
20313 	}
20314 
20315 	/* Multidata transmit? */
20316 	if (DB_TYPE(mp) == M_MULTIDATA) {
20317 		/*
20318 		 * We should never get here, since all Multidata messages
20319 		 * originating from tcp should have been directed over to
20320 		 * tcp_multisend() in the first place.
20321 		 */
20322 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20323 		freemsg(mp);
20324 		return;
20325 	} else if (DB_TYPE(mp) != M_DATA)
20326 		goto notdata;
20327 
20328 	if (mp->b_flag & MSGHASREF) {
20329 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20330 		mp->b_flag &= ~MSGHASREF;
20331 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20332 		need_decref = B_TRUE;
20333 	}
20334 	ipha = (ipha_t *)mp->b_rptr;
20335 
20336 	/* is IP header non-aligned or mblk smaller than basic IP header */
20337 #ifndef SAFETY_BEFORE_SPEED
20338 	if (!OK_32PTR(rptr) ||
20339 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20340 		goto hdrtoosmall;
20341 #endif
20342 
20343 	ASSERT(OK_32PTR(ipha));
20344 
20345 	/*
20346 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20347 	 * wrong version, we'll catch it again in ip_output_v6.
20348 	 *
20349 	 * Note that this is *only* locally-generated output here, and never
20350 	 * forwarded data, and that we need to deal only with transports that
20351 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20352 	 * label.)
20353 	 */
20354 	if (is_system_labeled() &&
20355 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20356 	    !connp->conn_ulp_labeled) {
20357 		err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20358 		    connp->conn_mac_exempt, ipst);
20359 		ipha = (ipha_t *)mp->b_rptr;
20360 		if (err != 0) {
20361 			first_mp = mp;
20362 			if (err == EINVAL)
20363 				goto icmp_parameter_problem;
20364 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20365 			goto discard_pkt;
20366 		}
20367 	}
20368 
20369 	ASSERT(infop != NULL);
20370 
20371 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20372 		/*
20373 		 * IP_PKTINFO ancillary option is present.
20374 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20375 		 * allows using address of any zone as the source address.
20376 		 */
20377 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20378 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20379 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20380 		if (ire == NULL)
20381 			goto drop_pkt;
20382 		ire_refrele(ire);
20383 		ire = NULL;
20384 	}
20385 
20386 	/*
20387 	 * IP_BOUND_IF has precedence over the ill index passed in IP_PKTINFO.
20388 	 */
20389 	if (infop->ip_opt_ill_index != 0 && connp->conn_outgoing_ill == NULL) {
20390 		xmit_ill = ill_lookup_on_ifindex(infop->ip_opt_ill_index,
20391 		    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20392 
20393 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20394 			goto drop_pkt;
20395 		/*
20396 		 * check that there is an ipif belonging
20397 		 * to our zone. IPCL_ZONEID is not used because
20398 		 * IP_ALLZONES option is valid only when the ill is
20399 		 * accessible from all zones i.e has a valid ipif in
20400 		 * all zones.
20401 		 */
20402 		if (!ipif_lookup_zoneid(xmit_ill, zoneid, 0, NULL)) {
20403 			goto drop_pkt;
20404 		}
20405 	}
20406 
20407 	/*
20408 	 * If there is a policy, try to attach an ipsec_out in
20409 	 * the front. At the end, first_mp either points to a
20410 	 * M_DATA message or IPSEC_OUT message linked to a
20411 	 * M_DATA message. We have to do it now as we might
20412 	 * lose the "conn" if we go through ip_newroute.
20413 	 */
20414 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20415 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20416 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20417 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20418 			if (need_decref)
20419 				CONN_DEC_REF(connp);
20420 			return;
20421 		} else {
20422 			ASSERT(mp->b_datap->db_type == M_CTL);
20423 			first_mp = mp;
20424 			mp = mp->b_cont;
20425 			mctl_present = B_TRUE;
20426 		}
20427 	} else {
20428 		first_mp = mp;
20429 		mctl_present = B_FALSE;
20430 	}
20431 
20432 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20433 
20434 	/* is wrong version or IP options present */
20435 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20436 		goto version_hdrlen_check;
20437 	dst = ipha->ipha_dst;
20438 
20439 	/* If IP_BOUND_IF has been set, use that ill. */
20440 	if (connp->conn_outgoing_ill != NULL) {
20441 		xmit_ill = conn_get_held_ill(connp,
20442 		    &connp->conn_outgoing_ill, &err);
20443 		if (err == ILL_LOOKUP_FAILED)
20444 			goto drop_pkt;
20445 
20446 		goto send_from_ill;
20447 	}
20448 
20449 	/* is packet multicast? */
20450 	if (CLASSD(dst))
20451 		goto multicast;
20452 
20453 	/*
20454 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20455 	 * takes precedence over conn_dontroute and conn_nexthop_set
20456 	 */
20457 	if (xmit_ill != NULL)
20458 		goto send_from_ill;
20459 
20460 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20461 		/*
20462 		 * If the destination is a broadcast, local, or loopback
20463 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20464 		 * standard path.
20465 		 */
20466 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20467 		if ((ire == NULL) || (ire->ire_type &
20468 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20469 			if (ire != NULL) {
20470 				ire_refrele(ire);
20471 				/* No more access to ire */
20472 				ire = NULL;
20473 			}
20474 			/*
20475 			 * bypass routing checks and go directly to interface.
20476 			 */
20477 			if (connp->conn_dontroute)
20478 				goto dontroute;
20479 
20480 			ASSERT(connp->conn_nexthop_set);
20481 			ip_nexthop = B_TRUE;
20482 			nexthop_addr = connp->conn_nexthop_v4;
20483 			goto send_from_ill;
20484 		}
20485 
20486 		/* Must be a broadcast, a loopback or a local ire */
20487 		ire_refrele(ire);
20488 		/* No more access to ire */
20489 		ire = NULL;
20490 	}
20491 
20492 	/*
20493 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20494 	 * this for the tcp global queue and listen end point
20495 	 * as it does not really have a real destination to
20496 	 * talk to.  This is also true for SCTP.
20497 	 */
20498 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20499 	    !connp->conn_fully_bound) {
20500 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20501 		if (ire == NULL)
20502 			goto noirefound;
20503 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20504 		    "ip_wput_end: q %p (%S)", q, "end");
20505 
20506 		/*
20507 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20508 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20509 		 */
20510 		if (ire->ire_flags & RTF_MULTIRT) {
20511 
20512 			/*
20513 			 * Force the TTL of multirouted packets if required.
20514 			 * The TTL of such packets is bounded by the
20515 			 * ip_multirt_ttl ndd variable.
20516 			 */
20517 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20518 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20519 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20520 				    "(was %d), dst 0x%08x\n",
20521 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20522 				    ntohl(ire->ire_addr)));
20523 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20524 			}
20525 			/*
20526 			 * We look at this point if there are pending
20527 			 * unresolved routes. ire_multirt_resolvable()
20528 			 * checks in O(n) that all IRE_OFFSUBNET ire
20529 			 * entries for the packet's destination and
20530 			 * flagged RTF_MULTIRT are currently resolved.
20531 			 * If some remain unresolved, we make a copy
20532 			 * of the current message. It will be used
20533 			 * to initiate additional route resolutions.
20534 			 */
20535 			multirt_need_resolve =
20536 			    ire_multirt_need_resolve(ire->ire_addr,
20537 			    MBLK_GETLABEL(first_mp), ipst);
20538 			ip2dbg(("ip_wput[TCP]: ire %p, "
20539 			    "multirt_need_resolve %d, first_mp %p\n",
20540 			    (void *)ire, multirt_need_resolve,
20541 			    (void *)first_mp));
20542 			if (multirt_need_resolve) {
20543 				copy_mp = copymsg(first_mp);
20544 				if (copy_mp != NULL) {
20545 					MULTIRT_DEBUG_TAG(copy_mp);
20546 				}
20547 			}
20548 		}
20549 
20550 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20551 
20552 		/*
20553 		 * Try to resolve another multiroute if
20554 		 * ire_multirt_need_resolve() deemed it necessary.
20555 		 */
20556 		if (copy_mp != NULL)
20557 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20558 		if (need_decref)
20559 			CONN_DEC_REF(connp);
20560 		return;
20561 	}
20562 
20563 	/*
20564 	 * Access to conn_ire_cache. (protected by conn_lock)
20565 	 *
20566 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20567 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20568 	 * send a packet or two with the IRE_CACHE that is going away.
20569 	 * Access to the ire requires an ire refhold on the ire prior to
20570 	 * its use since an interface unplumb thread may delete the cached
20571 	 * ire and release the refhold at any time.
20572 	 *
20573 	 * Caching an ire in the conn_ire_cache
20574 	 *
20575 	 * o Caching an ire pointer in the conn requires a strict check for
20576 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20577 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20578 	 * in the conn is done after making sure under the bucket lock that the
20579 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20580 	 * caching an ire after the unplumb thread has cleaned up the conn.
20581 	 * If the conn does not send a packet subsequently the unplumb thread
20582 	 * will be hanging waiting for the ire count to drop to zero.
20583 	 *
20584 	 * o We also need to atomically test for a null conn_ire_cache and
20585 	 * set the conn_ire_cache under the the protection of the conn_lock
20586 	 * to avoid races among concurrent threads trying to simultaneously
20587 	 * cache an ire in the conn_ire_cache.
20588 	 */
20589 	mutex_enter(&connp->conn_lock);
20590 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20591 
20592 	if (ire != NULL && ire->ire_addr == dst &&
20593 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20594 
20595 		IRE_REFHOLD(ire);
20596 		mutex_exit(&connp->conn_lock);
20597 
20598 	} else {
20599 		boolean_t cached = B_FALSE;
20600 		connp->conn_ire_cache = NULL;
20601 		mutex_exit(&connp->conn_lock);
20602 		/* Release the old ire */
20603 		if (ire != NULL && sctp_ire == NULL)
20604 			IRE_REFRELE_NOTR(ire);
20605 
20606 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20607 		if (ire == NULL)
20608 			goto noirefound;
20609 		IRE_REFHOLD_NOTR(ire);
20610 
20611 		mutex_enter(&connp->conn_lock);
20612 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20613 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20614 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20615 				if (connp->conn_ulp == IPPROTO_TCP)
20616 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20617 				connp->conn_ire_cache = ire;
20618 				cached = B_TRUE;
20619 			}
20620 			rw_exit(&ire->ire_bucket->irb_lock);
20621 		}
20622 		mutex_exit(&connp->conn_lock);
20623 
20624 		/*
20625 		 * We can continue to use the ire but since it was
20626 		 * not cached, we should drop the extra reference.
20627 		 */
20628 		if (!cached)
20629 			IRE_REFRELE_NOTR(ire);
20630 	}
20631 
20632 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20633 	    "ip_wput_end: q %p (%S)", q, "end");
20634 
20635 	/*
20636 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20637 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20638 	 */
20639 	if (ire->ire_flags & RTF_MULTIRT) {
20640 		/*
20641 		 * Force the TTL of multirouted packets if required.
20642 		 * The TTL of such packets is bounded by the
20643 		 * ip_multirt_ttl ndd variable.
20644 		 */
20645 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20646 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20647 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20648 			    "(was %d), dst 0x%08x\n",
20649 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20650 			    ntohl(ire->ire_addr)));
20651 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20652 		}
20653 
20654 		/*
20655 		 * At this point, we check to see if there are any pending
20656 		 * unresolved routes. ire_multirt_resolvable()
20657 		 * checks in O(n) that all IRE_OFFSUBNET ire
20658 		 * entries for the packet's destination and
20659 		 * flagged RTF_MULTIRT are currently resolved.
20660 		 * If some remain unresolved, we make a copy
20661 		 * of the current message. It will be used
20662 		 * to initiate additional route resolutions.
20663 		 */
20664 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20665 		    MBLK_GETLABEL(first_mp), ipst);
20666 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20667 		    "multirt_need_resolve %d, first_mp %p\n",
20668 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20669 		if (multirt_need_resolve) {
20670 			copy_mp = copymsg(first_mp);
20671 			if (copy_mp != NULL) {
20672 				MULTIRT_DEBUG_TAG(copy_mp);
20673 			}
20674 		}
20675 	}
20676 
20677 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20678 
20679 	/*
20680 	 * Try to resolve another multiroute if
20681 	 * ire_multirt_resolvable() deemed it necessary
20682 	 */
20683 	if (copy_mp != NULL)
20684 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20685 	if (need_decref)
20686 		CONN_DEC_REF(connp);
20687 	return;
20688 
20689 qnext:
20690 	/*
20691 	 * Upper Level Protocols pass down complete IP datagrams
20692 	 * as M_DATA messages.	Everything else is a sideshow.
20693 	 *
20694 	 * 1) We could be re-entering ip_wput because of ip_neworute
20695 	 *    in which case we could have a IPSEC_OUT message. We
20696 	 *    need to pass through ip_wput like other datagrams and
20697 	 *    hence cannot branch to ip_wput_nondata.
20698 	 *
20699 	 * 2) ARP, AH, ESP, and other clients who are on the module
20700 	 *    instance of IP stream, give us something to deal with.
20701 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20702 	 *
20703 	 * 3) ICMP replies also could come here.
20704 	 */
20705 	ipst = ILLQ_TO_IPST(q);
20706 
20707 	if (DB_TYPE(mp) != M_DATA) {
20708 notdata:
20709 		if (DB_TYPE(mp) == M_CTL) {
20710 			/*
20711 			 * M_CTL messages are used by ARP, AH and ESP to
20712 			 * communicate with IP. We deal with IPSEC_IN and
20713 			 * IPSEC_OUT here. ip_wput_nondata handles other
20714 			 * cases.
20715 			 */
20716 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20717 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20718 				first_mp = mp->b_cont;
20719 				first_mp->b_flag &= ~MSGHASREF;
20720 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20721 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20722 				CONN_DEC_REF(connp);
20723 				connp = NULL;
20724 			}
20725 			if (ii->ipsec_info_type == IPSEC_IN) {
20726 				/*
20727 				 * Either this message goes back to
20728 				 * IPsec for further processing or to
20729 				 * ULP after policy checks.
20730 				 */
20731 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20732 				return;
20733 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20734 				io = (ipsec_out_t *)ii;
20735 				if (io->ipsec_out_proc_begin) {
20736 					/*
20737 					 * IPsec processing has already started.
20738 					 * Complete it.
20739 					 * IPQoS notes: We don't care what is
20740 					 * in ipsec_out_ill_index since this
20741 					 * won't be processed for IPQoS policies
20742 					 * in ipsec_out_process.
20743 					 */
20744 					ipsec_out_process(q, mp, NULL,
20745 					    io->ipsec_out_ill_index);
20746 					return;
20747 				} else {
20748 					connp = (q->q_next != NULL) ?
20749 					    NULL : Q_TO_CONN(q);
20750 					first_mp = mp;
20751 					mp = mp->b_cont;
20752 					mctl_present = B_TRUE;
20753 				}
20754 				zoneid = io->ipsec_out_zoneid;
20755 				ASSERT(zoneid != ALL_ZONES);
20756 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20757 				/*
20758 				 * It's an IPsec control message requesting
20759 				 * an SADB update to be sent to the IPsec
20760 				 * hardware acceleration capable ills.
20761 				 */
20762 				ipsec_ctl_t *ipsec_ctl =
20763 				    (ipsec_ctl_t *)mp->b_rptr;
20764 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20765 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20766 				mblk_t *cmp = mp->b_cont;
20767 
20768 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20769 				ASSERT(cmp != NULL);
20770 
20771 				freeb(mp);
20772 				ill_ipsec_capab_send_all(satype, cmp, sa,
20773 				    ipst->ips_netstack);
20774 				return;
20775 			} else {
20776 				/*
20777 				 * This must be ARP or special TSOL signaling.
20778 				 */
20779 				ip_wput_nondata(NULL, q, mp, NULL);
20780 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20781 				    "ip_wput_end: q %p (%S)", q, "nondata");
20782 				return;
20783 			}
20784 		} else {
20785 			/*
20786 			 * This must be non-(ARP/AH/ESP) messages.
20787 			 */
20788 			ASSERT(!need_decref);
20789 			ip_wput_nondata(NULL, q, mp, NULL);
20790 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20791 			    "ip_wput_end: q %p (%S)", q, "nondata");
20792 			return;
20793 		}
20794 	} else {
20795 		first_mp = mp;
20796 		mctl_present = B_FALSE;
20797 	}
20798 
20799 	ASSERT(first_mp != NULL);
20800 
20801 	if (mctl_present) {
20802 		io = (ipsec_out_t *)first_mp->b_rptr;
20803 		if (io->ipsec_out_ip_nexthop) {
20804 			/*
20805 			 * We may have lost the conn context if we are
20806 			 * coming here from ip_newroute(). Copy the
20807 			 * nexthop information.
20808 			 */
20809 			ip_nexthop = B_TRUE;
20810 			nexthop_addr = io->ipsec_out_nexthop_addr;
20811 
20812 			ipha = (ipha_t *)mp->b_rptr;
20813 			dst = ipha->ipha_dst;
20814 			goto send_from_ill;
20815 		}
20816 	}
20817 
20818 	ASSERT(xmit_ill == NULL);
20819 
20820 	/* We have a complete IP datagram heading outbound. */
20821 	ipha = (ipha_t *)mp->b_rptr;
20822 
20823 #ifndef SPEED_BEFORE_SAFETY
20824 	/*
20825 	 * Make sure we have a full-word aligned message and that at least
20826 	 * a simple IP header is accessible in the first message.  If not,
20827 	 * try a pullup.  For labeled systems we need to always take this
20828 	 * path as M_CTLs are "notdata" but have trailing data to process.
20829 	 */
20830 	if (!OK_32PTR(rptr) ||
20831 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
20832 hdrtoosmall:
20833 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20834 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20835 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20836 			if (first_mp == NULL)
20837 				first_mp = mp;
20838 			goto discard_pkt;
20839 		}
20840 
20841 		/* This function assumes that mp points to an IPv4 packet. */
20842 		if (is_system_labeled() && q->q_next == NULL &&
20843 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20844 		    !connp->conn_ulp_labeled) {
20845 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20846 			    connp->conn_mac_exempt, ipst);
20847 			ipha = (ipha_t *)mp->b_rptr;
20848 			if (first_mp != NULL)
20849 				first_mp->b_cont = mp;
20850 			if (err != 0) {
20851 				if (first_mp == NULL)
20852 					first_mp = mp;
20853 				if (err == EINVAL)
20854 					goto icmp_parameter_problem;
20855 				ip2dbg(("ip_wput: label check failed (%d)\n",
20856 				    err));
20857 				goto discard_pkt;
20858 			}
20859 		}
20860 
20861 		ipha = (ipha_t *)mp->b_rptr;
20862 		if (first_mp == NULL) {
20863 			ASSERT(xmit_ill == NULL);
20864 			/*
20865 			 * If we got here because of "goto hdrtoosmall"
20866 			 * We need to attach a IPSEC_OUT.
20867 			 */
20868 			if (connp->conn_out_enforce_policy) {
20869 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20870 				    NULL, ipha->ipha_protocol,
20871 				    ipst->ips_netstack)) == NULL)) {
20872 					BUMP_MIB(&ipst->ips_ip_mib,
20873 					    ipIfStatsOutDiscards);
20874 					if (need_decref)
20875 						CONN_DEC_REF(connp);
20876 					return;
20877 				} else {
20878 					ASSERT(mp->b_datap->db_type == M_CTL);
20879 					first_mp = mp;
20880 					mp = mp->b_cont;
20881 					mctl_present = B_TRUE;
20882 				}
20883 			} else {
20884 				first_mp = mp;
20885 				mctl_present = B_FALSE;
20886 			}
20887 		}
20888 	}
20889 #endif
20890 
20891 	/* Most of the code below is written for speed, not readability */
20892 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20893 
20894 	/*
20895 	 * If ip_newroute() fails, we're going to need a full
20896 	 * header for the icmp wraparound.
20897 	 */
20898 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20899 		uint_t	v_hlen;
20900 version_hdrlen_check:
20901 		ASSERT(first_mp != NULL);
20902 		v_hlen = V_HLEN;
20903 		/*
20904 		 * siphon off IPv6 packets coming down from transport
20905 		 * layer modules here.
20906 		 * Note: high-order bit carries NUD reachability confirmation
20907 		 */
20908 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20909 			/*
20910 			 * FIXME: assume that callers of ip_output* call
20911 			 * the right version?
20912 			 */
20913 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20914 			ASSERT(xmit_ill == NULL);
20915 			if (need_decref)
20916 				mp->b_flag |= MSGHASREF;
20917 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20918 			return;
20919 		}
20920 
20921 		if ((v_hlen >> 4) != IP_VERSION) {
20922 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20923 			    "ip_wput_end: q %p (%S)", q, "badvers");
20924 			goto discard_pkt;
20925 		}
20926 		/*
20927 		 * Is the header length at least 20 bytes?
20928 		 *
20929 		 * Are there enough bytes accessible in the header?  If
20930 		 * not, try a pullup.
20931 		 */
20932 		v_hlen &= 0xF;
20933 		v_hlen <<= 2;
20934 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20935 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20936 			    "ip_wput_end: q %p (%S)", q, "badlen");
20937 			goto discard_pkt;
20938 		}
20939 		if (v_hlen > (mp->b_wptr - rptr)) {
20940 			if (!pullupmsg(mp, v_hlen)) {
20941 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20942 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20943 				goto discard_pkt;
20944 			}
20945 			ipha = (ipha_t *)mp->b_rptr;
20946 		}
20947 		/*
20948 		 * Move first entry from any source route into ipha_dst and
20949 		 * verify the options
20950 		 */
20951 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20952 		    zoneid, ipst)) {
20953 			ASSERT(xmit_ill == NULL);
20954 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20955 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20956 			    "ip_wput_end: q %p (%S)", q, "badopts");
20957 			if (need_decref)
20958 				CONN_DEC_REF(connp);
20959 			return;
20960 		}
20961 	}
20962 	dst = ipha->ipha_dst;
20963 
20964 	/*
20965 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20966 	 * we have to run the packet through ip_newroute which will take
20967 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20968 	 * a resolver, or assigning a default gateway, etc.
20969 	 */
20970 	if (CLASSD(dst)) {
20971 		ipif_t	*ipif;
20972 		uint32_t setsrc = 0;
20973 
20974 multicast:
20975 		ASSERT(first_mp != NULL);
20976 		ip2dbg(("ip_wput: CLASSD\n"));
20977 		if (connp == NULL) {
20978 			/*
20979 			 * Use the first good ipif on the ill.
20980 			 * XXX Should this ever happen? (Appears
20981 			 * to show up with just ppp and no ethernet due
20982 			 * to in.rdisc.)
20983 			 * However, ire_send should be able to
20984 			 * call ip_wput_ire directly.
20985 			 *
20986 			 * XXX Also, this can happen for ICMP and other packets
20987 			 * with multicast source addresses.  Perhaps we should
20988 			 * fix things so that we drop the packet in question,
20989 			 * but for now, just run with it.
20990 			 */
20991 			ill_t *ill = (ill_t *)q->q_ptr;
20992 
20993 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20994 			if (ipif == NULL) {
20995 				if (need_decref)
20996 					CONN_DEC_REF(connp);
20997 				freemsg(first_mp);
20998 				return;
20999 			}
21000 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21001 			    ntohl(dst), ill->ill_name));
21002 		} else {
21003 			/*
21004 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
21005 			 * and IP_MULTICAST_IF.  The block comment above this
21006 			 * function explains the locking mechanism used here.
21007 			 */
21008 			if (xmit_ill == NULL) {
21009 				xmit_ill = conn_get_held_ill(connp,
21010 				    &connp->conn_outgoing_ill, &err);
21011 				if (err == ILL_LOOKUP_FAILED) {
21012 					ip1dbg(("ip_wput: No ill for "
21013 					    "IP_BOUND_IF\n"));
21014 					BUMP_MIB(&ipst->ips_ip_mib,
21015 					    ipIfStatsOutNoRoutes);
21016 					goto drop_pkt;
21017 				}
21018 			}
21019 
21020 			if (xmit_ill == NULL) {
21021 				ipif = conn_get_held_ipif(connp,
21022 				    &connp->conn_multicast_ipif, &err);
21023 				if (err == IPIF_LOOKUP_FAILED) {
21024 					ip1dbg(("ip_wput: No ipif for "
21025 					    "multicast\n"));
21026 					BUMP_MIB(&ipst->ips_ip_mib,
21027 					    ipIfStatsOutNoRoutes);
21028 					goto drop_pkt;
21029 				}
21030 			}
21031 			if (xmit_ill != NULL) {
21032 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21033 				if (ipif == NULL) {
21034 					ip1dbg(("ip_wput: No ipif for "
21035 					    "xmit_ill\n"));
21036 					BUMP_MIB(&ipst->ips_ip_mib,
21037 					    ipIfStatsOutNoRoutes);
21038 					goto drop_pkt;
21039 				}
21040 			} else if (ipif == NULL || ipif->ipif_isv6) {
21041 				/*
21042 				 * We must do this ipif determination here
21043 				 * else we could pass through ip_newroute
21044 				 * and come back here without the conn context.
21045 				 *
21046 				 * Note: we do late binding i.e. we bind to
21047 				 * the interface when the first packet is sent.
21048 				 * For performance reasons we do not rebind on
21049 				 * each packet but keep the binding until the
21050 				 * next IP_MULTICAST_IF option.
21051 				 *
21052 				 * conn_multicast_{ipif,ill} are shared between
21053 				 * IPv4 and IPv6 and AF_INET6 sockets can
21054 				 * send both IPv4 and IPv6 packets. Hence
21055 				 * we have to check that "isv6" matches above.
21056 				 */
21057 				if (ipif != NULL)
21058 					ipif_refrele(ipif);
21059 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21060 				if (ipif == NULL) {
21061 					ip1dbg(("ip_wput: No ipif for "
21062 					    "multicast\n"));
21063 					BUMP_MIB(&ipst->ips_ip_mib,
21064 					    ipIfStatsOutNoRoutes);
21065 					goto drop_pkt;
21066 				}
21067 				err = conn_set_held_ipif(connp,
21068 				    &connp->conn_multicast_ipif, ipif);
21069 				if (err == IPIF_LOOKUP_FAILED) {
21070 					ipif_refrele(ipif);
21071 					ip1dbg(("ip_wput: No ipif for "
21072 					    "multicast\n"));
21073 					BUMP_MIB(&ipst->ips_ip_mib,
21074 					    ipIfStatsOutNoRoutes);
21075 					goto drop_pkt;
21076 				}
21077 			}
21078 		}
21079 		ASSERT(!ipif->ipif_isv6);
21080 		/*
21081 		 * As we may lose the conn by the time we reach ip_wput_ire,
21082 		 * we copy conn_multicast_loop and conn_dontroute on to an
21083 		 * ipsec_out. In case if this datagram goes out secure,
21084 		 * we need the ill_index also. Copy that also into the
21085 		 * ipsec_out.
21086 		 */
21087 		if (mctl_present) {
21088 			io = (ipsec_out_t *)first_mp->b_rptr;
21089 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21090 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21091 		} else {
21092 			ASSERT(mp == first_mp);
21093 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21094 			    BPRI_HI)) == NULL) {
21095 				ipif_refrele(ipif);
21096 				first_mp = mp;
21097 				goto discard_pkt;
21098 			}
21099 			first_mp->b_datap->db_type = M_CTL;
21100 			first_mp->b_wptr += sizeof (ipsec_info_t);
21101 			/* ipsec_out_secure is B_FALSE now */
21102 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21103 			io = (ipsec_out_t *)first_mp->b_rptr;
21104 			io->ipsec_out_type = IPSEC_OUT;
21105 			io->ipsec_out_len = sizeof (ipsec_out_t);
21106 			io->ipsec_out_use_global_policy = B_TRUE;
21107 			io->ipsec_out_ns = ipst->ips_netstack;
21108 			first_mp->b_cont = mp;
21109 			mctl_present = B_TRUE;
21110 		}
21111 
21112 		match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21113 		io->ipsec_out_ill_index =
21114 		    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21115 
21116 		if (connp != NULL) {
21117 			io->ipsec_out_multicast_loop =
21118 			    connp->conn_multicast_loop;
21119 			io->ipsec_out_dontroute = connp->conn_dontroute;
21120 			io->ipsec_out_zoneid = connp->conn_zoneid;
21121 		}
21122 		/*
21123 		 * If the application uses IP_MULTICAST_IF with
21124 		 * different logical addresses of the same ILL, we
21125 		 * need to make sure that the soruce address of
21126 		 * the packet matches the logical IP address used
21127 		 * in the option. We do it by initializing ipha_src
21128 		 * here. This should keep IPsec also happy as
21129 		 * when we return from IPsec processing, we don't
21130 		 * have to worry about getting the right address on
21131 		 * the packet. Thus it is sufficient to look for
21132 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21133 		 * MATCH_IRE_IPIF.
21134 		 *
21135 		 * NOTE : We need to do it for non-secure case also as
21136 		 * this might go out secure if there is a global policy
21137 		 * match in ip_wput_ire.
21138 		 *
21139 		 * As we do not have the ire yet, it is possible that
21140 		 * we set the source address here and then later discover
21141 		 * that the ire implies the source address to be assigned
21142 		 * through the RTF_SETSRC flag.
21143 		 * In that case, the setsrc variable will remind us
21144 		 * that overwritting the source address by the one
21145 		 * of the RTF_SETSRC-flagged ire is allowed.
21146 		 */
21147 		if (ipha->ipha_src == INADDR_ANY &&
21148 		    (connp == NULL || !connp->conn_unspec_src)) {
21149 			ipha->ipha_src = ipif->ipif_src_addr;
21150 			setsrc = RTF_SETSRC;
21151 		}
21152 		/*
21153 		 * Find an IRE which matches the destination and the outgoing
21154 		 * queue (i.e. the outgoing interface.)
21155 		 * For loopback use a unicast IP address for
21156 		 * the ire lookup.
21157 		 */
21158 		if (IS_LOOPBACK(ipif->ipif_ill))
21159 			dst = ipif->ipif_lcl_addr;
21160 
21161 		/*
21162 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21163 		 * We don't need to lookup ire in ctable as the packet
21164 		 * needs to be sent to the destination through the specified
21165 		 * ill irrespective of ires in the cache table.
21166 		 */
21167 		ire = NULL;
21168 		if (xmit_ill == NULL) {
21169 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21170 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21171 		}
21172 
21173 		if (ire == NULL) {
21174 			/*
21175 			 * Multicast loopback and multicast forwarding is
21176 			 * done in ip_wput_ire.
21177 			 *
21178 			 * Mark this packet to make it be delivered to
21179 			 * ip_wput_ire after the new ire has been
21180 			 * created.
21181 			 *
21182 			 * The call to ip_newroute_ipif takes into account
21183 			 * the setsrc reminder. In any case, we take care
21184 			 * of the RTF_MULTIRT flag.
21185 			 */
21186 			mp->b_prev = mp->b_next = NULL;
21187 			if (xmit_ill == NULL ||
21188 			    xmit_ill->ill_ipif_up_count > 0) {
21189 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21190 				    setsrc | RTF_MULTIRT, zoneid, infop);
21191 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21192 				    "ip_wput_end: q %p (%S)", q, "noire");
21193 			} else {
21194 				freemsg(first_mp);
21195 			}
21196 			ipif_refrele(ipif);
21197 			if (xmit_ill != NULL)
21198 				ill_refrele(xmit_ill);
21199 			if (need_decref)
21200 				CONN_DEC_REF(connp);
21201 			return;
21202 		}
21203 
21204 		ipif_refrele(ipif);
21205 		ipif = NULL;
21206 		ASSERT(xmit_ill == NULL);
21207 
21208 		/*
21209 		 * Honor the RTF_SETSRC flag for multicast packets,
21210 		 * if allowed by the setsrc reminder.
21211 		 */
21212 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21213 			ipha->ipha_src = ire->ire_src_addr;
21214 		}
21215 
21216 		/*
21217 		 * Unconditionally force the TTL to 1 for
21218 		 * multirouted multicast packets:
21219 		 * multirouted multicast should not cross
21220 		 * multicast routers.
21221 		 */
21222 		if (ire->ire_flags & RTF_MULTIRT) {
21223 			if (ipha->ipha_ttl > 1) {
21224 				ip2dbg(("ip_wput: forcing multicast "
21225 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21226 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21227 				ipha->ipha_ttl = 1;
21228 			}
21229 		}
21230 	} else {
21231 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21232 		if ((ire != NULL) && (ire->ire_type &
21233 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21234 			ignore_dontroute = B_TRUE;
21235 			ignore_nexthop = B_TRUE;
21236 		}
21237 		if (ire != NULL) {
21238 			ire_refrele(ire);
21239 			ire = NULL;
21240 		}
21241 		/*
21242 		 * Guard against coming in from arp in which case conn is NULL.
21243 		 * Also guard against non M_DATA with dontroute set but
21244 		 * destined to local, loopback or broadcast addresses.
21245 		 */
21246 		if (connp != NULL && connp->conn_dontroute &&
21247 		    !ignore_dontroute) {
21248 dontroute:
21249 			/*
21250 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21251 			 * routing protocols from seeing false direct
21252 			 * connectivity.
21253 			 */
21254 			ipha->ipha_ttl = 1;
21255 			/* If suitable ipif not found, drop packet */
21256 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21257 			if (dst_ipif == NULL) {
21258 noroute:
21259 				ip1dbg(("ip_wput: no route for dst using"
21260 				    " SO_DONTROUTE\n"));
21261 				BUMP_MIB(&ipst->ips_ip_mib,
21262 				    ipIfStatsOutNoRoutes);
21263 				mp->b_prev = mp->b_next = NULL;
21264 				if (first_mp == NULL)
21265 					first_mp = mp;
21266 				goto drop_pkt;
21267 			} else {
21268 				/*
21269 				 * If suitable ipif has been found, set
21270 				 * xmit_ill to the corresponding
21271 				 * ipif_ill because we'll be using the
21272 				 * send_from_ill logic below.
21273 				 */
21274 				ASSERT(xmit_ill == NULL);
21275 				xmit_ill = dst_ipif->ipif_ill;
21276 				mutex_enter(&xmit_ill->ill_lock);
21277 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21278 					mutex_exit(&xmit_ill->ill_lock);
21279 					xmit_ill = NULL;
21280 					ipif_refrele(dst_ipif);
21281 					goto noroute;
21282 				}
21283 				ill_refhold_locked(xmit_ill);
21284 				mutex_exit(&xmit_ill->ill_lock);
21285 				ipif_refrele(dst_ipif);
21286 			}
21287 		}
21288 
21289 send_from_ill:
21290 		if (xmit_ill != NULL) {
21291 			ipif_t *ipif;
21292 
21293 			/*
21294 			 * Mark this packet as originated locally
21295 			 */
21296 			mp->b_prev = mp->b_next = NULL;
21297 
21298 			/*
21299 			 * Could be SO_DONTROUTE case also.
21300 			 * Verify that at least one ipif is up on the ill.
21301 			 */
21302 			if (xmit_ill->ill_ipif_up_count == 0) {
21303 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21304 				    xmit_ill->ill_name));
21305 				goto drop_pkt;
21306 			}
21307 
21308 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21309 			if (ipif == NULL) {
21310 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21311 				    xmit_ill->ill_name));
21312 				goto drop_pkt;
21313 			}
21314 
21315 			match_flags = 0;
21316 			if (IS_UNDER_IPMP(xmit_ill))
21317 				match_flags |= MATCH_IRE_MARK_TESTHIDDEN;
21318 
21319 			/*
21320 			 * Look for a ire that is part of the group,
21321 			 * if found use it else call ip_newroute_ipif.
21322 			 * IPCL_ZONEID is not used for matching because
21323 			 * IP_ALLZONES option is valid only when the
21324 			 * ill is accessible from all zones i.e has a
21325 			 * valid ipif in all zones.
21326 			 */
21327 			match_flags |= MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21328 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21329 			    MBLK_GETLABEL(mp), match_flags, ipst);
21330 			/*
21331 			 * If an ire exists use it or else create
21332 			 * an ire but don't add it to the cache.
21333 			 * Adding an ire may cause issues with
21334 			 * asymmetric routing.
21335 			 * In case of multiroute always act as if
21336 			 * ire does not exist.
21337 			 */
21338 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21339 				if (ire != NULL)
21340 					ire_refrele(ire);
21341 				ip_newroute_ipif(q, first_mp, ipif,
21342 				    dst, connp, 0, zoneid, infop);
21343 				ipif_refrele(ipif);
21344 				ip1dbg(("ip_output: xmit_ill via %s\n",
21345 				    xmit_ill->ill_name));
21346 				ill_refrele(xmit_ill);
21347 				if (need_decref)
21348 					CONN_DEC_REF(connp);
21349 				return;
21350 			}
21351 			ipif_refrele(ipif);
21352 		} else if (ip_nexthop || (connp != NULL &&
21353 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21354 			if (!ip_nexthop) {
21355 				ip_nexthop = B_TRUE;
21356 				nexthop_addr = connp->conn_nexthop_v4;
21357 			}
21358 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21359 			    MATCH_IRE_GW;
21360 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21361 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21362 		} else {
21363 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21364 			    ipst);
21365 		}
21366 		if (!ire) {
21367 			if (ip_nexthop && !ignore_nexthop) {
21368 				if (mctl_present) {
21369 					io = (ipsec_out_t *)first_mp->b_rptr;
21370 					ASSERT(first_mp->b_datap->db_type ==
21371 					    M_CTL);
21372 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21373 				} else {
21374 					ASSERT(mp == first_mp);
21375 					first_mp = allocb(
21376 					    sizeof (ipsec_info_t), BPRI_HI);
21377 					if (first_mp == NULL) {
21378 						first_mp = mp;
21379 						goto discard_pkt;
21380 					}
21381 					first_mp->b_datap->db_type = M_CTL;
21382 					first_mp->b_wptr +=
21383 					    sizeof (ipsec_info_t);
21384 					/* ipsec_out_secure is B_FALSE now */
21385 					bzero(first_mp->b_rptr,
21386 					    sizeof (ipsec_info_t));
21387 					io = (ipsec_out_t *)first_mp->b_rptr;
21388 					io->ipsec_out_type = IPSEC_OUT;
21389 					io->ipsec_out_len =
21390 					    sizeof (ipsec_out_t);
21391 					io->ipsec_out_use_global_policy =
21392 					    B_TRUE;
21393 					io->ipsec_out_ns = ipst->ips_netstack;
21394 					first_mp->b_cont = mp;
21395 					mctl_present = B_TRUE;
21396 				}
21397 				io->ipsec_out_ip_nexthop = ip_nexthop;
21398 				io->ipsec_out_nexthop_addr = nexthop_addr;
21399 			}
21400 noirefound:
21401 			/*
21402 			 * Mark this packet as having originated on
21403 			 * this machine.  This will be noted in
21404 			 * ire_add_then_send, which needs to know
21405 			 * whether to run it back through ip_wput or
21406 			 * ip_rput following successful resolution.
21407 			 */
21408 			mp->b_prev = NULL;
21409 			mp->b_next = NULL;
21410 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21411 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21412 			    "ip_wput_end: q %p (%S)", q, "newroute");
21413 			if (xmit_ill != NULL)
21414 				ill_refrele(xmit_ill);
21415 			if (need_decref)
21416 				CONN_DEC_REF(connp);
21417 			return;
21418 		}
21419 	}
21420 
21421 	/* We now know where we are going with it. */
21422 
21423 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21424 	    "ip_wput_end: q %p (%S)", q, "end");
21425 
21426 	/*
21427 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21428 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21429 	 */
21430 	if (ire->ire_flags & RTF_MULTIRT) {
21431 		/*
21432 		 * Force the TTL of multirouted packets if required.
21433 		 * The TTL of such packets is bounded by the
21434 		 * ip_multirt_ttl ndd variable.
21435 		 */
21436 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21437 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21438 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21439 			    "(was %d), dst 0x%08x\n",
21440 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21441 			    ntohl(ire->ire_addr)));
21442 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21443 		}
21444 		/*
21445 		 * At this point, we check to see if there are any pending
21446 		 * unresolved routes. ire_multirt_resolvable()
21447 		 * checks in O(n) that all IRE_OFFSUBNET ire
21448 		 * entries for the packet's destination and
21449 		 * flagged RTF_MULTIRT are currently resolved.
21450 		 * If some remain unresolved, we make a copy
21451 		 * of the current message. It will be used
21452 		 * to initiate additional route resolutions.
21453 		 */
21454 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21455 		    MBLK_GETLABEL(first_mp), ipst);
21456 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21457 		    "multirt_need_resolve %d, first_mp %p\n",
21458 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21459 		if (multirt_need_resolve) {
21460 			copy_mp = copymsg(first_mp);
21461 			if (copy_mp != NULL) {
21462 				MULTIRT_DEBUG_TAG(copy_mp);
21463 			}
21464 		}
21465 	}
21466 
21467 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21468 	/*
21469 	 * Try to resolve another multiroute if
21470 	 * ire_multirt_resolvable() deemed it necessary.
21471 	 * At this point, we need to distinguish
21472 	 * multicasts from other packets. For multicasts,
21473 	 * we call ip_newroute_ipif() and request that both
21474 	 * multirouting and setsrc flags are checked.
21475 	 */
21476 	if (copy_mp != NULL) {
21477 		if (CLASSD(dst)) {
21478 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21479 			if (ipif) {
21480 				ASSERT(infop->ip_opt_ill_index == 0);
21481 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21482 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21483 				ipif_refrele(ipif);
21484 			} else {
21485 				MULTIRT_DEBUG_UNTAG(copy_mp);
21486 				freemsg(copy_mp);
21487 				copy_mp = NULL;
21488 			}
21489 		} else {
21490 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21491 		}
21492 	}
21493 	if (xmit_ill != NULL)
21494 		ill_refrele(xmit_ill);
21495 	if (need_decref)
21496 		CONN_DEC_REF(connp);
21497 	return;
21498 
21499 icmp_parameter_problem:
21500 	/* could not have originated externally */
21501 	ASSERT(mp->b_prev == NULL);
21502 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21503 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21504 		/* it's the IP header length that's in trouble */
21505 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21506 		first_mp = NULL;
21507 	}
21508 
21509 discard_pkt:
21510 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21511 drop_pkt:
21512 	ip1dbg(("ip_wput: dropped packet\n"));
21513 	if (ire != NULL)
21514 		ire_refrele(ire);
21515 	if (need_decref)
21516 		CONN_DEC_REF(connp);
21517 	freemsg(first_mp);
21518 	if (xmit_ill != NULL)
21519 		ill_refrele(xmit_ill);
21520 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21521 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21522 }
21523 
21524 /*
21525  * If this is a conn_t queue, then we pass in the conn. This includes the
21526  * zoneid.
21527  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21528  * in which case we use the global zoneid since those are all part of
21529  * the global zone.
21530  */
21531 void
21532 ip_wput(queue_t *q, mblk_t *mp)
21533 {
21534 	if (CONN_Q(q))
21535 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21536 	else
21537 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21538 }
21539 
21540 /*
21541  *
21542  * The following rules must be observed when accessing any ipif or ill
21543  * that has been cached in the conn. Typically conn_outgoing_ill,
21544  * conn_multicast_ipif and conn_multicast_ill.
21545  *
21546  * Access: The ipif or ill pointed to from the conn can be accessed under
21547  * the protection of the conn_lock or after it has been refheld under the
21548  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21549  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21550  * The reason for this is that a concurrent unplumb could actually be
21551  * cleaning up these cached pointers by walking the conns and might have
21552  * finished cleaning up the conn in question. The macros check that an
21553  * unplumb has not yet started on the ipif or ill.
21554  *
21555  * Caching: An ipif or ill pointer may be cached in the conn only after
21556  * making sure that an unplumb has not started. So the caching is done
21557  * while holding both the conn_lock and the ill_lock and after using the
21558  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21559  * flag before starting the cleanup of conns.
21560  *
21561  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21562  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21563  * or a reference to the ipif or a reference to an ire that references the
21564  * ipif. An ipif only changes its ill when migrating from an underlying ill
21565  * to an IPMP ill in ipif_up().
21566  */
21567 ipif_t *
21568 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21569 {
21570 	ipif_t	*ipif;
21571 	ill_t	*ill;
21572 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21573 
21574 	*err = 0;
21575 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21576 	mutex_enter(&connp->conn_lock);
21577 	ipif = *ipifp;
21578 	if (ipif != NULL) {
21579 		ill = ipif->ipif_ill;
21580 		mutex_enter(&ill->ill_lock);
21581 		if (IPIF_CAN_LOOKUP(ipif)) {
21582 			ipif_refhold_locked(ipif);
21583 			mutex_exit(&ill->ill_lock);
21584 			mutex_exit(&connp->conn_lock);
21585 			rw_exit(&ipst->ips_ill_g_lock);
21586 			return (ipif);
21587 		} else {
21588 			*err = IPIF_LOOKUP_FAILED;
21589 		}
21590 		mutex_exit(&ill->ill_lock);
21591 	}
21592 	mutex_exit(&connp->conn_lock);
21593 	rw_exit(&ipst->ips_ill_g_lock);
21594 	return (NULL);
21595 }
21596 
21597 ill_t *
21598 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21599 {
21600 	ill_t	*ill;
21601 
21602 	*err = 0;
21603 	mutex_enter(&connp->conn_lock);
21604 	ill = *illp;
21605 	if (ill != NULL) {
21606 		mutex_enter(&ill->ill_lock);
21607 		if (ILL_CAN_LOOKUP(ill)) {
21608 			ill_refhold_locked(ill);
21609 			mutex_exit(&ill->ill_lock);
21610 			mutex_exit(&connp->conn_lock);
21611 			return (ill);
21612 		} else {
21613 			*err = ILL_LOOKUP_FAILED;
21614 		}
21615 		mutex_exit(&ill->ill_lock);
21616 	}
21617 	mutex_exit(&connp->conn_lock);
21618 	return (NULL);
21619 }
21620 
21621 static int
21622 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21623 {
21624 	ill_t	*ill;
21625 
21626 	ill = ipif->ipif_ill;
21627 	mutex_enter(&connp->conn_lock);
21628 	mutex_enter(&ill->ill_lock);
21629 	if (IPIF_CAN_LOOKUP(ipif)) {
21630 		*ipifp = ipif;
21631 		mutex_exit(&ill->ill_lock);
21632 		mutex_exit(&connp->conn_lock);
21633 		return (0);
21634 	}
21635 	mutex_exit(&ill->ill_lock);
21636 	mutex_exit(&connp->conn_lock);
21637 	return (IPIF_LOOKUP_FAILED);
21638 }
21639 
21640 /*
21641  * This is called if the outbound datagram needs fragmentation.
21642  *
21643  * NOTE : This function does not ire_refrele the ire argument passed in.
21644  */
21645 static void
21646 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21647     ip_stack_t *ipst, conn_t *connp)
21648 {
21649 	ipha_t		*ipha;
21650 	mblk_t		*mp;
21651 	uint32_t	v_hlen_tos_len;
21652 	uint32_t	max_frag;
21653 	uint32_t	frag_flag;
21654 	boolean_t	dont_use;
21655 
21656 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21657 		mp = ipsec_mp->b_cont;
21658 	} else {
21659 		mp = ipsec_mp;
21660 	}
21661 
21662 	ipha = (ipha_t *)mp->b_rptr;
21663 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21664 
21665 #ifdef	_BIG_ENDIAN
21666 #define	V_HLEN	(v_hlen_tos_len >> 24)
21667 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21668 #else
21669 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21670 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21671 #endif
21672 
21673 #ifndef SPEED_BEFORE_SAFETY
21674 	/*
21675 	 * Check that ipha_length is consistent with
21676 	 * the mblk length
21677 	 */
21678 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21679 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21680 		    LENGTH, msgdsize(mp)));
21681 		freemsg(ipsec_mp);
21682 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21683 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21684 		    "packet length mismatch");
21685 		return;
21686 	}
21687 #endif
21688 	/*
21689 	 * Don't use frag_flag if pre-built packet or source
21690 	 * routed or if multicast (since multicast packets do not solicit
21691 	 * ICMP "packet too big" messages). Get the values of
21692 	 * max_frag and frag_flag atomically by acquiring the
21693 	 * ire_lock.
21694 	 */
21695 	mutex_enter(&ire->ire_lock);
21696 	max_frag = ire->ire_max_frag;
21697 	frag_flag = ire->ire_frag_flag;
21698 	mutex_exit(&ire->ire_lock);
21699 
21700 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21701 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21702 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21703 
21704 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21705 	    (dont_use ? 0 : frag_flag), zoneid, ipst, connp);
21706 }
21707 
21708 /*
21709  * Used for deciding the MSS size for the upper layer. Thus
21710  * we need to check the outbound policy values in the conn.
21711  */
21712 int
21713 conn_ipsec_length(conn_t *connp)
21714 {
21715 	ipsec_latch_t *ipl;
21716 
21717 	ipl = connp->conn_latch;
21718 	if (ipl == NULL)
21719 		return (0);
21720 
21721 	if (ipl->ipl_out_policy == NULL)
21722 		return (0);
21723 
21724 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21725 }
21726 
21727 /*
21728  * Returns an estimate of the IPsec headers size. This is used if
21729  * we don't want to call into IPsec to get the exact size.
21730  */
21731 int
21732 ipsec_out_extra_length(mblk_t *ipsec_mp)
21733 {
21734 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21735 	ipsec_action_t *a;
21736 
21737 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21738 	if (!io->ipsec_out_secure)
21739 		return (0);
21740 
21741 	a = io->ipsec_out_act;
21742 
21743 	if (a == NULL) {
21744 		ASSERT(io->ipsec_out_policy != NULL);
21745 		a = io->ipsec_out_policy->ipsp_act;
21746 	}
21747 	ASSERT(a != NULL);
21748 
21749 	return (a->ipa_ovhd);
21750 }
21751 
21752 /*
21753  * Returns an estimate of the IPsec headers size. This is used if
21754  * we don't want to call into IPsec to get the exact size.
21755  */
21756 int
21757 ipsec_in_extra_length(mblk_t *ipsec_mp)
21758 {
21759 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21760 	ipsec_action_t *a;
21761 
21762 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21763 
21764 	a = ii->ipsec_in_action;
21765 	return (a == NULL ? 0 : a->ipa_ovhd);
21766 }
21767 
21768 /*
21769  * If there are any source route options, return the true final
21770  * destination. Otherwise, return the destination.
21771  */
21772 ipaddr_t
21773 ip_get_dst(ipha_t *ipha)
21774 {
21775 	ipoptp_t	opts;
21776 	uchar_t		*opt;
21777 	uint8_t		optval;
21778 	uint8_t		optlen;
21779 	ipaddr_t	dst;
21780 	uint32_t off;
21781 
21782 	dst = ipha->ipha_dst;
21783 
21784 	if (IS_SIMPLE_IPH(ipha))
21785 		return (dst);
21786 
21787 	for (optval = ipoptp_first(&opts, ipha);
21788 	    optval != IPOPT_EOL;
21789 	    optval = ipoptp_next(&opts)) {
21790 		opt = opts.ipoptp_cur;
21791 		optlen = opts.ipoptp_len;
21792 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21793 		switch (optval) {
21794 		case IPOPT_SSRR:
21795 		case IPOPT_LSRR:
21796 			off = opt[IPOPT_OFFSET];
21797 			/*
21798 			 * If one of the conditions is true, it means
21799 			 * end of options and dst already has the right
21800 			 * value.
21801 			 */
21802 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21803 				off = optlen - IP_ADDR_LEN;
21804 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21805 			}
21806 			return (dst);
21807 		default:
21808 			break;
21809 		}
21810 	}
21811 
21812 	return (dst);
21813 }
21814 
21815 mblk_t *
21816 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21817     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21818 {
21819 	ipsec_out_t	*io;
21820 	mblk_t		*first_mp;
21821 	boolean_t policy_present;
21822 	ip_stack_t	*ipst;
21823 	ipsec_stack_t	*ipss;
21824 
21825 	ASSERT(ire != NULL);
21826 	ipst = ire->ire_ipst;
21827 	ipss = ipst->ips_netstack->netstack_ipsec;
21828 
21829 	first_mp = mp;
21830 	if (mp->b_datap->db_type == M_CTL) {
21831 		io = (ipsec_out_t *)first_mp->b_rptr;
21832 		/*
21833 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21834 		 *
21835 		 * 1) There is per-socket policy (including cached global
21836 		 *    policy) or a policy on the IP-in-IP tunnel.
21837 		 * 2) There is no per-socket policy, but it is
21838 		 *    a multicast packet that needs to go out
21839 		 *    on a specific interface. This is the case
21840 		 *    where (ip_wput and ip_wput_multicast) attaches
21841 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21842 		 *
21843 		 * In case (2) we check with global policy to
21844 		 * see if there is a match and set the ill_index
21845 		 * appropriately so that we can lookup the ire
21846 		 * properly in ip_wput_ipsec_out.
21847 		 */
21848 
21849 		/*
21850 		 * ipsec_out_use_global_policy is set to B_FALSE
21851 		 * in ipsec_in_to_out(). Refer to that function for
21852 		 * details.
21853 		 */
21854 		if ((io->ipsec_out_latch == NULL) &&
21855 		    (io->ipsec_out_use_global_policy)) {
21856 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21857 			    ire, connp, unspec_src, zoneid));
21858 		}
21859 		if (!io->ipsec_out_secure) {
21860 			/*
21861 			 * If this is not a secure packet, drop
21862 			 * the IPSEC_OUT mp and treat it as a clear
21863 			 * packet. This happens when we are sending
21864 			 * a ICMP reply back to a clear packet. See
21865 			 * ipsec_in_to_out() for details.
21866 			 */
21867 			mp = first_mp->b_cont;
21868 			freeb(first_mp);
21869 		}
21870 		return (mp);
21871 	}
21872 	/*
21873 	 * See whether we need to attach a global policy here. We
21874 	 * don't depend on the conn (as it could be null) for deciding
21875 	 * what policy this datagram should go through because it
21876 	 * should have happened in ip_wput if there was some
21877 	 * policy. This normally happens for connections which are not
21878 	 * fully bound preventing us from caching policies in
21879 	 * ip_bind. Packets coming from the TCP listener/global queue
21880 	 * - which are non-hard_bound - could also be affected by
21881 	 * applying policy here.
21882 	 *
21883 	 * If this packet is coming from tcp global queue or listener,
21884 	 * we will be applying policy here.  This may not be *right*
21885 	 * if these packets are coming from the detached connection as
21886 	 * it could have gone in clear before. This happens only if a
21887 	 * TCP connection started when there is no policy and somebody
21888 	 * added policy before it became detached. Thus packets of the
21889 	 * detached connection could go out secure and the other end
21890 	 * would drop it because it will be expecting in clear. The
21891 	 * converse is not true i.e if somebody starts a TCP
21892 	 * connection and deletes the policy, all the packets will
21893 	 * still go out with the policy that existed before deleting
21894 	 * because ip_unbind sends up policy information which is used
21895 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21896 	 * TCP to attach a dummy IPSEC_OUT and set
21897 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21898 	 * affect performance for normal cases, we are not doing it.
21899 	 * Thus, set policy before starting any TCP connections.
21900 	 *
21901 	 * NOTE - We might apply policy even for a hard bound connection
21902 	 * - for which we cached policy in ip_bind - if somebody added
21903 	 * global policy after we inherited the policy in ip_bind.
21904 	 * This means that the packets that were going out in clear
21905 	 * previously would start going secure and hence get dropped
21906 	 * on the other side. To fix this, TCP attaches a dummy
21907 	 * ipsec_out and make sure that we don't apply global policy.
21908 	 */
21909 	if (ipha != NULL)
21910 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21911 	else
21912 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21913 	if (!policy_present)
21914 		return (mp);
21915 
21916 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21917 	    zoneid));
21918 }
21919 
21920 /*
21921  * This function does the ire_refrele of the ire passed in as the
21922  * argument. As this function looks up more ires i.e broadcast ires,
21923  * it needs to REFRELE them. Currently, for simplicity we don't
21924  * differentiate the one passed in and looked up here. We always
21925  * REFRELE.
21926  * IPQoS Notes:
21927  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21928  * IPsec packets are done in ipsec_out_process.
21929  */
21930 void
21931 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21932     zoneid_t zoneid)
21933 {
21934 	ipha_t		*ipha;
21935 #define	rptr	((uchar_t *)ipha)
21936 	queue_t		*stq;
21937 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21938 	uint32_t	v_hlen_tos_len;
21939 	uint32_t	ttl_protocol;
21940 	ipaddr_t	src;
21941 	ipaddr_t	dst;
21942 	uint32_t	cksum;
21943 	ipaddr_t	orig_src;
21944 	ire_t		*ire1;
21945 	mblk_t		*next_mp;
21946 	uint_t		hlen;
21947 	uint16_t	*up;
21948 	uint32_t	max_frag = ire->ire_max_frag;
21949 	ill_t		*ill = ire_to_ill(ire);
21950 	int		clusterwide;
21951 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21952 	int		ipsec_len;
21953 	mblk_t		*first_mp;
21954 	ipsec_out_t	*io;
21955 	boolean_t	conn_dontroute;		/* conn value for multicast */
21956 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21957 	boolean_t	multicast_forward;	/* Should we forward ? */
21958 	boolean_t	unspec_src;
21959 	ill_t		*conn_outgoing_ill = NULL;
21960 	ill_t		*ire_ill;
21961 	ill_t		*ire1_ill;
21962 	ill_t		*out_ill;
21963 	uint32_t 	ill_index = 0;
21964 	boolean_t	multirt_send = B_FALSE;
21965 	int		err;
21966 	ipxmit_state_t	pktxmit_state;
21967 	ip_stack_t	*ipst = ire->ire_ipst;
21968 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
21969 
21970 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
21971 	    "ip_wput_ire_start: q %p", q);
21972 
21973 	multicast_forward = B_FALSE;
21974 	unspec_src = (connp != NULL && connp->conn_unspec_src);
21975 
21976 	if (ire->ire_flags & RTF_MULTIRT) {
21977 		/*
21978 		 * Multirouting case. The bucket where ire is stored
21979 		 * probably holds other RTF_MULTIRT flagged ire
21980 		 * to the destination. In this call to ip_wput_ire,
21981 		 * we attempt to send the packet through all
21982 		 * those ires. Thus, we first ensure that ire is the
21983 		 * first RTF_MULTIRT ire in the bucket,
21984 		 * before walking the ire list.
21985 		 */
21986 		ire_t *first_ire;
21987 		irb_t *irb = ire->ire_bucket;
21988 		ASSERT(irb != NULL);
21989 
21990 		/* Make sure we do not omit any multiroute ire. */
21991 		IRB_REFHOLD(irb);
21992 		for (first_ire = irb->irb_ire;
21993 		    first_ire != NULL;
21994 		    first_ire = first_ire->ire_next) {
21995 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
21996 			    (first_ire->ire_addr == ire->ire_addr) &&
21997 			    !(first_ire->ire_marks &
21998 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
21999 				break;
22000 		}
22001 
22002 		if ((first_ire != NULL) && (first_ire != ire)) {
22003 			IRE_REFHOLD(first_ire);
22004 			ire_refrele(ire);
22005 			ire = first_ire;
22006 			ill = ire_to_ill(ire);
22007 		}
22008 		IRB_REFRELE(irb);
22009 	}
22010 
22011 	/*
22012 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22013 	 * for performance we don't grab the mutexs in the fastpath
22014 	 */
22015 	if (ire->ire_type == IRE_BROADCAST && connp != NULL &&
22016 	    connp->conn_outgoing_ill != NULL) {
22017 		conn_outgoing_ill = conn_get_held_ill(connp,
22018 		    &connp->conn_outgoing_ill, &err);
22019 		if (err == ILL_LOOKUP_FAILED) {
22020 			ire_refrele(ire);
22021 			freemsg(mp);
22022 			return;
22023 		}
22024 	}
22025 
22026 	if (mp->b_datap->db_type != M_CTL) {
22027 		ipha = (ipha_t *)mp->b_rptr;
22028 	} else {
22029 		io = (ipsec_out_t *)mp->b_rptr;
22030 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22031 		ASSERT(zoneid == io->ipsec_out_zoneid);
22032 		ASSERT(zoneid != ALL_ZONES);
22033 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22034 		dst = ipha->ipha_dst;
22035 		/*
22036 		 * For the multicast case, ipsec_out carries conn_dontroute and
22037 		 * conn_multicast_loop as conn may not be available here. We
22038 		 * need this for multicast loopback and forwarding which is done
22039 		 * later in the code.
22040 		 */
22041 		if (CLASSD(dst)) {
22042 			conn_dontroute = io->ipsec_out_dontroute;
22043 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22044 			/*
22045 			 * If conn_dontroute is not set or conn_multicast_loop
22046 			 * is set, we need to do forwarding/loopback. For
22047 			 * datagrams from ip_wput_multicast, conn_dontroute is
22048 			 * set to B_TRUE and conn_multicast_loop is set to
22049 			 * B_FALSE so that we neither do forwarding nor
22050 			 * loopback.
22051 			 */
22052 			if (!conn_dontroute || conn_multicast_loop)
22053 				multicast_forward = B_TRUE;
22054 		}
22055 	}
22056 
22057 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22058 	    ire->ire_zoneid != ALL_ZONES) {
22059 		/*
22060 		 * When a zone sends a packet to another zone, we try to deliver
22061 		 * the packet under the same conditions as if the destination
22062 		 * was a real node on the network. To do so, we look for a
22063 		 * matching route in the forwarding table.
22064 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22065 		 * ip_newroute() does.
22066 		 * Note that IRE_LOCAL are special, since they are used
22067 		 * when the zoneid doesn't match in some cases. This means that
22068 		 * we need to handle ipha_src differently since ire_src_addr
22069 		 * belongs to the receiving zone instead of the sending zone.
22070 		 * When ip_restrict_interzone_loopback is set, then
22071 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22072 		 * for loopback between zones when the logical "Ethernet" would
22073 		 * have looped them back.
22074 		 */
22075 		ire_t *src_ire;
22076 
22077 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22078 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22079 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22080 		if (src_ire != NULL &&
22081 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22082 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22083 		    ire_local_same_lan(ire, src_ire))) {
22084 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22085 				ipha->ipha_src = src_ire->ire_src_addr;
22086 			ire_refrele(src_ire);
22087 		} else {
22088 			ire_refrele(ire);
22089 			if (conn_outgoing_ill != NULL)
22090 				ill_refrele(conn_outgoing_ill);
22091 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22092 			if (src_ire != NULL) {
22093 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22094 					ire_refrele(src_ire);
22095 					freemsg(mp);
22096 					return;
22097 				}
22098 				ire_refrele(src_ire);
22099 			}
22100 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22101 				/* Failed */
22102 				freemsg(mp);
22103 				return;
22104 			}
22105 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22106 			    ipst);
22107 			return;
22108 		}
22109 	}
22110 
22111 	if (mp->b_datap->db_type == M_CTL ||
22112 	    ipss->ipsec_outbound_v4_policy_present) {
22113 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22114 		    unspec_src, zoneid);
22115 		if (mp == NULL) {
22116 			ire_refrele(ire);
22117 			if (conn_outgoing_ill != NULL)
22118 				ill_refrele(conn_outgoing_ill);
22119 			return;
22120 		}
22121 		/*
22122 		 * Trusted Extensions supports all-zones interfaces, so
22123 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22124 		 * the global zone.
22125 		 */
22126 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22127 			io = (ipsec_out_t *)mp->b_rptr;
22128 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22129 			zoneid = io->ipsec_out_zoneid;
22130 		}
22131 	}
22132 
22133 	first_mp = mp;
22134 	ipsec_len = 0;
22135 
22136 	if (first_mp->b_datap->db_type == M_CTL) {
22137 		io = (ipsec_out_t *)first_mp->b_rptr;
22138 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22139 		mp = first_mp->b_cont;
22140 		ipsec_len = ipsec_out_extra_length(first_mp);
22141 		ASSERT(ipsec_len >= 0);
22142 		/* We already picked up the zoneid from the M_CTL above */
22143 		ASSERT(zoneid == io->ipsec_out_zoneid);
22144 		ASSERT(zoneid != ALL_ZONES);
22145 
22146 		/*
22147 		 * Drop M_CTL here if IPsec processing is not needed.
22148 		 * (Non-IPsec use of M_CTL extracted any information it
22149 		 * needed above).
22150 		 */
22151 		if (ipsec_len == 0) {
22152 			freeb(first_mp);
22153 			first_mp = mp;
22154 		}
22155 	}
22156 
22157 	/*
22158 	 * Fast path for ip_wput_ire
22159 	 */
22160 
22161 	ipha = (ipha_t *)mp->b_rptr;
22162 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22163 	dst = ipha->ipha_dst;
22164 
22165 	/*
22166 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22167 	 * if the socket is a SOCK_RAW type. The transport checksum should
22168 	 * be provided in the pre-built packet, so we don't need to compute it.
22169 	 * Also, other application set flags, like DF, should not be altered.
22170 	 * Other transport MUST pass down zero.
22171 	 */
22172 	ip_hdr_included = ipha->ipha_ident;
22173 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22174 
22175 	if (CLASSD(dst)) {
22176 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22177 		    ntohl(dst),
22178 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22179 		    ntohl(ire->ire_addr)));
22180 	}
22181 
22182 /* Macros to extract header fields from data already in registers */
22183 #ifdef	_BIG_ENDIAN
22184 #define	V_HLEN	(v_hlen_tos_len >> 24)
22185 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22186 #define	PROTO	(ttl_protocol & 0xFF)
22187 #else
22188 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22189 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22190 #define	PROTO	(ttl_protocol >> 8)
22191 #endif
22192 
22193 	orig_src = src = ipha->ipha_src;
22194 	/* (The loop back to "another" is explained down below.) */
22195 another:;
22196 	/*
22197 	 * Assign an ident value for this packet.  We assign idents on
22198 	 * a per destination basis out of the IRE.  There could be
22199 	 * other threads targeting the same destination, so we have to
22200 	 * arrange for a atomic increment.  Note that we use a 32-bit
22201 	 * atomic add because it has better performance than its
22202 	 * 16-bit sibling.
22203 	 *
22204 	 * If running in cluster mode and if the source address
22205 	 * belongs to a replicated service then vector through
22206 	 * cl_inet_ipident vector to allocate ip identifier
22207 	 * NOTE: This is a contract private interface with the
22208 	 * clustering group.
22209 	 */
22210 	clusterwide = 0;
22211 	if (cl_inet_ipident) {
22212 		ASSERT(cl_inet_isclusterwide);
22213 		netstackid_t stack_id = ipst->ips_netstack->netstack_stackid;
22214 
22215 		if ((*cl_inet_isclusterwide)(stack_id, IPPROTO_IP,
22216 		    AF_INET, (uint8_t *)(uintptr_t)src, NULL)) {
22217 			ipha->ipha_ident = (*cl_inet_ipident)(stack_id,
22218 			    IPPROTO_IP, AF_INET, (uint8_t *)(uintptr_t)src,
22219 			    (uint8_t *)(uintptr_t)dst, NULL);
22220 			clusterwide = 1;
22221 		}
22222 	}
22223 	if (!clusterwide) {
22224 		ipha->ipha_ident =
22225 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22226 	}
22227 
22228 #ifndef _BIG_ENDIAN
22229 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22230 #endif
22231 
22232 	/*
22233 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22234 	 * This is needed to obey conn_unspec_src when packets go through
22235 	 * ip_newroute + arp.
22236 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22237 	 */
22238 	if (src == INADDR_ANY && !unspec_src) {
22239 		/*
22240 		 * Assign the appropriate source address from the IRE if none
22241 		 * was specified.
22242 		 */
22243 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22244 
22245 		src = ire->ire_src_addr;
22246 		if (connp == NULL) {
22247 			ip1dbg(("ip_wput_ire: no connp and no src "
22248 			    "address for dst 0x%x, using src 0x%x\n",
22249 			    ntohl(dst),
22250 			    ntohl(src)));
22251 		}
22252 		ipha->ipha_src = src;
22253 	}
22254 	stq = ire->ire_stq;
22255 
22256 	/*
22257 	 * We only allow ire chains for broadcasts since there will
22258 	 * be multiple IRE_CACHE entries for the same multicast
22259 	 * address (one per ipif).
22260 	 */
22261 	next_mp = NULL;
22262 
22263 	/* broadcast packet */
22264 	if (ire->ire_type == IRE_BROADCAST)
22265 		goto broadcast;
22266 
22267 	/* loopback ? */
22268 	if (stq == NULL)
22269 		goto nullstq;
22270 
22271 	/* The ill_index for outbound ILL */
22272 	ill_index = Q_TO_INDEX(stq);
22273 
22274 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22275 	ttl_protocol = ((uint16_t *)ipha)[4];
22276 
22277 	/* pseudo checksum (do it in parts for IP header checksum) */
22278 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22279 
22280 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22281 		queue_t *dev_q = stq->q_next;
22282 
22283 		/* flow controlled */
22284 		if (DEV_Q_FLOW_BLOCKED(dev_q))
22285 			goto blocked;
22286 
22287 		if ((PROTO == IPPROTO_UDP) &&
22288 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22289 			hlen = (V_HLEN & 0xF) << 2;
22290 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22291 			if (*up != 0) {
22292 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22293 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22294 				/* Software checksum? */
22295 				if (DB_CKSUMFLAGS(mp) == 0) {
22296 					IP_STAT(ipst, ip_out_sw_cksum);
22297 					IP_STAT_UPDATE(ipst,
22298 					    ip_udp_out_sw_cksum_bytes,
22299 					    LENGTH - hlen);
22300 				}
22301 			}
22302 		}
22303 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22304 		hlen = (V_HLEN & 0xF) << 2;
22305 		if (PROTO == IPPROTO_TCP) {
22306 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22307 			/*
22308 			 * The packet header is processed once and for all, even
22309 			 * in the multirouting case. We disable hardware
22310 			 * checksum if the packet is multirouted, as it will be
22311 			 * replicated via several interfaces, and not all of
22312 			 * them may have this capability.
22313 			 */
22314 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22315 			    LENGTH, max_frag, ipsec_len, cksum);
22316 			/* Software checksum? */
22317 			if (DB_CKSUMFLAGS(mp) == 0) {
22318 				IP_STAT(ipst, ip_out_sw_cksum);
22319 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22320 				    LENGTH - hlen);
22321 			}
22322 		} else {
22323 			sctp_hdr_t	*sctph;
22324 
22325 			ASSERT(PROTO == IPPROTO_SCTP);
22326 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22327 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22328 			/*
22329 			 * Zero out the checksum field to ensure proper
22330 			 * checksum calculation.
22331 			 */
22332 			sctph->sh_chksum = 0;
22333 #ifdef	DEBUG
22334 			if (!skip_sctp_cksum)
22335 #endif
22336 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22337 		}
22338 	}
22339 
22340 	/*
22341 	 * If this is a multicast packet and originated from ip_wput
22342 	 * we need to do loopback and forwarding checks. If it comes
22343 	 * from ip_wput_multicast, we SHOULD not do this.
22344 	 */
22345 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22346 
22347 	/* checksum */
22348 	cksum += ttl_protocol;
22349 
22350 	/* fragment the packet */
22351 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22352 		goto fragmentit;
22353 	/*
22354 	 * Don't use frag_flag if packet is pre-built or source
22355 	 * routed or if multicast (since multicast packets do
22356 	 * not solicit ICMP "packet too big" messages).
22357 	 */
22358 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22359 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22360 	    !ip_source_route_included(ipha)) &&
22361 	    !CLASSD(ipha->ipha_dst))
22362 		ipha->ipha_fragment_offset_and_flags |=
22363 		    htons(ire->ire_frag_flag);
22364 
22365 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22366 		/* calculate IP header checksum */
22367 		cksum += ipha->ipha_ident;
22368 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22369 		cksum += ipha->ipha_fragment_offset_and_flags;
22370 
22371 		/* IP options present */
22372 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22373 		if (hlen)
22374 			goto checksumoptions;
22375 
22376 		/* calculate hdr checksum */
22377 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22378 		cksum = ~(cksum + (cksum >> 16));
22379 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22380 	}
22381 	if (ipsec_len != 0) {
22382 		/*
22383 		 * We will do the rest of the processing after
22384 		 * we come back from IPsec in ip_wput_ipsec_out().
22385 		 */
22386 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22387 
22388 		io = (ipsec_out_t *)first_mp->b_rptr;
22389 		io->ipsec_out_ill_index =
22390 		    ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
22391 		ipsec_out_process(q, first_mp, ire, 0);
22392 		ire_refrele(ire);
22393 		if (conn_outgoing_ill != NULL)
22394 			ill_refrele(conn_outgoing_ill);
22395 		return;
22396 	}
22397 
22398 	/*
22399 	 * In most cases, the emission loop below is entered only
22400 	 * once. Only in the case where the ire holds the
22401 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22402 	 * flagged ires in the bucket, and send the packet
22403 	 * through all crossed RTF_MULTIRT routes.
22404 	 */
22405 	if (ire->ire_flags & RTF_MULTIRT) {
22406 		multirt_send = B_TRUE;
22407 	}
22408 	do {
22409 		if (multirt_send) {
22410 			irb_t *irb;
22411 			/*
22412 			 * We are in a multiple send case, need to get
22413 			 * the next ire and make a duplicate of the packet.
22414 			 * ire1 holds here the next ire to process in the
22415 			 * bucket. If multirouting is expected,
22416 			 * any non-RTF_MULTIRT ire that has the
22417 			 * right destination address is ignored.
22418 			 */
22419 			irb = ire->ire_bucket;
22420 			ASSERT(irb != NULL);
22421 
22422 			IRB_REFHOLD(irb);
22423 			for (ire1 = ire->ire_next;
22424 			    ire1 != NULL;
22425 			    ire1 = ire1->ire_next) {
22426 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22427 					continue;
22428 				if (ire1->ire_addr != ire->ire_addr)
22429 					continue;
22430 				if (ire1->ire_marks &
22431 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
22432 					continue;
22433 
22434 				/* Got one */
22435 				IRE_REFHOLD(ire1);
22436 				break;
22437 			}
22438 			IRB_REFRELE(irb);
22439 
22440 			if (ire1 != NULL) {
22441 				next_mp = copyb(mp);
22442 				if ((next_mp == NULL) ||
22443 				    ((mp->b_cont != NULL) &&
22444 				    ((next_mp->b_cont =
22445 				    dupmsg(mp->b_cont)) == NULL))) {
22446 					freemsg(next_mp);
22447 					next_mp = NULL;
22448 					ire_refrele(ire1);
22449 					ire1 = NULL;
22450 				}
22451 			}
22452 
22453 			/* Last multiroute ire; don't loop anymore. */
22454 			if (ire1 == NULL) {
22455 				multirt_send = B_FALSE;
22456 			}
22457 		}
22458 
22459 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22460 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22461 		    mblk_t *, mp);
22462 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22463 		    ipst->ips_ipv4firewall_physical_out,
22464 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22465 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22466 
22467 		if (mp == NULL)
22468 			goto release_ire_and_ill;
22469 
22470 		if (ipst->ips_ipobs_enabled) {
22471 			zoneid_t szone;
22472 
22473 			/*
22474 			 * On the outbound path the destination zone will be
22475 			 * unknown as we're sending this packet out on the
22476 			 * wire.
22477 			 */
22478 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
22479 			    ALL_ZONES);
22480 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
22481 			    ire->ire_ipif->ipif_ill, IPV4_VERSION, 0, ipst);
22482 		}
22483 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22484 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22485 
22486 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE, connp);
22487 
22488 		if ((pktxmit_state == SEND_FAILED) ||
22489 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22490 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22491 			    "- packet dropped\n"));
22492 release_ire_and_ill:
22493 			ire_refrele(ire);
22494 			if (next_mp != NULL) {
22495 				freemsg(next_mp);
22496 				ire_refrele(ire1);
22497 			}
22498 			if (conn_outgoing_ill != NULL)
22499 				ill_refrele(conn_outgoing_ill);
22500 			return;
22501 		}
22502 
22503 		if (CLASSD(dst)) {
22504 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22505 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22506 			    LENGTH);
22507 		}
22508 
22509 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22510 		    "ip_wput_ire_end: q %p (%S)",
22511 		    q, "last copy out");
22512 		IRE_REFRELE(ire);
22513 
22514 		if (multirt_send) {
22515 			ASSERT(ire1);
22516 			/*
22517 			 * Proceed with the next RTF_MULTIRT ire,
22518 			 * Also set up the send-to queue accordingly.
22519 			 */
22520 			ire = ire1;
22521 			ire1 = NULL;
22522 			stq = ire->ire_stq;
22523 			mp = next_mp;
22524 			next_mp = NULL;
22525 			ipha = (ipha_t *)mp->b_rptr;
22526 			ill_index = Q_TO_INDEX(stq);
22527 			ill = (ill_t *)stq->q_ptr;
22528 		}
22529 	} while (multirt_send);
22530 	if (conn_outgoing_ill != NULL)
22531 		ill_refrele(conn_outgoing_ill);
22532 	return;
22533 
22534 	/*
22535 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22536 	 */
22537 broadcast:
22538 	{
22539 		/*
22540 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22541 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22542 		 * can be overridden stack-wide through the ip_broadcast_ttl
22543 		 * ndd tunable, or on a per-connection basis through the
22544 		 * IP_BROADCAST_TTL socket option.
22545 		 *
22546 		 * In the event that we are replying to incoming ICMP packets,
22547 		 * connp could be NULL.
22548 		 */
22549 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22550 		if (connp != NULL) {
22551 			if (connp->conn_dontroute)
22552 				ipha->ipha_ttl = 1;
22553 			else if (connp->conn_broadcast_ttl != 0)
22554 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22555 		}
22556 
22557 		/*
22558 		 * Note that we are not doing a IRB_REFHOLD here.
22559 		 * Actually we don't care if the list changes i.e
22560 		 * if somebody deletes an IRE from the list while
22561 		 * we drop the lock, the next time we come around
22562 		 * ire_next will be NULL and hence we won't send
22563 		 * out multiple copies which is fine.
22564 		 */
22565 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22566 		ire1 = ire->ire_next;
22567 		if (conn_outgoing_ill != NULL) {
22568 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22569 				ASSERT(ire1 == ire->ire_next);
22570 				if (ire1 != NULL && ire1->ire_addr == dst) {
22571 					ire_refrele(ire);
22572 					ire = ire1;
22573 					IRE_REFHOLD(ire);
22574 					ire1 = ire->ire_next;
22575 					continue;
22576 				}
22577 				rw_exit(&ire->ire_bucket->irb_lock);
22578 				/* Did not find a matching ill */
22579 				ip1dbg(("ip_wput_ire: broadcast with no "
22580 				    "matching IP_BOUND_IF ill %s dst %x\n",
22581 				    conn_outgoing_ill->ill_name, dst));
22582 				freemsg(first_mp);
22583 				if (ire != NULL)
22584 					ire_refrele(ire);
22585 				ill_refrele(conn_outgoing_ill);
22586 				return;
22587 			}
22588 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22589 			/*
22590 			 * If the next IRE has the same address and is not one
22591 			 * of the two copies that we need to send, try to see
22592 			 * whether this copy should be sent at all. This
22593 			 * assumes that we insert loopbacks first and then
22594 			 * non-loopbacks. This is acheived by inserting the
22595 			 * loopback always before non-loopback.
22596 			 * This is used to send a single copy of a broadcast
22597 			 * packet out all physical interfaces that have an
22598 			 * matching IRE_BROADCAST while also looping
22599 			 * back one copy (to ip_wput_local) for each
22600 			 * matching physical interface. However, we avoid
22601 			 * sending packets out different logical that match by
22602 			 * having ipif_up/ipif_down supress duplicate
22603 			 * IRE_BROADCASTS.
22604 			 *
22605 			 * This feature is currently used to get broadcasts
22606 			 * sent to multiple interfaces, when the broadcast
22607 			 * address being used applies to multiple interfaces.
22608 			 * For example, a whole net broadcast will be
22609 			 * replicated on every connected subnet of
22610 			 * the target net.
22611 			 *
22612 			 * Each zone has its own set of IRE_BROADCASTs, so that
22613 			 * we're able to distribute inbound packets to multiple
22614 			 * zones who share a broadcast address. We avoid looping
22615 			 * back outbound packets in different zones but on the
22616 			 * same ill, as the application would see duplicates.
22617 			 *
22618 			 * This logic assumes that ire_add_v4() groups the
22619 			 * IRE_BROADCAST entries so that those with the same
22620 			 * ire_addr are kept together.
22621 			 */
22622 			ire_ill = ire->ire_ipif->ipif_ill;
22623 			if (ire->ire_stq != NULL || ire1->ire_stq == NULL) {
22624 				while (ire1 != NULL && ire1->ire_addr == dst) {
22625 					ire1_ill = ire1->ire_ipif->ipif_ill;
22626 					if (ire1_ill != ire_ill)
22627 						break;
22628 					ire1 = ire1->ire_next;
22629 				}
22630 			}
22631 		}
22632 		ASSERT(multirt_send == B_FALSE);
22633 		if (ire1 != NULL && ire1->ire_addr == dst) {
22634 			if ((ire->ire_flags & RTF_MULTIRT) &&
22635 			    (ire1->ire_flags & RTF_MULTIRT)) {
22636 				/*
22637 				 * We are in the multirouting case.
22638 				 * The message must be sent at least
22639 				 * on both ires. These ires have been
22640 				 * inserted AFTER the standard ones
22641 				 * in ip_rt_add(). There are thus no
22642 				 * other ire entries for the destination
22643 				 * address in the rest of the bucket
22644 				 * that do not have the RTF_MULTIRT
22645 				 * flag. We don't process a copy
22646 				 * of the message here. This will be
22647 				 * done in the final sending loop.
22648 				 */
22649 				multirt_send = B_TRUE;
22650 			} else {
22651 				next_mp = ip_copymsg(first_mp);
22652 				if (next_mp != NULL)
22653 					IRE_REFHOLD(ire1);
22654 			}
22655 		}
22656 		rw_exit(&ire->ire_bucket->irb_lock);
22657 	}
22658 
22659 	if (stq) {
22660 		/*
22661 		 * A non-NULL send-to queue means this packet is going
22662 		 * out of this machine.
22663 		 */
22664 		out_ill = (ill_t *)stq->q_ptr;
22665 
22666 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22667 		ttl_protocol = ((uint16_t *)ipha)[4];
22668 		/*
22669 		 * We accumulate the pseudo header checksum in cksum.
22670 		 * This is pretty hairy code, so watch close.  One
22671 		 * thing to keep in mind is that UDP and TCP have
22672 		 * stored their respective datagram lengths in their
22673 		 * checksum fields.  This lines things up real nice.
22674 		 */
22675 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22676 		    (src >> 16) + (src & 0xFFFF);
22677 		/*
22678 		 * We assume the udp checksum field contains the
22679 		 * length, so to compute the pseudo header checksum,
22680 		 * all we need is the protocol number and src/dst.
22681 		 */
22682 		/* Provide the checksums for UDP and TCP. */
22683 		if ((PROTO == IPPROTO_TCP) &&
22684 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22685 			/* hlen gets the number of uchar_ts in the IP header */
22686 			hlen = (V_HLEN & 0xF) << 2;
22687 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22688 			IP_STAT(ipst, ip_out_sw_cksum);
22689 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22690 			    LENGTH - hlen);
22691 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22692 		} else if (PROTO == IPPROTO_SCTP &&
22693 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22694 			sctp_hdr_t	*sctph;
22695 
22696 			hlen = (V_HLEN & 0xF) << 2;
22697 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22698 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22699 			sctph->sh_chksum = 0;
22700 #ifdef	DEBUG
22701 			if (!skip_sctp_cksum)
22702 #endif
22703 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22704 		} else {
22705 			queue_t	*dev_q = stq->q_next;
22706 
22707 			if (DEV_Q_FLOW_BLOCKED(dev_q)) {
22708 blocked:
22709 				ipha->ipha_ident = ip_hdr_included;
22710 				/*
22711 				 * If we don't have a conn to apply
22712 				 * backpressure, free the message.
22713 				 * In the ire_send path, we don't know
22714 				 * the position to requeue the packet. Rather
22715 				 * than reorder packets, we just drop this
22716 				 * packet.
22717 				 */
22718 				if (ipst->ips_ip_output_queue &&
22719 				    connp != NULL &&
22720 				    caller != IRE_SEND) {
22721 					if (caller == IP_WSRV) {
22722 						connp->conn_did_putbq = 1;
22723 						(void) putbq(connp->conn_wq,
22724 						    first_mp);
22725 						conn_drain_insert(connp);
22726 						/*
22727 						 * This is the service thread,
22728 						 * and the queue is already
22729 						 * noenabled. The check for
22730 						 * canput and the putbq is not
22731 						 * atomic. So we need to check
22732 						 * again.
22733 						 */
22734 						if (canput(stq->q_next))
22735 							connp->conn_did_putbq
22736 							    = 0;
22737 						IP_STAT(ipst, ip_conn_flputbq);
22738 					} else {
22739 						/*
22740 						 * We are not the service proc.
22741 						 * ip_wsrv will be scheduled or
22742 						 * is already running.
22743 						 */
22744 
22745 						(void) putq(connp->conn_wq,
22746 						    first_mp);
22747 					}
22748 				} else {
22749 					out_ill = (ill_t *)stq->q_ptr;
22750 					BUMP_MIB(out_ill->ill_ip_mib,
22751 					    ipIfStatsOutDiscards);
22752 					freemsg(first_mp);
22753 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22754 					    "ip_wput_ire_end: q %p (%S)",
22755 					    q, "discard");
22756 				}
22757 				ire_refrele(ire);
22758 				if (next_mp) {
22759 					ire_refrele(ire1);
22760 					freemsg(next_mp);
22761 				}
22762 				if (conn_outgoing_ill != NULL)
22763 					ill_refrele(conn_outgoing_ill);
22764 				return;
22765 			}
22766 			if ((PROTO == IPPROTO_UDP) &&
22767 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22768 				/*
22769 				 * hlen gets the number of uchar_ts in the
22770 				 * IP header
22771 				 */
22772 				hlen = (V_HLEN & 0xF) << 2;
22773 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22774 				max_frag = ire->ire_max_frag;
22775 				if (*up != 0) {
22776 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22777 					    up, PROTO, hlen, LENGTH, max_frag,
22778 					    ipsec_len, cksum);
22779 					/* Software checksum? */
22780 					if (DB_CKSUMFLAGS(mp) == 0) {
22781 						IP_STAT(ipst, ip_out_sw_cksum);
22782 						IP_STAT_UPDATE(ipst,
22783 						    ip_udp_out_sw_cksum_bytes,
22784 						    LENGTH - hlen);
22785 					}
22786 				}
22787 			}
22788 		}
22789 		/*
22790 		 * Need to do this even when fragmenting. The local
22791 		 * loopback can be done without computing checksums
22792 		 * but forwarding out other interface must be done
22793 		 * after the IP checksum (and ULP checksums) have been
22794 		 * computed.
22795 		 *
22796 		 * NOTE : multicast_forward is set only if this packet
22797 		 * originated from ip_wput. For packets originating from
22798 		 * ip_wput_multicast, it is not set.
22799 		 */
22800 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22801 multi_loopback:
22802 			ip2dbg(("ip_wput: multicast, loop %d\n",
22803 			    conn_multicast_loop));
22804 
22805 			/*  Forget header checksum offload */
22806 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22807 
22808 			/*
22809 			 * Local loopback of multicasts?  Check the
22810 			 * ill.
22811 			 *
22812 			 * Note that the loopback function will not come
22813 			 * in through ip_rput - it will only do the
22814 			 * client fanout thus we need to do an mforward
22815 			 * as well.  The is different from the BSD
22816 			 * logic.
22817 			 */
22818 			if (ill != NULL) {
22819 				if (ilm_lookup_ill(ill, ipha->ipha_dst,
22820 				    ALL_ZONES) != NULL) {
22821 					/*
22822 					 * Pass along the virtual output q.
22823 					 * ip_wput_local() will distribute the
22824 					 * packet to all the matching zones,
22825 					 * except the sending zone when
22826 					 * IP_MULTICAST_LOOP is false.
22827 					 */
22828 					ip_multicast_loopback(q, ill, first_mp,
22829 					    conn_multicast_loop ? 0 :
22830 					    IP_FF_NO_MCAST_LOOP, zoneid);
22831 				}
22832 			}
22833 			if (ipha->ipha_ttl == 0) {
22834 				/*
22835 				 * 0 => only to this host i.e. we are
22836 				 * done. We are also done if this was the
22837 				 * loopback interface since it is sufficient
22838 				 * to loopback one copy of a multicast packet.
22839 				 */
22840 				freemsg(first_mp);
22841 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22842 				    "ip_wput_ire_end: q %p (%S)",
22843 				    q, "loopback");
22844 				ire_refrele(ire);
22845 				if (conn_outgoing_ill != NULL)
22846 					ill_refrele(conn_outgoing_ill);
22847 				return;
22848 			}
22849 			/*
22850 			 * ILLF_MULTICAST is checked in ip_newroute
22851 			 * i.e. we don't need to check it here since
22852 			 * all IRE_CACHEs come from ip_newroute.
22853 			 * For multicast traffic, SO_DONTROUTE is interpreted
22854 			 * to mean only send the packet out the interface
22855 			 * (optionally specified with IP_MULTICAST_IF)
22856 			 * and do not forward it out additional interfaces.
22857 			 * RSVP and the rsvp daemon is an example of a
22858 			 * protocol and user level process that
22859 			 * handles it's own routing. Hence, it uses the
22860 			 * SO_DONTROUTE option to accomplish this.
22861 			 */
22862 
22863 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
22864 			    ill != NULL) {
22865 				/* Unconditionally redo the checksum */
22866 				ipha->ipha_hdr_checksum = 0;
22867 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22868 
22869 				/*
22870 				 * If this needs to go out secure, we need
22871 				 * to wait till we finish the IPsec
22872 				 * processing.
22873 				 */
22874 				if (ipsec_len == 0 &&
22875 				    ip_mforward(ill, ipha, mp)) {
22876 					freemsg(first_mp);
22877 					ip1dbg(("ip_wput: mforward failed\n"));
22878 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22879 					    "ip_wput_ire_end: q %p (%S)",
22880 					    q, "mforward failed");
22881 					ire_refrele(ire);
22882 					if (conn_outgoing_ill != NULL)
22883 						ill_refrele(conn_outgoing_ill);
22884 					return;
22885 				}
22886 			}
22887 		}
22888 		max_frag = ire->ire_max_frag;
22889 		cksum += ttl_protocol;
22890 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
22891 			/* No fragmentation required for this one. */
22892 			/*
22893 			 * Don't use frag_flag if packet is pre-built or source
22894 			 * routed or if multicast (since multicast packets do
22895 			 * not solicit ICMP "packet too big" messages).
22896 			 */
22897 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22898 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22899 			    !ip_source_route_included(ipha)) &&
22900 			    !CLASSD(ipha->ipha_dst))
22901 				ipha->ipha_fragment_offset_and_flags |=
22902 				    htons(ire->ire_frag_flag);
22903 
22904 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22905 				/* Complete the IP header checksum. */
22906 				cksum += ipha->ipha_ident;
22907 				cksum += (v_hlen_tos_len >> 16)+
22908 				    (v_hlen_tos_len & 0xFFFF);
22909 				cksum += ipha->ipha_fragment_offset_and_flags;
22910 				hlen = (V_HLEN & 0xF) -
22911 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22912 				if (hlen) {
22913 checksumoptions:
22914 					/*
22915 					 * Account for the IP Options in the IP
22916 					 * header checksum.
22917 					 */
22918 					up = (uint16_t *)(rptr+
22919 					    IP_SIMPLE_HDR_LENGTH);
22920 					do {
22921 						cksum += up[0];
22922 						cksum += up[1];
22923 						up += 2;
22924 					} while (--hlen);
22925 				}
22926 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22927 				cksum = ~(cksum + (cksum >> 16));
22928 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
22929 			}
22930 			if (ipsec_len != 0) {
22931 				ipsec_out_process(q, first_mp, ire, ill_index);
22932 				if (!next_mp) {
22933 					ire_refrele(ire);
22934 					if (conn_outgoing_ill != NULL)
22935 						ill_refrele(conn_outgoing_ill);
22936 					return;
22937 				}
22938 				goto next;
22939 			}
22940 
22941 			/*
22942 			 * multirt_send has already been handled
22943 			 * for broadcast, but not yet for multicast
22944 			 * or IP options.
22945 			 */
22946 			if (next_mp == NULL) {
22947 				if (ire->ire_flags & RTF_MULTIRT) {
22948 					multirt_send = B_TRUE;
22949 				}
22950 			}
22951 
22952 			/*
22953 			 * In most cases, the emission loop below is
22954 			 * entered only once. Only in the case where
22955 			 * the ire holds the RTF_MULTIRT flag, do we loop
22956 			 * to process all RTF_MULTIRT ires in the bucket,
22957 			 * and send the packet through all crossed
22958 			 * RTF_MULTIRT routes.
22959 			 */
22960 			do {
22961 				if (multirt_send) {
22962 					irb_t *irb;
22963 
22964 					irb = ire->ire_bucket;
22965 					ASSERT(irb != NULL);
22966 					/*
22967 					 * We are in a multiple send case,
22968 					 * need to get the next IRE and make
22969 					 * a duplicate of the packet.
22970 					 */
22971 					IRB_REFHOLD(irb);
22972 					for (ire1 = ire->ire_next;
22973 					    ire1 != NULL;
22974 					    ire1 = ire1->ire_next) {
22975 						if (!(ire1->ire_flags &
22976 						    RTF_MULTIRT))
22977 							continue;
22978 
22979 						if (ire1->ire_addr !=
22980 						    ire->ire_addr)
22981 							continue;
22982 
22983 						if (ire1->ire_marks &
22984 						    (IRE_MARK_CONDEMNED |
22985 						    IRE_MARK_TESTHIDDEN))
22986 							continue;
22987 
22988 						/* Got one */
22989 						IRE_REFHOLD(ire1);
22990 						break;
22991 					}
22992 					IRB_REFRELE(irb);
22993 
22994 					if (ire1 != NULL) {
22995 						next_mp = copyb(mp);
22996 						if ((next_mp == NULL) ||
22997 						    ((mp->b_cont != NULL) &&
22998 						    ((next_mp->b_cont =
22999 						    dupmsg(mp->b_cont))
23000 						    == NULL))) {
23001 							freemsg(next_mp);
23002 							next_mp = NULL;
23003 							ire_refrele(ire1);
23004 							ire1 = NULL;
23005 						}
23006 					}
23007 
23008 					/*
23009 					 * Last multiroute ire; don't loop
23010 					 * anymore. The emission is over
23011 					 * and next_mp is NULL.
23012 					 */
23013 					if (ire1 == NULL) {
23014 						multirt_send = B_FALSE;
23015 					}
23016 				}
23017 
23018 				out_ill = ire_to_ill(ire);
23019 				DTRACE_PROBE4(ip4__physical__out__start,
23020 				    ill_t *, NULL,
23021 				    ill_t *, out_ill,
23022 				    ipha_t *, ipha, mblk_t *, mp);
23023 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23024 				    ipst->ips_ipv4firewall_physical_out,
23025 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23026 				DTRACE_PROBE1(ip4__physical__out__end,
23027 				    mblk_t *, mp);
23028 				if (mp == NULL)
23029 					goto release_ire_and_ill_2;
23030 
23031 				ASSERT(ipsec_len == 0);
23032 				mp->b_prev =
23033 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23034 				DTRACE_PROBE2(ip__xmit__2,
23035 				    mblk_t *, mp, ire_t *, ire);
23036 				pktxmit_state = ip_xmit_v4(mp, ire,
23037 				    NULL, B_TRUE, connp);
23038 				if ((pktxmit_state == SEND_FAILED) ||
23039 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23040 release_ire_and_ill_2:
23041 					if (next_mp) {
23042 						freemsg(next_mp);
23043 						ire_refrele(ire1);
23044 					}
23045 					ire_refrele(ire);
23046 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23047 					    "ip_wput_ire_end: q %p (%S)",
23048 					    q, "discard MDATA");
23049 					if (conn_outgoing_ill != NULL)
23050 						ill_refrele(conn_outgoing_ill);
23051 					return;
23052 				}
23053 
23054 				if (CLASSD(dst)) {
23055 					BUMP_MIB(out_ill->ill_ip_mib,
23056 					    ipIfStatsHCOutMcastPkts);
23057 					UPDATE_MIB(out_ill->ill_ip_mib,
23058 					    ipIfStatsHCOutMcastOctets,
23059 					    LENGTH);
23060 				} else if (ire->ire_type == IRE_BROADCAST) {
23061 					BUMP_MIB(out_ill->ill_ip_mib,
23062 					    ipIfStatsHCOutBcastPkts);
23063 				}
23064 
23065 				if (multirt_send) {
23066 					/*
23067 					 * We are in a multiple send case,
23068 					 * need to re-enter the sending loop
23069 					 * using the next ire.
23070 					 */
23071 					ire_refrele(ire);
23072 					ire = ire1;
23073 					stq = ire->ire_stq;
23074 					mp = next_mp;
23075 					next_mp = NULL;
23076 					ipha = (ipha_t *)mp->b_rptr;
23077 					ill_index = Q_TO_INDEX(stq);
23078 				}
23079 			} while (multirt_send);
23080 
23081 			if (!next_mp) {
23082 				/*
23083 				 * Last copy going out (the ultra-common
23084 				 * case).  Note that we intentionally replicate
23085 				 * the putnext rather than calling it before
23086 				 * the next_mp check in hopes of a little
23087 				 * tail-call action out of the compiler.
23088 				 */
23089 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23090 				    "ip_wput_ire_end: q %p (%S)",
23091 				    q, "last copy out(1)");
23092 				ire_refrele(ire);
23093 				if (conn_outgoing_ill != NULL)
23094 					ill_refrele(conn_outgoing_ill);
23095 				return;
23096 			}
23097 			/* More copies going out below. */
23098 		} else {
23099 			int offset;
23100 fragmentit:
23101 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23102 			/*
23103 			 * If this would generate a icmp_frag_needed message,
23104 			 * we need to handle it before we do the IPsec
23105 			 * processing. Otherwise, we need to strip the IPsec
23106 			 * headers before we send up the message to the ULPs
23107 			 * which becomes messy and difficult.
23108 			 */
23109 			if (ipsec_len != 0) {
23110 				if ((max_frag < (unsigned int)(LENGTH +
23111 				    ipsec_len)) && (offset & IPH_DF)) {
23112 					out_ill = (ill_t *)stq->q_ptr;
23113 					BUMP_MIB(out_ill->ill_ip_mib,
23114 					    ipIfStatsOutFragFails);
23115 					BUMP_MIB(out_ill->ill_ip_mib,
23116 					    ipIfStatsOutFragReqds);
23117 					ipha->ipha_hdr_checksum = 0;
23118 					ipha->ipha_hdr_checksum =
23119 					    (uint16_t)ip_csum_hdr(ipha);
23120 					icmp_frag_needed(ire->ire_stq, first_mp,
23121 					    max_frag, zoneid, ipst);
23122 					if (!next_mp) {
23123 						ire_refrele(ire);
23124 						if (conn_outgoing_ill != NULL) {
23125 							ill_refrele(
23126 							    conn_outgoing_ill);
23127 						}
23128 						return;
23129 					}
23130 				} else {
23131 					/*
23132 					 * This won't cause a icmp_frag_needed
23133 					 * message. to be generated. Send it on
23134 					 * the wire. Note that this could still
23135 					 * cause fragmentation and all we
23136 					 * do is the generation of the message
23137 					 * to the ULP if needed before IPsec.
23138 					 */
23139 					if (!next_mp) {
23140 						ipsec_out_process(q, first_mp,
23141 						    ire, ill_index);
23142 						TRACE_2(TR_FAC_IP,
23143 						    TR_IP_WPUT_IRE_END,
23144 						    "ip_wput_ire_end: q %p "
23145 						    "(%S)", q,
23146 						    "last ipsec_out_process");
23147 						ire_refrele(ire);
23148 						if (conn_outgoing_ill != NULL) {
23149 							ill_refrele(
23150 							    conn_outgoing_ill);
23151 						}
23152 						return;
23153 					}
23154 					ipsec_out_process(q, first_mp,
23155 					    ire, ill_index);
23156 				}
23157 			} else {
23158 				/*
23159 				 * Initiate IPPF processing. For
23160 				 * fragmentable packets we finish
23161 				 * all QOS packet processing before
23162 				 * calling:
23163 				 * ip_wput_ire_fragmentit->ip_wput_frag
23164 				 */
23165 
23166 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23167 					ip_process(IPP_LOCAL_OUT, &mp,
23168 					    ill_index);
23169 					if (mp == NULL) {
23170 						out_ill = (ill_t *)stq->q_ptr;
23171 						BUMP_MIB(out_ill->ill_ip_mib,
23172 						    ipIfStatsOutDiscards);
23173 						if (next_mp != NULL) {
23174 							freemsg(next_mp);
23175 							ire_refrele(ire1);
23176 						}
23177 						ire_refrele(ire);
23178 						TRACE_2(TR_FAC_IP,
23179 						    TR_IP_WPUT_IRE_END,
23180 						    "ip_wput_ire: q %p (%S)",
23181 						    q, "discard MDATA");
23182 						if (conn_outgoing_ill != NULL) {
23183 							ill_refrele(
23184 							    conn_outgoing_ill);
23185 						}
23186 						return;
23187 					}
23188 				}
23189 				if (!next_mp) {
23190 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23191 					    "ip_wput_ire_end: q %p (%S)",
23192 					    q, "last fragmentation");
23193 					ip_wput_ire_fragmentit(mp, ire,
23194 					    zoneid, ipst, connp);
23195 					ire_refrele(ire);
23196 					if (conn_outgoing_ill != NULL)
23197 						ill_refrele(conn_outgoing_ill);
23198 					return;
23199 				}
23200 				ip_wput_ire_fragmentit(mp, ire,
23201 				    zoneid, ipst, connp);
23202 			}
23203 		}
23204 	} else {
23205 nullstq:
23206 		/* A NULL stq means the destination address is local. */
23207 		UPDATE_OB_PKT_COUNT(ire);
23208 		ire->ire_last_used_time = lbolt;
23209 		ASSERT(ire->ire_ipif != NULL);
23210 		if (!next_mp) {
23211 			/*
23212 			 * Is there an "in" and "out" for traffic local
23213 			 * to a host (loopback)?  The code in Solaris doesn't
23214 			 * explicitly draw a line in its code for in vs out,
23215 			 * so we've had to draw a line in the sand: ip_wput_ire
23216 			 * is considered to be the "output" side and
23217 			 * ip_wput_local to be the "input" side.
23218 			 */
23219 			out_ill = ire_to_ill(ire);
23220 
23221 			/*
23222 			 * DTrace this as ip:::send.  A blocked packet will
23223 			 * fire the send probe, but not the receive probe.
23224 			 */
23225 			DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23226 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23227 			    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23228 
23229 			DTRACE_PROBE4(ip4__loopback__out__start,
23230 			    ill_t *, NULL, ill_t *, out_ill,
23231 			    ipha_t *, ipha, mblk_t *, first_mp);
23232 
23233 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23234 			    ipst->ips_ipv4firewall_loopback_out,
23235 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23236 
23237 			DTRACE_PROBE1(ip4__loopback__out_end,
23238 			    mblk_t *, first_mp);
23239 
23240 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23241 			    "ip_wput_ire_end: q %p (%S)",
23242 			    q, "local address");
23243 
23244 			if (first_mp != NULL)
23245 				ip_wput_local(q, out_ill, ipha,
23246 				    first_mp, ire, 0, ire->ire_zoneid);
23247 			ire_refrele(ire);
23248 			if (conn_outgoing_ill != NULL)
23249 				ill_refrele(conn_outgoing_ill);
23250 			return;
23251 		}
23252 
23253 		out_ill = ire_to_ill(ire);
23254 
23255 		/*
23256 		 * DTrace this as ip:::send.  A blocked packet will fire the
23257 		 * send probe, but not the receive probe.
23258 		 */
23259 		DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23260 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23261 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23262 
23263 		DTRACE_PROBE4(ip4__loopback__out__start,
23264 		    ill_t *, NULL, ill_t *, out_ill,
23265 		    ipha_t *, ipha, mblk_t *, first_mp);
23266 
23267 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23268 		    ipst->ips_ipv4firewall_loopback_out,
23269 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23270 
23271 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23272 
23273 		if (first_mp != NULL)
23274 			ip_wput_local(q, out_ill, ipha,
23275 			    first_mp, ire, 0, ire->ire_zoneid);
23276 	}
23277 next:
23278 	/*
23279 	 * More copies going out to additional interfaces.
23280 	 * ire1 has already been held. We don't need the
23281 	 * "ire" anymore.
23282 	 */
23283 	ire_refrele(ire);
23284 	ire = ire1;
23285 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23286 	mp = next_mp;
23287 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23288 	ill = ire_to_ill(ire);
23289 	first_mp = mp;
23290 	if (ipsec_len != 0) {
23291 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23292 		mp = mp->b_cont;
23293 	}
23294 	dst = ire->ire_addr;
23295 	ipha = (ipha_t *)mp->b_rptr;
23296 	/*
23297 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23298 	 * Restore ipha_ident "no checksum" flag.
23299 	 */
23300 	src = orig_src;
23301 	ipha->ipha_ident = ip_hdr_included;
23302 	goto another;
23303 
23304 #undef	rptr
23305 #undef	Q_TO_INDEX
23306 }
23307 
23308 /*
23309  * Routine to allocate a message that is used to notify the ULP about MDT.
23310  * The caller may provide a pointer to the link-layer MDT capabilities,
23311  * or NULL if MDT is to be disabled on the stream.
23312  */
23313 mblk_t *
23314 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23315 {
23316 	mblk_t *mp;
23317 	ip_mdt_info_t *mdti;
23318 	ill_mdt_capab_t *idst;
23319 
23320 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23321 		DB_TYPE(mp) = M_CTL;
23322 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23323 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23324 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23325 		idst = &(mdti->mdt_capab);
23326 
23327 		/*
23328 		 * If the caller provides us with the capability, copy
23329 		 * it over into our notification message; otherwise
23330 		 * we zero out the capability portion.
23331 		 */
23332 		if (isrc != NULL)
23333 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23334 		else
23335 			bzero((caddr_t)idst, sizeof (*idst));
23336 	}
23337 	return (mp);
23338 }
23339 
23340 /*
23341  * Routine which determines whether MDT can be enabled on the destination
23342  * IRE and IPC combination, and if so, allocates and returns the MDT
23343  * notification mblk that may be used by ULP.  We also check if we need to
23344  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23345  * MDT usage in the past have been lifted.  This gets called during IP
23346  * and ULP binding.
23347  */
23348 mblk_t *
23349 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23350     ill_mdt_capab_t *mdt_cap)
23351 {
23352 	mblk_t *mp;
23353 	boolean_t rc = B_FALSE;
23354 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23355 
23356 	ASSERT(dst_ire != NULL);
23357 	ASSERT(connp != NULL);
23358 	ASSERT(mdt_cap != NULL);
23359 
23360 	/*
23361 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23362 	 * Multidata, which is handled in tcp_multisend().  This
23363 	 * is the reason why we do all these checks here, to ensure
23364 	 * that we don't enable Multidata for the cases which we
23365 	 * can't handle at the moment.
23366 	 */
23367 	do {
23368 		/* Only do TCP at the moment */
23369 		if (connp->conn_ulp != IPPROTO_TCP)
23370 			break;
23371 
23372 		/*
23373 		 * IPsec outbound policy present?  Note that we get here
23374 		 * after calling ipsec_conn_cache_policy() where the global
23375 		 * policy checking is performed.  conn_latch will be
23376 		 * non-NULL as long as there's a policy defined,
23377 		 * i.e. conn_out_enforce_policy may be NULL in such case
23378 		 * when the connection is non-secure, and hence we check
23379 		 * further if the latch refers to an outbound policy.
23380 		 */
23381 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23382 			break;
23383 
23384 		/* CGTP (multiroute) is enabled? */
23385 		if (dst_ire->ire_flags & RTF_MULTIRT)
23386 			break;
23387 
23388 		/* Outbound IPQoS enabled? */
23389 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23390 			/*
23391 			 * In this case, we disable MDT for this and all
23392 			 * future connections going over the interface.
23393 			 */
23394 			mdt_cap->ill_mdt_on = 0;
23395 			break;
23396 		}
23397 
23398 		/* socket option(s) present? */
23399 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23400 			break;
23401 
23402 		rc = B_TRUE;
23403 	/* CONSTCOND */
23404 	} while (0);
23405 
23406 	/* Remember the result */
23407 	connp->conn_mdt_ok = rc;
23408 
23409 	if (!rc)
23410 		return (NULL);
23411 	else if (!mdt_cap->ill_mdt_on) {
23412 		/*
23413 		 * If MDT has been previously turned off in the past, and we
23414 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23415 		 * then enable it for this interface.
23416 		 */
23417 		mdt_cap->ill_mdt_on = 1;
23418 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23419 		    "interface %s\n", ill_name));
23420 	}
23421 
23422 	/* Allocate the MDT info mblk */
23423 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23424 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23425 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23426 		return (NULL);
23427 	}
23428 	return (mp);
23429 }
23430 
23431 /*
23432  * Routine to allocate a message that is used to notify the ULP about LSO.
23433  * The caller may provide a pointer to the link-layer LSO capabilities,
23434  * or NULL if LSO is to be disabled on the stream.
23435  */
23436 mblk_t *
23437 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23438 {
23439 	mblk_t *mp;
23440 	ip_lso_info_t *lsoi;
23441 	ill_lso_capab_t *idst;
23442 
23443 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23444 		DB_TYPE(mp) = M_CTL;
23445 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23446 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23447 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23448 		idst = &(lsoi->lso_capab);
23449 
23450 		/*
23451 		 * If the caller provides us with the capability, copy
23452 		 * it over into our notification message; otherwise
23453 		 * we zero out the capability portion.
23454 		 */
23455 		if (isrc != NULL)
23456 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23457 		else
23458 			bzero((caddr_t)idst, sizeof (*idst));
23459 	}
23460 	return (mp);
23461 }
23462 
23463 /*
23464  * Routine which determines whether LSO can be enabled on the destination
23465  * IRE and IPC combination, and if so, allocates and returns the LSO
23466  * notification mblk that may be used by ULP.  We also check if we need to
23467  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23468  * LSO usage in the past have been lifted.  This gets called during IP
23469  * and ULP binding.
23470  */
23471 mblk_t *
23472 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23473     ill_lso_capab_t *lso_cap)
23474 {
23475 	mblk_t *mp;
23476 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23477 
23478 	ASSERT(dst_ire != NULL);
23479 	ASSERT(connp != NULL);
23480 	ASSERT(lso_cap != NULL);
23481 
23482 	connp->conn_lso_ok = B_TRUE;
23483 
23484 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23485 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23486 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23487 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23488 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23489 		connp->conn_lso_ok = B_FALSE;
23490 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23491 			/*
23492 			 * Disable LSO for this and all future connections going
23493 			 * over the interface.
23494 			 */
23495 			lso_cap->ill_lso_on = 0;
23496 		}
23497 	}
23498 
23499 	if (!connp->conn_lso_ok)
23500 		return (NULL);
23501 	else if (!lso_cap->ill_lso_on) {
23502 		/*
23503 		 * If LSO has been previously turned off in the past, and we
23504 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23505 		 * then enable it for this interface.
23506 		 */
23507 		lso_cap->ill_lso_on = 1;
23508 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23509 		    ill_name));
23510 	}
23511 
23512 	/* Allocate the LSO info mblk */
23513 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23514 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23515 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23516 
23517 	return (mp);
23518 }
23519 
23520 /*
23521  * Create destination address attribute, and fill it with the physical
23522  * destination address and SAP taken from the template DL_UNITDATA_REQ
23523  * message block.
23524  */
23525 boolean_t
23526 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23527 {
23528 	dl_unitdata_req_t *dlurp;
23529 	pattr_t *pa;
23530 	pattrinfo_t pa_info;
23531 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23532 	uint_t das_len, das_off;
23533 
23534 	ASSERT(dlmp != NULL);
23535 
23536 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23537 	das_len = dlurp->dl_dest_addr_length;
23538 	das_off = dlurp->dl_dest_addr_offset;
23539 
23540 	pa_info.type = PATTR_DSTADDRSAP;
23541 	pa_info.len = sizeof (**das) + das_len - 1;
23542 
23543 	/* create and associate the attribute */
23544 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23545 	if (pa != NULL) {
23546 		ASSERT(*das != NULL);
23547 		(*das)->addr_is_group = 0;
23548 		(*das)->addr_len = (uint8_t)das_len;
23549 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23550 	}
23551 
23552 	return (pa != NULL);
23553 }
23554 
23555 /*
23556  * Create hardware checksum attribute and fill it with the values passed.
23557  */
23558 boolean_t
23559 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23560     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23561 {
23562 	pattr_t *pa;
23563 	pattrinfo_t pa_info;
23564 
23565 	ASSERT(mmd != NULL);
23566 
23567 	pa_info.type = PATTR_HCKSUM;
23568 	pa_info.len = sizeof (pattr_hcksum_t);
23569 
23570 	/* create and associate the attribute */
23571 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23572 	if (pa != NULL) {
23573 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23574 
23575 		hck->hcksum_start_offset = start_offset;
23576 		hck->hcksum_stuff_offset = stuff_offset;
23577 		hck->hcksum_end_offset = end_offset;
23578 		hck->hcksum_flags = flags;
23579 	}
23580 	return (pa != NULL);
23581 }
23582 
23583 /*
23584  * Create zerocopy attribute and fill it with the specified flags
23585  */
23586 boolean_t
23587 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23588 {
23589 	pattr_t *pa;
23590 	pattrinfo_t pa_info;
23591 
23592 	ASSERT(mmd != NULL);
23593 	pa_info.type = PATTR_ZCOPY;
23594 	pa_info.len = sizeof (pattr_zcopy_t);
23595 
23596 	/* create and associate the attribute */
23597 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23598 	if (pa != NULL) {
23599 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23600 
23601 		zcopy->zcopy_flags = flags;
23602 	}
23603 	return (pa != NULL);
23604 }
23605 
23606 /*
23607  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23608  * block chain. We could rewrite to handle arbitrary message block chains but
23609  * that would make the code complicated and slow. Right now there three
23610  * restrictions:
23611  *
23612  *   1. The first message block must contain the complete IP header and
23613  *	at least 1 byte of payload data.
23614  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23615  *	so that we can use a single Multidata message.
23616  *   3. No frag must be distributed over two or more message blocks so
23617  *	that we don't need more than two packet descriptors per frag.
23618  *
23619  * The above restrictions allow us to support userland applications (which
23620  * will send down a single message block) and NFS over UDP (which will
23621  * send down a chain of at most three message blocks).
23622  *
23623  * We also don't use MDT for payloads with less than or equal to
23624  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23625  */
23626 boolean_t
23627 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23628 {
23629 	int	blocks;
23630 	ssize_t	total, missing, size;
23631 
23632 	ASSERT(mp != NULL);
23633 	ASSERT(hdr_len > 0);
23634 
23635 	size = MBLKL(mp) - hdr_len;
23636 	if (size <= 0)
23637 		return (B_FALSE);
23638 
23639 	/* The first mblk contains the header and some payload. */
23640 	blocks = 1;
23641 	total = size;
23642 	size %= len;
23643 	missing = (size == 0) ? 0 : (len - size);
23644 	mp = mp->b_cont;
23645 
23646 	while (mp != NULL) {
23647 		/*
23648 		 * Give up if we encounter a zero length message block.
23649 		 * In practice, this should rarely happen and therefore
23650 		 * not worth the trouble of freeing and re-linking the
23651 		 * mblk from the chain to handle such case.
23652 		 */
23653 		if ((size = MBLKL(mp)) == 0)
23654 			return (B_FALSE);
23655 
23656 		/* Too many payload buffers for a single Multidata message? */
23657 		if (++blocks > MULTIDATA_MAX_PBUFS)
23658 			return (B_FALSE);
23659 
23660 		total += size;
23661 		/* Is a frag distributed over two or more message blocks? */
23662 		if (missing > size)
23663 			return (B_FALSE);
23664 		size -= missing;
23665 
23666 		size %= len;
23667 		missing = (size == 0) ? 0 : (len - size);
23668 
23669 		mp = mp->b_cont;
23670 	}
23671 
23672 	return (total > ip_wput_frag_mdt_min);
23673 }
23674 
23675 /*
23676  * Outbound IPv4 fragmentation routine using MDT.
23677  */
23678 static void
23679 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23680     uint32_t frag_flag, int offset)
23681 {
23682 	ipha_t		*ipha_orig;
23683 	int		i1, ip_data_end;
23684 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23685 	mblk_t		*hdr_mp, *md_mp = NULL;
23686 	unsigned char	*hdr_ptr, *pld_ptr;
23687 	multidata_t	*mmd;
23688 	ip_pdescinfo_t	pdi;
23689 	ill_t		*ill;
23690 	ip_stack_t	*ipst = ire->ire_ipst;
23691 
23692 	ASSERT(DB_TYPE(mp) == M_DATA);
23693 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23694 
23695 	ill = ire_to_ill(ire);
23696 	ASSERT(ill != NULL);
23697 
23698 	ipha_orig = (ipha_t *)mp->b_rptr;
23699 	mp->b_rptr += sizeof (ipha_t);
23700 
23701 	/* Calculate how many packets we will send out */
23702 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23703 	pkts = (i1 + len - 1) / len;
23704 	ASSERT(pkts > 1);
23705 
23706 	/* Allocate a message block which will hold all the IP Headers. */
23707 	wroff = ipst->ips_ip_wroff_extra;
23708 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23709 
23710 	i1 = pkts * hdr_chunk_len;
23711 	/*
23712 	 * Create the header buffer, Multidata and destination address
23713 	 * and SAP attribute that should be associated with it.
23714 	 */
23715 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23716 	    ((hdr_mp->b_wptr += i1),
23717 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23718 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23719 		freemsg(mp);
23720 		if (md_mp == NULL) {
23721 			freemsg(hdr_mp);
23722 		} else {
23723 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23724 			freemsg(md_mp);
23725 		}
23726 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23727 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23728 		return;
23729 	}
23730 	IP_STAT(ipst, ip_frag_mdt_allocd);
23731 
23732 	/*
23733 	 * Add a payload buffer to the Multidata; this operation must not
23734 	 * fail, or otherwise our logic in this routine is broken.  There
23735 	 * is no memory allocation done by the routine, so any returned
23736 	 * failure simply tells us that we've done something wrong.
23737 	 *
23738 	 * A failure tells us that either we're adding the same payload
23739 	 * buffer more than once, or we're trying to add more buffers than
23740 	 * allowed.  None of the above cases should happen, and we panic
23741 	 * because either there's horrible heap corruption, and/or
23742 	 * programming mistake.
23743 	 */
23744 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23745 		goto pbuf_panic;
23746 
23747 	hdr_ptr = hdr_mp->b_rptr;
23748 	pld_ptr = mp->b_rptr;
23749 
23750 	/* Establish the ending byte offset, based on the starting offset. */
23751 	offset <<= 3;
23752 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23753 	    IP_SIMPLE_HDR_LENGTH;
23754 
23755 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23756 
23757 	while (pld_ptr < mp->b_wptr) {
23758 		ipha_t		*ipha;
23759 		uint16_t	offset_and_flags;
23760 		uint16_t	ip_len;
23761 		int		error;
23762 
23763 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23764 		ipha = (ipha_t *)(hdr_ptr + wroff);
23765 		ASSERT(OK_32PTR(ipha));
23766 		*ipha = *ipha_orig;
23767 
23768 		if (ip_data_end - offset > len) {
23769 			offset_and_flags = IPH_MF;
23770 		} else {
23771 			/*
23772 			 * Last frag. Set len to the length of this last piece.
23773 			 */
23774 			len = ip_data_end - offset;
23775 			/* A frag of a frag might have IPH_MF non-zero */
23776 			offset_and_flags =
23777 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23778 			    IPH_MF;
23779 		}
23780 		offset_and_flags |= (uint16_t)(offset >> 3);
23781 		offset_and_flags |= (uint16_t)frag_flag;
23782 		/* Store the offset and flags in the IP header. */
23783 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23784 
23785 		/* Store the length in the IP header. */
23786 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23787 		ipha->ipha_length = htons(ip_len);
23788 
23789 		/*
23790 		 * Set the IP header checksum.  Note that mp is just
23791 		 * the header, so this is easy to pass to ip_csum.
23792 		 */
23793 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23794 
23795 		DTRACE_IP7(send, mblk_t *, md_mp, conn_t *, NULL, void_ip_t *,
23796 		    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *,
23797 		    NULL, int, 0);
23798 
23799 		/*
23800 		 * Record offset and size of header and data of the next packet
23801 		 * in the multidata message.
23802 		 */
23803 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23804 		PDESC_PLD_INIT(&pdi);
23805 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23806 		ASSERT(i1 > 0);
23807 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23808 		if (i1 == len) {
23809 			pld_ptr += len;
23810 		} else {
23811 			i1 = len - i1;
23812 			mp = mp->b_cont;
23813 			ASSERT(mp != NULL);
23814 			ASSERT(MBLKL(mp) >= i1);
23815 			/*
23816 			 * Attach the next payload message block to the
23817 			 * multidata message.
23818 			 */
23819 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23820 				goto pbuf_panic;
23821 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23822 			pld_ptr = mp->b_rptr + i1;
23823 		}
23824 
23825 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23826 		    KM_NOSLEEP)) == NULL) {
23827 			/*
23828 			 * Any failure other than ENOMEM indicates that we
23829 			 * have passed in invalid pdesc info or parameters
23830 			 * to mmd_addpdesc, which must not happen.
23831 			 *
23832 			 * EINVAL is a result of failure on boundary checks
23833 			 * against the pdesc info contents.  It should not
23834 			 * happen, and we panic because either there's
23835 			 * horrible heap corruption, and/or programming
23836 			 * mistake.
23837 			 */
23838 			if (error != ENOMEM) {
23839 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23840 				    "pdesc logic error detected for "
23841 				    "mmd %p pinfo %p (%d)\n",
23842 				    (void *)mmd, (void *)&pdi, error);
23843 				/* NOTREACHED */
23844 			}
23845 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
23846 			/* Free unattached payload message blocks as well */
23847 			md_mp->b_cont = mp->b_cont;
23848 			goto free_mmd;
23849 		}
23850 
23851 		/* Advance fragment offset. */
23852 		offset += len;
23853 
23854 		/* Advance to location for next header in the buffer. */
23855 		hdr_ptr += hdr_chunk_len;
23856 
23857 		/* Did we reach the next payload message block? */
23858 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23859 			mp = mp->b_cont;
23860 			/*
23861 			 * Attach the next message block with payload
23862 			 * data to the multidata message.
23863 			 */
23864 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23865 				goto pbuf_panic;
23866 			pld_ptr = mp->b_rptr;
23867 		}
23868 	}
23869 
23870 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23871 	ASSERT(mp->b_wptr == pld_ptr);
23872 
23873 	/* Update IP statistics */
23874 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
23875 
23876 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
23877 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
23878 
23879 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
23880 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
23881 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
23882 
23883 	if (pkt_type == OB_PKT) {
23884 		ire->ire_ob_pkt_count += pkts;
23885 		if (ire->ire_ipif != NULL)
23886 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23887 	} else {
23888 		/* The type is IB_PKT in the forwarding path. */
23889 		ire->ire_ib_pkt_count += pkts;
23890 		ASSERT(!IRE_IS_LOCAL(ire));
23891 		if (ire->ire_type & IRE_BROADCAST) {
23892 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23893 		} else {
23894 			UPDATE_MIB(ill->ill_ip_mib,
23895 			    ipIfStatsHCOutForwDatagrams, pkts);
23896 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
23897 		}
23898 	}
23899 	ire->ire_last_used_time = lbolt;
23900 	/* Send it down */
23901 	putnext(ire->ire_stq, md_mp);
23902 	return;
23903 
23904 pbuf_panic:
23905 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
23906 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
23907 	    pbuf_idx);
23908 	/* NOTREACHED */
23909 }
23910 
23911 /*
23912  * Outbound IP fragmentation routine.
23913  *
23914  * NOTE : This routine does not ire_refrele the ire that is passed in
23915  * as the argument.
23916  */
23917 static void
23918 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
23919     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst, conn_t *connp)
23920 {
23921 	int		i1;
23922 	mblk_t		*ll_hdr_mp;
23923 	int 		ll_hdr_len;
23924 	int		hdr_len;
23925 	mblk_t		*hdr_mp;
23926 	ipha_t		*ipha;
23927 	int		ip_data_end;
23928 	int		len;
23929 	mblk_t		*mp = mp_orig, *mp1;
23930 	int		offset;
23931 	queue_t		*q;
23932 	uint32_t	v_hlen_tos_len;
23933 	mblk_t		*first_mp;
23934 	boolean_t	mctl_present;
23935 	ill_t		*ill;
23936 	ill_t		*out_ill;
23937 	mblk_t		*xmit_mp;
23938 	mblk_t		*carve_mp;
23939 	ire_t		*ire1 = NULL;
23940 	ire_t		*save_ire = NULL;
23941 	mblk_t  	*next_mp = NULL;
23942 	boolean_t	last_frag = B_FALSE;
23943 	boolean_t	multirt_send = B_FALSE;
23944 	ire_t		*first_ire = NULL;
23945 	irb_t		*irb = NULL;
23946 	mib2_ipIfStatsEntry_t *mibptr = NULL;
23947 
23948 	ill = ire_to_ill(ire);
23949 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
23950 
23951 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
23952 
23953 	if (max_frag == 0) {
23954 		ip1dbg(("ip_wput_frag: ire frag size is 0"
23955 		    " -  dropping packet\n"));
23956 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
23957 		freemsg(mp);
23958 		return;
23959 	}
23960 
23961 	/*
23962 	 * IPsec does not allow hw accelerated packets to be fragmented
23963 	 * This check is made in ip_wput_ipsec_out prior to coming here
23964 	 * via ip_wput_ire_fragmentit.
23965 	 *
23966 	 * If at this point we have an ire whose ARP request has not
23967 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
23968 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
23969 	 * This packet and all fragmentable packets for this ire will
23970 	 * continue to get dropped while ire_nce->nce_state remains in
23971 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
23972 	 * ND_REACHABLE, all subsquent large packets for this ire will
23973 	 * get fragemented and sent out by this function.
23974 	 */
23975 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
23976 		/* If nce_state is ND_INITIAL, trigger ARP query */
23977 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
23978 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
23979 		    " -  dropping packet\n"));
23980 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
23981 		freemsg(mp);
23982 		return;
23983 	}
23984 
23985 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
23986 	    "ip_wput_frag_start:");
23987 
23988 	if (mp->b_datap->db_type == M_CTL) {
23989 		first_mp = mp;
23990 		mp_orig = mp = mp->b_cont;
23991 		mctl_present = B_TRUE;
23992 	} else {
23993 		first_mp = mp;
23994 		mctl_present = B_FALSE;
23995 	}
23996 
23997 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
23998 	ipha = (ipha_t *)mp->b_rptr;
23999 
24000 	/*
24001 	 * If the Don't Fragment flag is on, generate an ICMP destination
24002 	 * unreachable, fragmentation needed.
24003 	 */
24004 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24005 	if (offset & IPH_DF) {
24006 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24007 		if (is_system_labeled()) {
24008 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24009 			    ire->ire_max_frag - max_frag, AF_INET);
24010 		}
24011 		/*
24012 		 * Need to compute hdr checksum if called from ip_wput_ire.
24013 		 * Note that ip_rput_forward verifies the checksum before
24014 		 * calling this routine so in that case this is a noop.
24015 		 */
24016 		ipha->ipha_hdr_checksum = 0;
24017 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24018 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24019 		    ipst);
24020 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24021 		    "ip_wput_frag_end:(%S)",
24022 		    "don't fragment");
24023 		return;
24024 	}
24025 	/*
24026 	 * Labeled systems adjust max_frag if they add a label
24027 	 * to send the correct path mtu.  We need the real mtu since we
24028 	 * are fragmenting the packet after label adjustment.
24029 	 */
24030 	if (is_system_labeled())
24031 		max_frag = ire->ire_max_frag;
24032 	if (mctl_present)
24033 		freeb(first_mp);
24034 	/*
24035 	 * Establish the starting offset.  May not be zero if we are fragging
24036 	 * a fragment that is being forwarded.
24037 	 */
24038 	offset = offset & IPH_OFFSET;
24039 
24040 	/* TODO why is this test needed? */
24041 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24042 	if (((max_frag - LENGTH) & ~7) < 8) {
24043 		/* TODO: notify ulp somehow */
24044 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24045 		freemsg(mp);
24046 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24047 		    "ip_wput_frag_end:(%S)",
24048 		    "len < 8");
24049 		return;
24050 	}
24051 
24052 	hdr_len = (V_HLEN & 0xF) << 2;
24053 
24054 	ipha->ipha_hdr_checksum = 0;
24055 
24056 	/*
24057 	 * Establish the number of bytes maximum per frag, after putting
24058 	 * in the header.
24059 	 */
24060 	len = (max_frag - hdr_len) & ~7;
24061 
24062 	/* Check if we can use MDT to send out the frags. */
24063 	ASSERT(!IRE_IS_LOCAL(ire));
24064 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24065 	    ipst->ips_ip_multidata_outbound &&
24066 	    !(ire->ire_flags & RTF_MULTIRT) &&
24067 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24068 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24069 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24070 		ASSERT(ill->ill_mdt_capab != NULL);
24071 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24072 			/*
24073 			 * If MDT has been previously turned off in the past,
24074 			 * and we currently can do MDT (due to IPQoS policy
24075 			 * removal, etc.) then enable it for this interface.
24076 			 */
24077 			ill->ill_mdt_capab->ill_mdt_on = 1;
24078 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24079 			    ill->ill_name));
24080 		}
24081 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24082 		    offset);
24083 		return;
24084 	}
24085 
24086 	/* Get a copy of the header for the trailing frags */
24087 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24088 	if (!hdr_mp) {
24089 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24090 		freemsg(mp);
24091 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24092 		    "ip_wput_frag_end:(%S)",
24093 		    "couldn't copy hdr");
24094 		return;
24095 	}
24096 	if (DB_CRED(mp) != NULL)
24097 		mblk_setcred(hdr_mp, DB_CRED(mp));
24098 
24099 	/* Store the starting offset, with the MoreFrags flag. */
24100 	i1 = offset | IPH_MF | frag_flag;
24101 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24102 
24103 	/* Establish the ending byte offset, based on the starting offset. */
24104 	offset <<= 3;
24105 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24106 
24107 	/* Store the length of the first fragment in the IP header. */
24108 	i1 = len + hdr_len;
24109 	ASSERT(i1 <= IP_MAXPACKET);
24110 	ipha->ipha_length = htons((uint16_t)i1);
24111 
24112 	/*
24113 	 * Compute the IP header checksum for the first frag.  We have to
24114 	 * watch out that we stop at the end of the header.
24115 	 */
24116 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24117 
24118 	/*
24119 	 * Now carve off the first frag.  Note that this will include the
24120 	 * original IP header.
24121 	 */
24122 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24123 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24124 		freeb(hdr_mp);
24125 		freemsg(mp_orig);
24126 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24127 		    "ip_wput_frag_end:(%S)",
24128 		    "couldn't carve first");
24129 		return;
24130 	}
24131 
24132 	/*
24133 	 * Multirouting case. Each fragment is replicated
24134 	 * via all non-condemned RTF_MULTIRT routes
24135 	 * currently resolved.
24136 	 * We ensure that first_ire is the first RTF_MULTIRT
24137 	 * ire in the bucket.
24138 	 */
24139 	if (ire->ire_flags & RTF_MULTIRT) {
24140 		irb = ire->ire_bucket;
24141 		ASSERT(irb != NULL);
24142 
24143 		multirt_send = B_TRUE;
24144 
24145 		/* Make sure we do not omit any multiroute ire. */
24146 		IRB_REFHOLD(irb);
24147 		for (first_ire = irb->irb_ire;
24148 		    first_ire != NULL;
24149 		    first_ire = first_ire->ire_next) {
24150 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24151 			    (first_ire->ire_addr == ire->ire_addr) &&
24152 			    !(first_ire->ire_marks &
24153 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
24154 				break;
24155 		}
24156 
24157 		if (first_ire != NULL) {
24158 			if (first_ire != ire) {
24159 				IRE_REFHOLD(first_ire);
24160 				/*
24161 				 * Do not release the ire passed in
24162 				 * as the argument.
24163 				 */
24164 				ire = first_ire;
24165 			} else {
24166 				first_ire = NULL;
24167 			}
24168 		}
24169 		IRB_REFRELE(irb);
24170 
24171 		/*
24172 		 * Save the first ire; we will need to restore it
24173 		 * for the trailing frags.
24174 		 * We REFHOLD save_ire, as each iterated ire will be
24175 		 * REFRELEd.
24176 		 */
24177 		save_ire = ire;
24178 		IRE_REFHOLD(save_ire);
24179 	}
24180 
24181 	/*
24182 	 * First fragment emission loop.
24183 	 * In most cases, the emission loop below is entered only
24184 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24185 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24186 	 * bucket, and send the fragment through all crossed
24187 	 * RTF_MULTIRT routes.
24188 	 */
24189 	do {
24190 		if (ire->ire_flags & RTF_MULTIRT) {
24191 			/*
24192 			 * We are in a multiple send case, need to get
24193 			 * the next ire and make a copy of the packet.
24194 			 * ire1 holds here the next ire to process in the
24195 			 * bucket. If multirouting is expected,
24196 			 * any non-RTF_MULTIRT ire that has the
24197 			 * right destination address is ignored.
24198 			 *
24199 			 * We have to take into account the MTU of
24200 			 * each walked ire. max_frag is set by the
24201 			 * the caller and generally refers to
24202 			 * the primary ire entry. Here we ensure that
24203 			 * no route with a lower MTU will be used, as
24204 			 * fragments are carved once for all ires,
24205 			 * then replicated.
24206 			 */
24207 			ASSERT(irb != NULL);
24208 			IRB_REFHOLD(irb);
24209 			for (ire1 = ire->ire_next;
24210 			    ire1 != NULL;
24211 			    ire1 = ire1->ire_next) {
24212 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24213 					continue;
24214 				if (ire1->ire_addr != ire->ire_addr)
24215 					continue;
24216 				if (ire1->ire_marks &
24217 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
24218 					continue;
24219 				/*
24220 				 * Ensure we do not exceed the MTU
24221 				 * of the next route.
24222 				 */
24223 				if (ire1->ire_max_frag < max_frag) {
24224 					ip_multirt_bad_mtu(ire1, max_frag);
24225 					continue;
24226 				}
24227 
24228 				/* Got one. */
24229 				IRE_REFHOLD(ire1);
24230 				break;
24231 			}
24232 			IRB_REFRELE(irb);
24233 
24234 			if (ire1 != NULL) {
24235 				next_mp = copyb(mp);
24236 				if ((next_mp == NULL) ||
24237 				    ((mp->b_cont != NULL) &&
24238 				    ((next_mp->b_cont =
24239 				    dupmsg(mp->b_cont)) == NULL))) {
24240 					freemsg(next_mp);
24241 					next_mp = NULL;
24242 					ire_refrele(ire1);
24243 					ire1 = NULL;
24244 				}
24245 			}
24246 
24247 			/* Last multiroute ire; don't loop anymore. */
24248 			if (ire1 == NULL) {
24249 				multirt_send = B_FALSE;
24250 			}
24251 		}
24252 
24253 		ll_hdr_len = 0;
24254 		LOCK_IRE_FP_MP(ire);
24255 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24256 		if (ll_hdr_mp != NULL) {
24257 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24258 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24259 		} else {
24260 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24261 		}
24262 
24263 		/* If there is a transmit header, get a copy for this frag. */
24264 		/*
24265 		 * TODO: should check db_ref before calling ip_carve_mp since
24266 		 * it might give us a dup.
24267 		 */
24268 		if (!ll_hdr_mp) {
24269 			/* No xmit header. */
24270 			xmit_mp = mp;
24271 
24272 		/* We have a link-layer header that can fit in our mblk. */
24273 		} else if (mp->b_datap->db_ref == 1 &&
24274 		    ll_hdr_len != 0 &&
24275 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24276 			/* M_DATA fastpath */
24277 			mp->b_rptr -= ll_hdr_len;
24278 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24279 			xmit_mp = mp;
24280 
24281 		/* Corner case if copyb has failed */
24282 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24283 			UNLOCK_IRE_FP_MP(ire);
24284 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24285 			freeb(hdr_mp);
24286 			freemsg(mp);
24287 			freemsg(mp_orig);
24288 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24289 			    "ip_wput_frag_end:(%S)",
24290 			    "discard");
24291 
24292 			if (multirt_send) {
24293 				ASSERT(ire1);
24294 				ASSERT(next_mp);
24295 
24296 				freemsg(next_mp);
24297 				ire_refrele(ire1);
24298 			}
24299 			if (save_ire != NULL)
24300 				IRE_REFRELE(save_ire);
24301 
24302 			if (first_ire != NULL)
24303 				ire_refrele(first_ire);
24304 			return;
24305 
24306 		/*
24307 		 * Case of res_mp OR the fastpath mp can't fit
24308 		 * in the mblk
24309 		 */
24310 		} else {
24311 			xmit_mp->b_cont = mp;
24312 			if (DB_CRED(mp) != NULL)
24313 				mblk_setcred(xmit_mp, DB_CRED(mp));
24314 			/*
24315 			 * Get priority marking, if any.
24316 			 * We propagate the CoS marking from the
24317 			 * original packet that went to QoS processing
24318 			 * in ip_wput_ire to the newly carved mp.
24319 			 */
24320 			if (DB_TYPE(xmit_mp) == M_DATA)
24321 				xmit_mp->b_band = mp->b_band;
24322 		}
24323 		UNLOCK_IRE_FP_MP(ire);
24324 
24325 		q = ire->ire_stq;
24326 		out_ill = (ill_t *)q->q_ptr;
24327 
24328 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24329 
24330 		DTRACE_PROBE4(ip4__physical__out__start,
24331 		    ill_t *, NULL, ill_t *, out_ill,
24332 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24333 
24334 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24335 		    ipst->ips_ipv4firewall_physical_out,
24336 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24337 
24338 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24339 
24340 		if (xmit_mp != NULL) {
24341 			DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *, NULL,
24342 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
24343 			    ipha_t *, ipha, ip6_t *, NULL, int, 0);
24344 
24345 			ILL_SEND_TX(out_ill, ire, connp, xmit_mp, 0);
24346 
24347 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24348 			UPDATE_MIB(out_ill->ill_ip_mib,
24349 			    ipIfStatsHCOutOctets, i1);
24350 
24351 			if (pkt_type != OB_PKT) {
24352 				/*
24353 				 * Update the packet count and MIB stats
24354 				 * of trailing RTF_MULTIRT ires.
24355 				 */
24356 				UPDATE_OB_PKT_COUNT(ire);
24357 				BUMP_MIB(out_ill->ill_ip_mib,
24358 				    ipIfStatsOutFragReqds);
24359 			}
24360 		}
24361 
24362 		if (multirt_send) {
24363 			/*
24364 			 * We are in a multiple send case; look for
24365 			 * the next ire and re-enter the loop.
24366 			 */
24367 			ASSERT(ire1);
24368 			ASSERT(next_mp);
24369 			/* REFRELE the current ire before looping */
24370 			ire_refrele(ire);
24371 			ire = ire1;
24372 			ire1 = NULL;
24373 			mp = next_mp;
24374 			next_mp = NULL;
24375 		}
24376 	} while (multirt_send);
24377 
24378 	ASSERT(ire1 == NULL);
24379 
24380 	/* Restore the original ire; we need it for the trailing frags */
24381 	if (save_ire != NULL) {
24382 		/* REFRELE the last iterated ire */
24383 		ire_refrele(ire);
24384 		/* save_ire has been REFHOLDed */
24385 		ire = save_ire;
24386 		save_ire = NULL;
24387 		q = ire->ire_stq;
24388 	}
24389 
24390 	if (pkt_type == OB_PKT) {
24391 		UPDATE_OB_PKT_COUNT(ire);
24392 	} else {
24393 		out_ill = (ill_t *)q->q_ptr;
24394 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24395 		UPDATE_IB_PKT_COUNT(ire);
24396 	}
24397 
24398 	/* Advance the offset to the second frag starting point. */
24399 	offset += len;
24400 	/*
24401 	 * Update hdr_len from the copied header - there might be less options
24402 	 * in the later fragments.
24403 	 */
24404 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24405 	/* Loop until done. */
24406 	for (;;) {
24407 		uint16_t	offset_and_flags;
24408 		uint16_t	ip_len;
24409 
24410 		if (ip_data_end - offset > len) {
24411 			/*
24412 			 * Carve off the appropriate amount from the original
24413 			 * datagram.
24414 			 */
24415 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24416 				mp = NULL;
24417 				break;
24418 			}
24419 			/*
24420 			 * More frags after this one.  Get another copy
24421 			 * of the header.
24422 			 */
24423 			if (carve_mp->b_datap->db_ref == 1 &&
24424 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24425 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24426 				/* Inline IP header */
24427 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24428 				    hdr_mp->b_rptr;
24429 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24430 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24431 				mp = carve_mp;
24432 			} else {
24433 				if (!(mp = copyb(hdr_mp))) {
24434 					freemsg(carve_mp);
24435 					break;
24436 				}
24437 				/* Get priority marking, if any. */
24438 				mp->b_band = carve_mp->b_band;
24439 				mp->b_cont = carve_mp;
24440 			}
24441 			ipha = (ipha_t *)mp->b_rptr;
24442 			offset_and_flags = IPH_MF;
24443 		} else {
24444 			/*
24445 			 * Last frag.  Consume the header. Set len to
24446 			 * the length of this last piece.
24447 			 */
24448 			len = ip_data_end - offset;
24449 
24450 			/*
24451 			 * Carve off the appropriate amount from the original
24452 			 * datagram.
24453 			 */
24454 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24455 				mp = NULL;
24456 				break;
24457 			}
24458 			if (carve_mp->b_datap->db_ref == 1 &&
24459 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24460 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24461 				/* Inline IP header */
24462 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24463 				    hdr_mp->b_rptr;
24464 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24465 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24466 				mp = carve_mp;
24467 				freeb(hdr_mp);
24468 				hdr_mp = mp;
24469 			} else {
24470 				mp = hdr_mp;
24471 				/* Get priority marking, if any. */
24472 				mp->b_band = carve_mp->b_band;
24473 				mp->b_cont = carve_mp;
24474 			}
24475 			ipha = (ipha_t *)mp->b_rptr;
24476 			/* A frag of a frag might have IPH_MF non-zero */
24477 			offset_and_flags =
24478 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24479 			    IPH_MF;
24480 		}
24481 		offset_and_flags |= (uint16_t)(offset >> 3);
24482 		offset_and_flags |= (uint16_t)frag_flag;
24483 		/* Store the offset and flags in the IP header. */
24484 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24485 
24486 		/* Store the length in the IP header. */
24487 		ip_len = (uint16_t)(len + hdr_len);
24488 		ipha->ipha_length = htons(ip_len);
24489 
24490 		/*
24491 		 * Set the IP header checksum.	Note that mp is just
24492 		 * the header, so this is easy to pass to ip_csum.
24493 		 */
24494 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24495 
24496 		/* Attach a transmit header, if any, and ship it. */
24497 		if (pkt_type == OB_PKT) {
24498 			UPDATE_OB_PKT_COUNT(ire);
24499 		} else {
24500 			out_ill = (ill_t *)q->q_ptr;
24501 			BUMP_MIB(out_ill->ill_ip_mib,
24502 			    ipIfStatsHCOutForwDatagrams);
24503 			UPDATE_IB_PKT_COUNT(ire);
24504 		}
24505 
24506 		if (ire->ire_flags & RTF_MULTIRT) {
24507 			irb = ire->ire_bucket;
24508 			ASSERT(irb != NULL);
24509 
24510 			multirt_send = B_TRUE;
24511 
24512 			/*
24513 			 * Save the original ire; we will need to restore it
24514 			 * for the tailing frags.
24515 			 */
24516 			save_ire = ire;
24517 			IRE_REFHOLD(save_ire);
24518 		}
24519 		/*
24520 		 * Emission loop for this fragment, similar
24521 		 * to what is done for the first fragment.
24522 		 */
24523 		do {
24524 			if (multirt_send) {
24525 				/*
24526 				 * We are in a multiple send case, need to get
24527 				 * the next ire and make a copy of the packet.
24528 				 */
24529 				ASSERT(irb != NULL);
24530 				IRB_REFHOLD(irb);
24531 				for (ire1 = ire->ire_next;
24532 				    ire1 != NULL;
24533 				    ire1 = ire1->ire_next) {
24534 					if (!(ire1->ire_flags & RTF_MULTIRT))
24535 						continue;
24536 					if (ire1->ire_addr != ire->ire_addr)
24537 						continue;
24538 					if (ire1->ire_marks &
24539 					    (IRE_MARK_CONDEMNED |
24540 					    IRE_MARK_TESTHIDDEN))
24541 						continue;
24542 					/*
24543 					 * Ensure we do not exceed the MTU
24544 					 * of the next route.
24545 					 */
24546 					if (ire1->ire_max_frag < max_frag) {
24547 						ip_multirt_bad_mtu(ire1,
24548 						    max_frag);
24549 						continue;
24550 					}
24551 
24552 					/* Got one. */
24553 					IRE_REFHOLD(ire1);
24554 					break;
24555 				}
24556 				IRB_REFRELE(irb);
24557 
24558 				if (ire1 != NULL) {
24559 					next_mp = copyb(mp);
24560 					if ((next_mp == NULL) ||
24561 					    ((mp->b_cont != NULL) &&
24562 					    ((next_mp->b_cont =
24563 					    dupmsg(mp->b_cont)) == NULL))) {
24564 						freemsg(next_mp);
24565 						next_mp = NULL;
24566 						ire_refrele(ire1);
24567 						ire1 = NULL;
24568 					}
24569 				}
24570 
24571 				/* Last multiroute ire; don't loop anymore. */
24572 				if (ire1 == NULL) {
24573 					multirt_send = B_FALSE;
24574 				}
24575 			}
24576 
24577 			/* Update transmit header */
24578 			ll_hdr_len = 0;
24579 			LOCK_IRE_FP_MP(ire);
24580 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24581 			if (ll_hdr_mp != NULL) {
24582 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24583 				ll_hdr_len = MBLKL(ll_hdr_mp);
24584 			} else {
24585 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24586 			}
24587 
24588 			if (!ll_hdr_mp) {
24589 				xmit_mp = mp;
24590 
24591 			/*
24592 			 * We have link-layer header that can fit in
24593 			 * our mblk.
24594 			 */
24595 			} else if (mp->b_datap->db_ref == 1 &&
24596 			    ll_hdr_len != 0 &&
24597 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24598 				/* M_DATA fastpath */
24599 				mp->b_rptr -= ll_hdr_len;
24600 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24601 				    ll_hdr_len);
24602 				xmit_mp = mp;
24603 
24604 			/*
24605 			 * Case of res_mp OR the fastpath mp can't fit
24606 			 * in the mblk
24607 			 */
24608 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24609 				xmit_mp->b_cont = mp;
24610 				if (DB_CRED(mp) != NULL)
24611 					mblk_setcred(xmit_mp, DB_CRED(mp));
24612 				/* Get priority marking, if any. */
24613 				if (DB_TYPE(xmit_mp) == M_DATA)
24614 					xmit_mp->b_band = mp->b_band;
24615 
24616 			/* Corner case if copyb failed */
24617 			} else {
24618 				/*
24619 				 * Exit both the replication and
24620 				 * fragmentation loops.
24621 				 */
24622 				UNLOCK_IRE_FP_MP(ire);
24623 				goto drop_pkt;
24624 			}
24625 			UNLOCK_IRE_FP_MP(ire);
24626 
24627 			mp1 = mp;
24628 			out_ill = (ill_t *)q->q_ptr;
24629 
24630 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24631 
24632 			DTRACE_PROBE4(ip4__physical__out__start,
24633 			    ill_t *, NULL, ill_t *, out_ill,
24634 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24635 
24636 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24637 			    ipst->ips_ipv4firewall_physical_out,
24638 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24639 
24640 			DTRACE_PROBE1(ip4__physical__out__end,
24641 			    mblk_t *, xmit_mp);
24642 
24643 			if (mp != mp1 && hdr_mp == mp1)
24644 				hdr_mp = mp;
24645 			if (mp != mp1 && mp_orig == mp1)
24646 				mp_orig = mp;
24647 
24648 			if (xmit_mp != NULL) {
24649 				DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *,
24650 				    NULL, void_ip_t *, ipha,
24651 				    __dtrace_ipsr_ill_t *, out_ill, ipha_t *,
24652 				    ipha, ip6_t *, NULL, int, 0);
24653 
24654 				ILL_SEND_TX(out_ill, ire, connp, xmit_mp, 0);
24655 
24656 				BUMP_MIB(out_ill->ill_ip_mib,
24657 				    ipIfStatsHCOutTransmits);
24658 				UPDATE_MIB(out_ill->ill_ip_mib,
24659 				    ipIfStatsHCOutOctets, ip_len);
24660 
24661 				if (pkt_type != OB_PKT) {
24662 					/*
24663 					 * Update the packet count of trailing
24664 					 * RTF_MULTIRT ires.
24665 					 */
24666 					UPDATE_OB_PKT_COUNT(ire);
24667 				}
24668 			}
24669 
24670 			/* All done if we just consumed the hdr_mp. */
24671 			if (mp == hdr_mp) {
24672 				last_frag = B_TRUE;
24673 				BUMP_MIB(out_ill->ill_ip_mib,
24674 				    ipIfStatsOutFragOKs);
24675 			}
24676 
24677 			if (multirt_send) {
24678 				/*
24679 				 * We are in a multiple send case; look for
24680 				 * the next ire and re-enter the loop.
24681 				 */
24682 				ASSERT(ire1);
24683 				ASSERT(next_mp);
24684 				/* REFRELE the current ire before looping */
24685 				ire_refrele(ire);
24686 				ire = ire1;
24687 				ire1 = NULL;
24688 				q = ire->ire_stq;
24689 				mp = next_mp;
24690 				next_mp = NULL;
24691 			}
24692 		} while (multirt_send);
24693 		/*
24694 		 * Restore the original ire; we need it for the
24695 		 * trailing frags
24696 		 */
24697 		if (save_ire != NULL) {
24698 			ASSERT(ire1 == NULL);
24699 			/* REFRELE the last iterated ire */
24700 			ire_refrele(ire);
24701 			/* save_ire has been REFHOLDed */
24702 			ire = save_ire;
24703 			q = ire->ire_stq;
24704 			save_ire = NULL;
24705 		}
24706 
24707 		if (last_frag) {
24708 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24709 			    "ip_wput_frag_end:(%S)",
24710 			    "consumed hdr_mp");
24711 
24712 			if (first_ire != NULL)
24713 				ire_refrele(first_ire);
24714 			return;
24715 		}
24716 		/* Otherwise, advance and loop. */
24717 		offset += len;
24718 	}
24719 
24720 drop_pkt:
24721 	/* Clean up following allocation failure. */
24722 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24723 	freemsg(mp);
24724 	if (mp != hdr_mp)
24725 		freeb(hdr_mp);
24726 	if (mp != mp_orig)
24727 		freemsg(mp_orig);
24728 
24729 	if (save_ire != NULL)
24730 		IRE_REFRELE(save_ire);
24731 	if (first_ire != NULL)
24732 		ire_refrele(first_ire);
24733 
24734 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24735 	    "ip_wput_frag_end:(%S)",
24736 	    "end--alloc failure");
24737 }
24738 
24739 /*
24740  * Copy the header plus those options which have the copy bit set
24741  */
24742 static mblk_t *
24743 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
24744 {
24745 	mblk_t	*mp;
24746 	uchar_t	*up;
24747 
24748 	/*
24749 	 * Quick check if we need to look for options without the copy bit
24750 	 * set
24751 	 */
24752 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
24753 	if (!mp)
24754 		return (mp);
24755 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24756 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24757 		bcopy(rptr, mp->b_rptr, hdr_len);
24758 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24759 		return (mp);
24760 	}
24761 	up  = mp->b_rptr;
24762 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24763 	up += IP_SIMPLE_HDR_LENGTH;
24764 	rptr += IP_SIMPLE_HDR_LENGTH;
24765 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24766 	while (hdr_len > 0) {
24767 		uint32_t optval;
24768 		uint32_t optlen;
24769 
24770 		optval = *rptr;
24771 		if (optval == IPOPT_EOL)
24772 			break;
24773 		if (optval == IPOPT_NOP)
24774 			optlen = 1;
24775 		else
24776 			optlen = rptr[1];
24777 		if (optval & IPOPT_COPY) {
24778 			bcopy(rptr, up, optlen);
24779 			up += optlen;
24780 		}
24781 		rptr += optlen;
24782 		hdr_len -= optlen;
24783 	}
24784 	/*
24785 	 * Make sure that we drop an even number of words by filling
24786 	 * with EOL to the next word boundary.
24787 	 */
24788 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24789 	    hdr_len & 0x3; hdr_len++)
24790 		*up++ = IPOPT_EOL;
24791 	mp->b_wptr = up;
24792 	/* Update header length */
24793 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24794 	return (mp);
24795 }
24796 
24797 /*
24798  * Delivery to local recipients including fanout to multiple recipients.
24799  * Does not do checksumming of UDP/TCP.
24800  * Note: q should be the read side queue for either the ill or conn.
24801  * Note: rq should be the read side q for the lower (ill) stream.
24802  * We don't send packets to IPPF processing, thus the last argument
24803  * to all the fanout calls are B_FALSE.
24804  */
24805 void
24806 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24807     int fanout_flags, zoneid_t zoneid)
24808 {
24809 	uint32_t	protocol;
24810 	mblk_t		*first_mp;
24811 	boolean_t	mctl_present;
24812 	int		ire_type;
24813 #define	rptr	((uchar_t *)ipha)
24814 	ip_stack_t	*ipst = ill->ill_ipst;
24815 
24816 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24817 	    "ip_wput_local_start: q %p", q);
24818 
24819 	if (ire != NULL) {
24820 		ire_type = ire->ire_type;
24821 	} else {
24822 		/*
24823 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24824 		 * packet is not multicast, we can't tell the ire type.
24825 		 */
24826 		ASSERT(CLASSD(ipha->ipha_dst));
24827 		ire_type = IRE_BROADCAST;
24828 	}
24829 
24830 	first_mp = mp;
24831 	if (first_mp->b_datap->db_type == M_CTL) {
24832 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24833 		if (!io->ipsec_out_secure) {
24834 			/*
24835 			 * This ipsec_out_t was allocated in ip_wput
24836 			 * for multicast packets to store the ill_index.
24837 			 * As this is being delivered locally, we don't
24838 			 * need this anymore.
24839 			 */
24840 			mp = first_mp->b_cont;
24841 			freeb(first_mp);
24842 			first_mp = mp;
24843 			mctl_present = B_FALSE;
24844 		} else {
24845 			/*
24846 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24847 			 * security properties for the looped-back packet.
24848 			 */
24849 			mctl_present = B_TRUE;
24850 			mp = first_mp->b_cont;
24851 			ASSERT(mp != NULL);
24852 			ipsec_out_to_in(first_mp);
24853 		}
24854 	} else {
24855 		mctl_present = B_FALSE;
24856 	}
24857 
24858 	DTRACE_PROBE4(ip4__loopback__in__start,
24859 	    ill_t *, ill, ill_t *, NULL,
24860 	    ipha_t *, ipha, mblk_t *, first_mp);
24861 
24862 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
24863 	    ipst->ips_ipv4firewall_loopback_in,
24864 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
24865 
24866 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24867 
24868 	if (first_mp == NULL)
24869 		return;
24870 
24871 	if (ipst->ips_ipobs_enabled) {
24872 		zoneid_t szone, dzone, lookup_zoneid = ALL_ZONES;
24873 		zoneid_t stackzoneid = netstackid_to_zoneid(
24874 		    ipst->ips_netstack->netstack_stackid);
24875 
24876 		dzone = (stackzoneid == GLOBAL_ZONEID) ? zoneid : stackzoneid;
24877 		/*
24878 		 * 127.0.0.1 is special, as we cannot lookup its zoneid by
24879 		 * address.  Restrict the lookup below to the destination zone.
24880 		 */
24881 		if (ipha->ipha_src == ntohl(INADDR_LOOPBACK))
24882 			lookup_zoneid = zoneid;
24883 		szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
24884 		    lookup_zoneid);
24885 		ipobs_hook(mp, IPOBS_HOOK_LOCAL, szone, dzone, ill,
24886 		    IPV4_VERSION, 0, ipst);
24887 	}
24888 
24889 	DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL, void_ip_t *,
24890 	    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *, NULL,
24891 	    int, 1);
24892 
24893 	ipst->ips_loopback_packets++;
24894 
24895 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
24896 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
24897 	if (!IS_SIMPLE_IPH(ipha)) {
24898 		ip_wput_local_options(ipha, ipst);
24899 	}
24900 
24901 	protocol = ipha->ipha_protocol;
24902 	switch (protocol) {
24903 	case IPPROTO_ICMP: {
24904 		ire_t		*ire_zone;
24905 		ilm_t		*ilm;
24906 		mblk_t		*mp1;
24907 		zoneid_t	last_zoneid;
24908 		ilm_walker_t	ilw;
24909 
24910 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
24911 			ASSERT(ire_type == IRE_BROADCAST);
24912 			/*
24913 			 * In the multicast case, applications may have joined
24914 			 * the group from different zones, so we need to deliver
24915 			 * the packet to each of them. Loop through the
24916 			 * multicast memberships structures (ilm) on the receive
24917 			 * ill and send a copy of the packet up each matching
24918 			 * one. However, we don't do this for multicasts sent on
24919 			 * the loopback interface (PHYI_LOOPBACK flag set) as
24920 			 * they must stay in the sender's zone.
24921 			 *
24922 			 * ilm_add_v6() ensures that ilms in the same zone are
24923 			 * contiguous in the ill_ilm list. We use this property
24924 			 * to avoid sending duplicates needed when two
24925 			 * applications in the same zone join the same group on
24926 			 * different logical interfaces: we ignore the ilm if
24927 			 * it's zoneid is the same as the last matching one.
24928 			 * In addition, the sending of the packet for
24929 			 * ire_zoneid is delayed until all of the other ilms
24930 			 * have been exhausted.
24931 			 */
24932 			last_zoneid = -1;
24933 			ilm = ilm_walker_start(&ilw, ill);
24934 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
24935 				if (ipha->ipha_dst != ilm->ilm_addr ||
24936 				    ilm->ilm_zoneid == last_zoneid ||
24937 				    ilm->ilm_zoneid == zoneid ||
24938 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
24939 					continue;
24940 				mp1 = ip_copymsg(first_mp);
24941 				if (mp1 == NULL)
24942 					continue;
24943 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
24944 				    0, 0, mctl_present, B_FALSE, ill,
24945 				    ilm->ilm_zoneid);
24946 				last_zoneid = ilm->ilm_zoneid;
24947 			}
24948 			ilm_walker_finish(&ilw);
24949 			/*
24950 			 * Loopback case: the sending endpoint has
24951 			 * IP_MULTICAST_LOOP disabled, therefore we don't
24952 			 * dispatch the multicast packet to the sending zone.
24953 			 */
24954 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
24955 				freemsg(first_mp);
24956 				return;
24957 			}
24958 		} else if (ire_type == IRE_BROADCAST) {
24959 			/*
24960 			 * In the broadcast case, there may be many zones
24961 			 * which need a copy of the packet delivered to them.
24962 			 * There is one IRE_BROADCAST per broadcast address
24963 			 * and per zone; we walk those using a helper function.
24964 			 * In addition, the sending of the packet for zoneid is
24965 			 * delayed until all of the other ires have been
24966 			 * processed.
24967 			 */
24968 			IRB_REFHOLD(ire->ire_bucket);
24969 			ire_zone = NULL;
24970 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
24971 			    ire)) != NULL) {
24972 				mp1 = ip_copymsg(first_mp);
24973 				if (mp1 == NULL)
24974 					continue;
24975 
24976 				UPDATE_IB_PKT_COUNT(ire_zone);
24977 				ire_zone->ire_last_used_time = lbolt;
24978 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24979 				    mctl_present, B_FALSE, ill,
24980 				    ire_zone->ire_zoneid);
24981 			}
24982 			IRB_REFRELE(ire->ire_bucket);
24983 		}
24984 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
24985 		    0, mctl_present, B_FALSE, ill, zoneid);
24986 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24987 		    "ip_wput_local_end: q %p (%S)",
24988 		    q, "icmp");
24989 		return;
24990 	}
24991 	case IPPROTO_IGMP:
24992 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
24993 			/* Bad packet - discarded by igmp_input */
24994 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24995 			    "ip_wput_local_end: q %p (%S)",
24996 			    q, "igmp_input--bad packet");
24997 			if (mctl_present)
24998 				freeb(first_mp);
24999 			return;
25000 		}
25001 		/*
25002 		 * igmp_input() may have returned the pulled up message.
25003 		 * So first_mp and ipha need to be reinitialized.
25004 		 */
25005 		ipha = (ipha_t *)mp->b_rptr;
25006 		if (mctl_present)
25007 			first_mp->b_cont = mp;
25008 		else
25009 			first_mp = mp;
25010 		/* deliver to local raw users */
25011 		break;
25012 	case IPPROTO_ENCAP:
25013 		/*
25014 		 * This case is covered by either ip_fanout_proto, or by
25015 		 * the above security processing for self-tunneled packets.
25016 		 */
25017 		break;
25018 	case IPPROTO_UDP: {
25019 		uint16_t	*up;
25020 		uint32_t	ports;
25021 
25022 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25023 		    UDP_PORTS_OFFSET);
25024 		/* Force a 'valid' checksum. */
25025 		up[3] = 0;
25026 
25027 		ports = *(uint32_t *)up;
25028 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25029 		    (ire_type == IRE_BROADCAST),
25030 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25031 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25032 		    ill, zoneid);
25033 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25034 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25035 		return;
25036 	}
25037 	case IPPROTO_TCP: {
25038 
25039 		/*
25040 		 * For TCP, discard broadcast packets.
25041 		 */
25042 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25043 			freemsg(first_mp);
25044 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25045 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25046 			return;
25047 		}
25048 
25049 		if (mp->b_datap->db_type == M_DATA) {
25050 			/*
25051 			 * M_DATA mblk, so init mblk (chain) for no struio().
25052 			 */
25053 			mblk_t	*mp1 = mp;
25054 
25055 			do {
25056 				mp1->b_datap->db_struioflag = 0;
25057 			} while ((mp1 = mp1->b_cont) != NULL);
25058 		}
25059 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25060 		    <= mp->b_wptr);
25061 		ip_fanout_tcp(q, first_mp, ill, ipha,
25062 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25063 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25064 		    mctl_present, B_FALSE, zoneid);
25065 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25066 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25067 		return;
25068 	}
25069 	case IPPROTO_SCTP:
25070 	{
25071 		uint32_t	ports;
25072 
25073 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25074 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25075 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25076 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25077 		return;
25078 	}
25079 
25080 	default:
25081 		break;
25082 	}
25083 	/*
25084 	 * Find a client for some other protocol.  We give
25085 	 * copies to multiple clients, if more than one is
25086 	 * bound.
25087 	 */
25088 	ip_fanout_proto(q, first_mp, ill, ipha,
25089 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25090 	    mctl_present, B_FALSE, ill, zoneid);
25091 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25092 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25093 #undef	rptr
25094 }
25095 
25096 /*
25097  * Update any source route, record route, or timestamp options.
25098  * Check that we are at end of strict source route.
25099  * The options have been sanity checked by ip_wput_options().
25100  */
25101 static void
25102 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25103 {
25104 	ipoptp_t	opts;
25105 	uchar_t		*opt;
25106 	uint8_t		optval;
25107 	uint8_t		optlen;
25108 	ipaddr_t	dst;
25109 	uint32_t	ts;
25110 	ire_t		*ire;
25111 	timestruc_t	now;
25112 
25113 	ip2dbg(("ip_wput_local_options\n"));
25114 	for (optval = ipoptp_first(&opts, ipha);
25115 	    optval != IPOPT_EOL;
25116 	    optval = ipoptp_next(&opts)) {
25117 		opt = opts.ipoptp_cur;
25118 		optlen = opts.ipoptp_len;
25119 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25120 		switch (optval) {
25121 			uint32_t off;
25122 		case IPOPT_SSRR:
25123 		case IPOPT_LSRR:
25124 			off = opt[IPOPT_OFFSET];
25125 			off--;
25126 			if (optlen < IP_ADDR_LEN ||
25127 			    off > optlen - IP_ADDR_LEN) {
25128 				/* End of source route */
25129 				break;
25130 			}
25131 			/*
25132 			 * This will only happen if two consecutive entries
25133 			 * in the source route contains our address or if
25134 			 * it is a packet with a loose source route which
25135 			 * reaches us before consuming the whole source route
25136 			 */
25137 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25138 			if (optval == IPOPT_SSRR) {
25139 				return;
25140 			}
25141 			/*
25142 			 * Hack: instead of dropping the packet truncate the
25143 			 * source route to what has been used by filling the
25144 			 * rest with IPOPT_NOP.
25145 			 */
25146 			opt[IPOPT_OLEN] = (uint8_t)off;
25147 			while (off < optlen) {
25148 				opt[off++] = IPOPT_NOP;
25149 			}
25150 			break;
25151 		case IPOPT_RR:
25152 			off = opt[IPOPT_OFFSET];
25153 			off--;
25154 			if (optlen < IP_ADDR_LEN ||
25155 			    off > optlen - IP_ADDR_LEN) {
25156 				/* No more room - ignore */
25157 				ip1dbg((
25158 				    "ip_wput_forward_options: end of RR\n"));
25159 				break;
25160 			}
25161 			dst = htonl(INADDR_LOOPBACK);
25162 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25163 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25164 			break;
25165 		case IPOPT_TS:
25166 			/* Insert timestamp if there is romm */
25167 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25168 			case IPOPT_TS_TSONLY:
25169 				off = IPOPT_TS_TIMELEN;
25170 				break;
25171 			case IPOPT_TS_PRESPEC:
25172 			case IPOPT_TS_PRESPEC_RFC791:
25173 				/* Verify that the address matched */
25174 				off = opt[IPOPT_OFFSET] - 1;
25175 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25176 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25177 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25178 				    ipst);
25179 				if (ire == NULL) {
25180 					/* Not for us */
25181 					break;
25182 				}
25183 				ire_refrele(ire);
25184 				/* FALLTHRU */
25185 			case IPOPT_TS_TSANDADDR:
25186 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25187 				break;
25188 			default:
25189 				/*
25190 				 * ip_*put_options should have already
25191 				 * dropped this packet.
25192 				 */
25193 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25194 				    "unknown IT - bug in ip_wput_options?\n");
25195 				return;	/* Keep "lint" happy */
25196 			}
25197 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25198 				/* Increase overflow counter */
25199 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25200 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25201 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25202 				    (off << 4);
25203 				break;
25204 			}
25205 			off = opt[IPOPT_OFFSET] - 1;
25206 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25207 			case IPOPT_TS_PRESPEC:
25208 			case IPOPT_TS_PRESPEC_RFC791:
25209 			case IPOPT_TS_TSANDADDR:
25210 				dst = htonl(INADDR_LOOPBACK);
25211 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25212 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25213 				/* FALLTHRU */
25214 			case IPOPT_TS_TSONLY:
25215 				off = opt[IPOPT_OFFSET] - 1;
25216 				/* Compute # of milliseconds since midnight */
25217 				gethrestime(&now);
25218 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25219 				    now.tv_nsec / (NANOSEC / MILLISEC);
25220 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25221 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25222 				break;
25223 			}
25224 			break;
25225 		}
25226 	}
25227 }
25228 
25229 /*
25230  * Send out a multicast packet on interface ipif.
25231  * The sender does not have an conn.
25232  * Caller verifies that this isn't a PHYI_LOOPBACK.
25233  */
25234 void
25235 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25236 {
25237 	ipha_t	*ipha;
25238 	ire_t	*ire;
25239 	ipaddr_t	dst;
25240 	mblk_t		*first_mp;
25241 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25242 
25243 	/* igmp_sendpkt always allocates a ipsec_out_t */
25244 	ASSERT(mp->b_datap->db_type == M_CTL);
25245 	ASSERT(!ipif->ipif_isv6);
25246 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25247 
25248 	first_mp = mp;
25249 	mp = first_mp->b_cont;
25250 	ASSERT(mp->b_datap->db_type == M_DATA);
25251 	ipha = (ipha_t *)mp->b_rptr;
25252 
25253 	/*
25254 	 * Find an IRE which matches the destination and the outgoing
25255 	 * queue (i.e. the outgoing interface.)
25256 	 */
25257 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25258 		dst = ipif->ipif_pp_dst_addr;
25259 	else
25260 		dst = ipha->ipha_dst;
25261 	/*
25262 	 * The source address has already been initialized by the
25263 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25264 	 * be sufficient rather than MATCH_IRE_IPIF.
25265 	 *
25266 	 * This function is used for sending IGMP packets.  For IPMP,
25267 	 * we sidestep IGMP snooping issues by sending all multicast
25268 	 * traffic on a single interface in the IPMP group.
25269 	 */
25270 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25271 	    MATCH_IRE_ILL, ipst);
25272 	if (!ire) {
25273 		/*
25274 		 * Mark this packet to make it be delivered to
25275 		 * ip_wput_ire after the new ire has been
25276 		 * created.
25277 		 */
25278 		mp->b_prev = NULL;
25279 		mp->b_next = NULL;
25280 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25281 		    zoneid, &zero_info);
25282 		return;
25283 	}
25284 
25285 	/*
25286 	 * Honor the RTF_SETSRC flag; this is the only case
25287 	 * where we force this addr whatever the current src addr is,
25288 	 * because this address is set by igmp_sendpkt(), and
25289 	 * cannot be specified by any user.
25290 	 */
25291 	if (ire->ire_flags & RTF_SETSRC) {
25292 		ipha->ipha_src = ire->ire_src_addr;
25293 	}
25294 
25295 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25296 }
25297 
25298 /*
25299  * NOTE : This function does not ire_refrele the ire argument passed in.
25300  *
25301  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25302  * failure. The nce_fp_mp can vanish any time in the case of
25303  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25304  * the ire_lock to access the nce_fp_mp in this case.
25305  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25306  * prepending a fastpath message IPQoS processing must precede it, we also set
25307  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25308  * (IPQoS might have set the b_band for CoS marking).
25309  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25310  * must follow it so that IPQoS can mark the dl_priority field for CoS
25311  * marking, if needed.
25312  */
25313 static mblk_t *
25314 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc,
25315     uint32_t ill_index, ipha_t **iphap)
25316 {
25317 	uint_t	hlen;
25318 	ipha_t *ipha;
25319 	mblk_t *mp1;
25320 	boolean_t qos_done = B_FALSE;
25321 	uchar_t	*ll_hdr;
25322 	ip_stack_t	*ipst = ire->ire_ipst;
25323 
25324 #define	rptr	((uchar_t *)ipha)
25325 
25326 	ipha = (ipha_t *)mp->b_rptr;
25327 	hlen = 0;
25328 	LOCK_IRE_FP_MP(ire);
25329 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25330 		ASSERT(DB_TYPE(mp1) == M_DATA);
25331 		/* Initiate IPPF processing */
25332 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25333 			UNLOCK_IRE_FP_MP(ire);
25334 			ip_process(proc, &mp, ill_index);
25335 			if (mp == NULL)
25336 				return (NULL);
25337 
25338 			ipha = (ipha_t *)mp->b_rptr;
25339 			LOCK_IRE_FP_MP(ire);
25340 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25341 				qos_done = B_TRUE;
25342 				goto no_fp_mp;
25343 			}
25344 			ASSERT(DB_TYPE(mp1) == M_DATA);
25345 		}
25346 		hlen = MBLKL(mp1);
25347 		/*
25348 		 * Check if we have enough room to prepend fastpath
25349 		 * header
25350 		 */
25351 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25352 			ll_hdr = rptr - hlen;
25353 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25354 			/*
25355 			 * Set the b_rptr to the start of the link layer
25356 			 * header
25357 			 */
25358 			mp->b_rptr = ll_hdr;
25359 			mp1 = mp;
25360 		} else {
25361 			mp1 = copyb(mp1);
25362 			if (mp1 == NULL)
25363 				goto unlock_err;
25364 			mp1->b_band = mp->b_band;
25365 			mp1->b_cont = mp;
25366 			/*
25367 			 * certain system generated traffic may not
25368 			 * have cred/label in ip header block. This
25369 			 * is true even for a labeled system. But for
25370 			 * labeled traffic, inherit the label in the
25371 			 * new header.
25372 			 */
25373 			if (DB_CRED(mp) != NULL)
25374 				mblk_setcred(mp1, DB_CRED(mp));
25375 			/*
25376 			 * XXX disable ICK_VALID and compute checksum
25377 			 * here; can happen if nce_fp_mp changes and
25378 			 * it can't be copied now due to insufficient
25379 			 * space. (unlikely, fp mp can change, but it
25380 			 * does not increase in length)
25381 			 */
25382 		}
25383 		UNLOCK_IRE_FP_MP(ire);
25384 	} else {
25385 no_fp_mp:
25386 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25387 		if (mp1 == NULL) {
25388 unlock_err:
25389 			UNLOCK_IRE_FP_MP(ire);
25390 			freemsg(mp);
25391 			return (NULL);
25392 		}
25393 		UNLOCK_IRE_FP_MP(ire);
25394 		mp1->b_cont = mp;
25395 		/*
25396 		 * certain system generated traffic may not
25397 		 * have cred/label in ip header block. This
25398 		 * is true even for a labeled system. But for
25399 		 * labeled traffic, inherit the label in the
25400 		 * new header.
25401 		 */
25402 		if (DB_CRED(mp) != NULL)
25403 			mblk_setcred(mp1, DB_CRED(mp));
25404 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25405 			ip_process(proc, &mp1, ill_index);
25406 			if (mp1 == NULL)
25407 				return (NULL);
25408 
25409 			if (mp1->b_cont == NULL)
25410 				ipha = NULL;
25411 			else
25412 				ipha = (ipha_t *)mp1->b_cont->b_rptr;
25413 		}
25414 	}
25415 
25416 	*iphap = ipha;
25417 	return (mp1);
25418 #undef rptr
25419 }
25420 
25421 /*
25422  * Finish the outbound IPsec processing for an IPv6 packet. This function
25423  * is called from ipsec_out_process() if the IPsec packet was processed
25424  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25425  * asynchronously.
25426  */
25427 void
25428 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25429     ire_t *ire_arg)
25430 {
25431 	in6_addr_t *v6dstp;
25432 	ire_t *ire;
25433 	mblk_t *mp;
25434 	ip6_t *ip6h1;
25435 	uint_t	ill_index;
25436 	ipsec_out_t *io;
25437 	boolean_t hwaccel;
25438 	uint32_t flags = IP6_NO_IPPOLICY;
25439 	int match_flags;
25440 	zoneid_t zoneid;
25441 	boolean_t ill_need_rele = B_FALSE;
25442 	boolean_t ire_need_rele = B_FALSE;
25443 	ip_stack_t	*ipst;
25444 
25445 	mp = ipsec_mp->b_cont;
25446 	ip6h1 = (ip6_t *)mp->b_rptr;
25447 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25448 	ASSERT(io->ipsec_out_ns != NULL);
25449 	ipst = io->ipsec_out_ns->netstack_ip;
25450 	ill_index = io->ipsec_out_ill_index;
25451 	if (io->ipsec_out_reachable) {
25452 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25453 	}
25454 	hwaccel = io->ipsec_out_accelerated;
25455 	zoneid = io->ipsec_out_zoneid;
25456 	ASSERT(zoneid != ALL_ZONES);
25457 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25458 	/* Multicast addresses should have non-zero ill_index. */
25459 	v6dstp = &ip6h->ip6_dst;
25460 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25461 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25462 
25463 	if (ill == NULL && ill_index != 0) {
25464 		ill = ip_grab_ill(ipsec_mp, ill_index, B_TRUE, ipst);
25465 		/* Failure case frees things for us. */
25466 		if (ill == NULL)
25467 			return;
25468 
25469 		ill_need_rele = B_TRUE;
25470 	}
25471 	ASSERT(mp != NULL);
25472 
25473 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25474 		boolean_t unspec_src;
25475 		ipif_t	*ipif;
25476 
25477 		/*
25478 		 * Use the ill_index to get the right ill.
25479 		 */
25480 		unspec_src = io->ipsec_out_unspec_src;
25481 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25482 		if (ipif == NULL) {
25483 			if (ill_need_rele)
25484 				ill_refrele(ill);
25485 			freemsg(ipsec_mp);
25486 			return;
25487 		}
25488 
25489 		if (ire_arg != NULL) {
25490 			ire = ire_arg;
25491 		} else {
25492 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25493 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25494 			ire_need_rele = B_TRUE;
25495 		}
25496 		if (ire != NULL) {
25497 			ipif_refrele(ipif);
25498 			/*
25499 			 * XXX Do the multicast forwarding now, as the IPsec
25500 			 * processing has been done.
25501 			 */
25502 			goto send;
25503 		}
25504 
25505 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25506 		mp->b_prev = NULL;
25507 		mp->b_next = NULL;
25508 
25509 		/*
25510 		 * If the IPsec packet was processed asynchronously,
25511 		 * drop it now.
25512 		 */
25513 		if (q == NULL) {
25514 			if (ill_need_rele)
25515 				ill_refrele(ill);
25516 			freemsg(ipsec_mp);
25517 			return;
25518 		}
25519 
25520 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, v6dstp, &ip6h->ip6_src,
25521 		    unspec_src, zoneid);
25522 		ipif_refrele(ipif);
25523 	} else {
25524 		if (ire_arg != NULL) {
25525 			ire = ire_arg;
25526 		} else {
25527 			ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL, ipst);
25528 			ire_need_rele = B_TRUE;
25529 		}
25530 		if (ire != NULL)
25531 			goto send;
25532 		/*
25533 		 * ire disappeared underneath.
25534 		 *
25535 		 * What we need to do here is the ip_newroute
25536 		 * logic to get the ire without doing the IPsec
25537 		 * processing. Follow the same old path. But this
25538 		 * time, ip_wput or ire_add_then_send will call us
25539 		 * directly as all the IPsec operations are done.
25540 		 */
25541 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25542 		mp->b_prev = NULL;
25543 		mp->b_next = NULL;
25544 
25545 		/*
25546 		 * If the IPsec packet was processed asynchronously,
25547 		 * drop it now.
25548 		 */
25549 		if (q == NULL) {
25550 			if (ill_need_rele)
25551 				ill_refrele(ill);
25552 			freemsg(ipsec_mp);
25553 			return;
25554 		}
25555 
25556 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25557 		    zoneid, ipst);
25558 	}
25559 	if (ill != NULL && ill_need_rele)
25560 		ill_refrele(ill);
25561 	return;
25562 send:
25563 	if (ill != NULL && ill_need_rele)
25564 		ill_refrele(ill);
25565 
25566 	/* Local delivery */
25567 	if (ire->ire_stq == NULL) {
25568 		ill_t	*out_ill;
25569 		ASSERT(q != NULL);
25570 
25571 		/* PFHooks: LOOPBACK_OUT */
25572 		out_ill = ire_to_ill(ire);
25573 
25574 		/*
25575 		 * DTrace this as ip:::send.  A blocked packet will fire the
25576 		 * send probe, but not the receive probe.
25577 		 */
25578 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25579 		    void_ip_t *, ip6h, __dtrace_ipsr_ill_t *, out_ill,
25580 		    ipha_t *, NULL, ip6_t *, ip6h, int, 1);
25581 
25582 		DTRACE_PROBE4(ip6__loopback__out__start,
25583 		    ill_t *, NULL, ill_t *, out_ill,
25584 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25585 
25586 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25587 		    ipst->ips_ipv6firewall_loopback_out,
25588 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25589 
25590 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25591 
25592 		if (ipsec_mp != NULL) {
25593 			ip_wput_local_v6(RD(q), out_ill,
25594 			    ip6h, ipsec_mp, ire, 0, zoneid);
25595 		}
25596 		if (ire_need_rele)
25597 			ire_refrele(ire);
25598 		return;
25599 	}
25600 	/*
25601 	 * Everything is done. Send it out on the wire.
25602 	 * We force the insertion of a fragment header using the
25603 	 * IPH_FRAG_HDR flag in two cases:
25604 	 * - after reception of an ICMPv6 "packet too big" message
25605 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25606 	 * - for multirouted IPv6 packets, so that the receiver can
25607 	 *   discard duplicates according to their fragment identifier
25608 	 */
25609 	/* XXX fix flow control problems. */
25610 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25611 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25612 		if (hwaccel) {
25613 			/*
25614 			 * hardware acceleration does not handle these
25615 			 * "slow path" cases.
25616 			 */
25617 			/* IPsec KSTATS: should bump bean counter here. */
25618 			if (ire_need_rele)
25619 				ire_refrele(ire);
25620 			freemsg(ipsec_mp);
25621 			return;
25622 		}
25623 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25624 		    (mp->b_cont ? msgdsize(mp) :
25625 		    mp->b_wptr - (uchar_t *)ip6h)) {
25626 			/* IPsec KSTATS: should bump bean counter here. */
25627 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25628 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25629 			    msgdsize(mp)));
25630 			if (ire_need_rele)
25631 				ire_refrele(ire);
25632 			freemsg(ipsec_mp);
25633 			return;
25634 		}
25635 		ASSERT(mp->b_prev == NULL);
25636 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25637 		    ntohs(ip6h->ip6_plen) +
25638 		    IPV6_HDR_LEN, ire->ire_max_frag));
25639 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25640 		    ire->ire_max_frag);
25641 	} else {
25642 		UPDATE_OB_PKT_COUNT(ire);
25643 		ire->ire_last_used_time = lbolt;
25644 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25645 	}
25646 	if (ire_need_rele)
25647 		ire_refrele(ire);
25648 	freeb(ipsec_mp);
25649 }
25650 
25651 void
25652 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25653 {
25654 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25655 	da_ipsec_t *hada;	/* data attributes */
25656 	ill_t *ill = (ill_t *)q->q_ptr;
25657 
25658 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25659 
25660 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25661 		/* IPsec KSTATS: Bump lose counter here! */
25662 		freemsg(mp);
25663 		return;
25664 	}
25665 
25666 	/*
25667 	 * It's an IPsec packet that must be
25668 	 * accelerated by the Provider, and the
25669 	 * outbound ill is IPsec acceleration capable.
25670 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25671 	 * to the ill.
25672 	 * IPsec KSTATS: should bump packet counter here.
25673 	 */
25674 
25675 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25676 	if (hada_mp == NULL) {
25677 		/* IPsec KSTATS: should bump packet counter here. */
25678 		freemsg(mp);
25679 		return;
25680 	}
25681 
25682 	hada_mp->b_datap->db_type = M_CTL;
25683 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25684 	hada_mp->b_cont = mp;
25685 
25686 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25687 	bzero(hada, sizeof (da_ipsec_t));
25688 	hada->da_type = IPHADA_M_CTL;
25689 
25690 	putnext(q, hada_mp);
25691 }
25692 
25693 /*
25694  * Finish the outbound IPsec processing. This function is called from
25695  * ipsec_out_process() if the IPsec packet was processed
25696  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25697  * asynchronously.
25698  */
25699 void
25700 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25701     ire_t *ire_arg)
25702 {
25703 	uint32_t v_hlen_tos_len;
25704 	ipaddr_t	dst;
25705 	ipif_t	*ipif = NULL;
25706 	ire_t *ire;
25707 	ire_t *ire1 = NULL;
25708 	mblk_t *next_mp = NULL;
25709 	uint32_t max_frag;
25710 	boolean_t multirt_send = B_FALSE;
25711 	mblk_t *mp;
25712 	ipha_t *ipha1;
25713 	uint_t	ill_index;
25714 	ipsec_out_t *io;
25715 	int match_flags;
25716 	irb_t *irb = NULL;
25717 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25718 	zoneid_t zoneid;
25719 	ipxmit_state_t	pktxmit_state;
25720 	ip_stack_t	*ipst;
25721 
25722 #ifdef	_BIG_ENDIAN
25723 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25724 #else
25725 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25726 #endif
25727 
25728 	mp = ipsec_mp->b_cont;
25729 	ipha1 = (ipha_t *)mp->b_rptr;
25730 	ASSERT(mp != NULL);
25731 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25732 	dst = ipha->ipha_dst;
25733 
25734 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25735 	ill_index = io->ipsec_out_ill_index;
25736 	zoneid = io->ipsec_out_zoneid;
25737 	ASSERT(zoneid != ALL_ZONES);
25738 	ipst = io->ipsec_out_ns->netstack_ip;
25739 	ASSERT(io->ipsec_out_ns != NULL);
25740 
25741 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25742 	if (ill == NULL && ill_index != 0) {
25743 		ill = ip_grab_ill(ipsec_mp, ill_index, B_FALSE, ipst);
25744 		/* Failure case frees things for us. */
25745 		if (ill == NULL)
25746 			return;
25747 
25748 		ill_need_rele = B_TRUE;
25749 	}
25750 
25751 	if (CLASSD(dst)) {
25752 		boolean_t conn_dontroute;
25753 		/*
25754 		 * Use the ill_index to get the right ipif.
25755 		 */
25756 		conn_dontroute = io->ipsec_out_dontroute;
25757 		if (ill_index == 0)
25758 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25759 		else
25760 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25761 		if (ipif == NULL) {
25762 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25763 			    " multicast\n"));
25764 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25765 			freemsg(ipsec_mp);
25766 			goto done;
25767 		}
25768 		/*
25769 		 * ipha_src has already been intialized with the
25770 		 * value of the ipif in ip_wput. All we need now is
25771 		 * an ire to send this downstream.
25772 		 */
25773 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25774 		    MBLK_GETLABEL(mp), match_flags, ipst);
25775 		if (ire != NULL) {
25776 			ill_t *ill1;
25777 			/*
25778 			 * Do the multicast forwarding now, as the IPsec
25779 			 * processing has been done.
25780 			 */
25781 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25782 			    (ill1 = ire_to_ill(ire))) {
25783 				if (ip_mforward(ill1, ipha, mp)) {
25784 					freemsg(ipsec_mp);
25785 					ip1dbg(("ip_wput_ipsec_out: mforward "
25786 					    "failed\n"));
25787 					ire_refrele(ire);
25788 					goto done;
25789 				}
25790 			}
25791 			goto send;
25792 		}
25793 
25794 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25795 		mp->b_prev = NULL;
25796 		mp->b_next = NULL;
25797 
25798 		/*
25799 		 * If the IPsec packet was processed asynchronously,
25800 		 * drop it now.
25801 		 */
25802 		if (q == NULL) {
25803 			freemsg(ipsec_mp);
25804 			goto done;
25805 		}
25806 
25807 		/*
25808 		 * We may be using a wrong ipif to create the ire.
25809 		 * But it is okay as the source address is assigned
25810 		 * for the packet already. Next outbound packet would
25811 		 * create the IRE with the right IPIF in ip_wput.
25812 		 *
25813 		 * Also handle RTF_MULTIRT routes.
25814 		 */
25815 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25816 		    zoneid, &zero_info);
25817 	} else {
25818 		if (ire_arg != NULL) {
25819 			ire = ire_arg;
25820 			ire_need_rele = B_FALSE;
25821 		} else {
25822 			ire = ire_cache_lookup(dst, zoneid,
25823 			    MBLK_GETLABEL(mp), ipst);
25824 		}
25825 		if (ire != NULL) {
25826 			goto send;
25827 		}
25828 
25829 		/*
25830 		 * ire disappeared underneath.
25831 		 *
25832 		 * What we need to do here is the ip_newroute
25833 		 * logic to get the ire without doing the IPsec
25834 		 * processing. Follow the same old path. But this
25835 		 * time, ip_wput or ire_add_then_put will call us
25836 		 * directly as all the IPsec operations are done.
25837 		 */
25838 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25839 		mp->b_prev = NULL;
25840 		mp->b_next = NULL;
25841 
25842 		/*
25843 		 * If the IPsec packet was processed asynchronously,
25844 		 * drop it now.
25845 		 */
25846 		if (q == NULL) {
25847 			freemsg(ipsec_mp);
25848 			goto done;
25849 		}
25850 
25851 		/*
25852 		 * Since we're going through ip_newroute() again, we
25853 		 * need to make sure we don't:
25854 		 *
25855 		 *	1.) Trigger the ASSERT() with the ipha_ident
25856 		 *	    overloading.
25857 		 *	2.) Redo transport-layer checksumming, since we've
25858 		 *	    already done all that to get this far.
25859 		 *
25860 		 * The easiest way not do either of the above is to set
25861 		 * the ipha_ident field to IP_HDR_INCLUDED.
25862 		 */
25863 		ipha->ipha_ident = IP_HDR_INCLUDED;
25864 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
25865 		    zoneid, ipst);
25866 	}
25867 	goto done;
25868 send:
25869 	if (ire->ire_stq == NULL) {
25870 		ill_t	*out_ill;
25871 		/*
25872 		 * Loopbacks go through ip_wput_local except for one case.
25873 		 * We come here if we generate a icmp_frag_needed message
25874 		 * after IPsec processing is over. When this function calls
25875 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
25876 		 * icmp_frag_needed. The message generated comes back here
25877 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
25878 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
25879 		 * source address as it is usually set in ip_wput_ire. As
25880 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
25881 		 * and we end up here. We can't enter ip_wput_ire once the
25882 		 * IPsec processing is over and hence we need to do it here.
25883 		 */
25884 		ASSERT(q != NULL);
25885 		UPDATE_OB_PKT_COUNT(ire);
25886 		ire->ire_last_used_time = lbolt;
25887 		if (ipha->ipha_src == 0)
25888 			ipha->ipha_src = ire->ire_src_addr;
25889 
25890 		/* PFHooks: LOOPBACK_OUT */
25891 		out_ill = ire_to_ill(ire);
25892 
25893 		/*
25894 		 * DTrace this as ip:::send.  A blocked packet will fire the
25895 		 * send probe, but not the receive probe.
25896 		 */
25897 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25898 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
25899 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
25900 
25901 		DTRACE_PROBE4(ip4__loopback__out__start,
25902 		    ill_t *, NULL, ill_t *, out_ill,
25903 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
25904 
25905 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
25906 		    ipst->ips_ipv4firewall_loopback_out,
25907 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
25908 
25909 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
25910 
25911 		if (ipsec_mp != NULL)
25912 			ip_wput_local(RD(q), out_ill,
25913 			    ipha, ipsec_mp, ire, 0, zoneid);
25914 		if (ire_need_rele)
25915 			ire_refrele(ire);
25916 		goto done;
25917 	}
25918 
25919 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
25920 		/*
25921 		 * We are through with IPsec processing.
25922 		 * Fragment this and send it on the wire.
25923 		 */
25924 		if (io->ipsec_out_accelerated) {
25925 			/*
25926 			 * The packet has been accelerated but must
25927 			 * be fragmented. This should not happen
25928 			 * since AH and ESP must not accelerate
25929 			 * packets that need fragmentation, however
25930 			 * the configuration could have changed
25931 			 * since the AH or ESP processing.
25932 			 * Drop packet.
25933 			 * IPsec KSTATS: bump bean counter here.
25934 			 */
25935 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
25936 			    "fragmented accelerated packet!\n"));
25937 			freemsg(ipsec_mp);
25938 		} else {
25939 			ip_wput_ire_fragmentit(ipsec_mp, ire,
25940 			    zoneid, ipst, NULL);
25941 		}
25942 		if (ire_need_rele)
25943 			ire_refrele(ire);
25944 		goto done;
25945 	}
25946 
25947 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
25948 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
25949 	    (void *)ire->ire_ipif, (void *)ipif));
25950 
25951 	/*
25952 	 * Multiroute the secured packet.
25953 	 */
25954 	if (ire->ire_flags & RTF_MULTIRT) {
25955 		ire_t *first_ire;
25956 		irb = ire->ire_bucket;
25957 		ASSERT(irb != NULL);
25958 		/*
25959 		 * This ire has been looked up as the one that
25960 		 * goes through the given ipif;
25961 		 * make sure we do not omit any other multiroute ire
25962 		 * that may be present in the bucket before this one.
25963 		 */
25964 		IRB_REFHOLD(irb);
25965 		for (first_ire = irb->irb_ire;
25966 		    first_ire != NULL;
25967 		    first_ire = first_ire->ire_next) {
25968 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
25969 			    (first_ire->ire_addr == ire->ire_addr) &&
25970 			    !(first_ire->ire_marks &
25971 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
25972 				break;
25973 		}
25974 
25975 		if ((first_ire != NULL) && (first_ire != ire)) {
25976 			/*
25977 			 * Don't change the ire if the packet must
25978 			 * be fragmented if sent via this new one.
25979 			 */
25980 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
25981 				IRE_REFHOLD(first_ire);
25982 				if (ire_need_rele)
25983 					ire_refrele(ire);
25984 				else
25985 					ire_need_rele = B_TRUE;
25986 				ire = first_ire;
25987 			}
25988 		}
25989 		IRB_REFRELE(irb);
25990 
25991 		multirt_send = B_TRUE;
25992 		max_frag = ire->ire_max_frag;
25993 	}
25994 
25995 	/*
25996 	 * In most cases, the emission loop below is entered only once.
25997 	 * Only in the case where the ire holds the RTF_MULTIRT
25998 	 * flag, we loop to process all RTF_MULTIRT ires in the
25999 	 * bucket, and send the packet through all crossed
26000 	 * RTF_MULTIRT routes.
26001 	 */
26002 	do {
26003 		if (multirt_send) {
26004 			/*
26005 			 * ire1 holds here the next ire to process in the
26006 			 * bucket. If multirouting is expected,
26007 			 * any non-RTF_MULTIRT ire that has the
26008 			 * right destination address is ignored.
26009 			 */
26010 			ASSERT(irb != NULL);
26011 			IRB_REFHOLD(irb);
26012 			for (ire1 = ire->ire_next;
26013 			    ire1 != NULL;
26014 			    ire1 = ire1->ire_next) {
26015 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26016 					continue;
26017 				if (ire1->ire_addr != ire->ire_addr)
26018 					continue;
26019 				if (ire1->ire_marks &
26020 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
26021 					continue;
26022 				/* No loopback here */
26023 				if (ire1->ire_stq == NULL)
26024 					continue;
26025 				/*
26026 				 * Ensure we do not exceed the MTU
26027 				 * of the next route.
26028 				 */
26029 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26030 					ip_multirt_bad_mtu(ire1, max_frag);
26031 					continue;
26032 				}
26033 
26034 				IRE_REFHOLD(ire1);
26035 				break;
26036 			}
26037 			IRB_REFRELE(irb);
26038 			if (ire1 != NULL) {
26039 				/*
26040 				 * We are in a multiple send case, need to
26041 				 * make a copy of the packet.
26042 				 */
26043 				next_mp = copymsg(ipsec_mp);
26044 				if (next_mp == NULL) {
26045 					ire_refrele(ire1);
26046 					ire1 = NULL;
26047 				}
26048 			}
26049 		}
26050 		/*
26051 		 * Everything is done. Send it out on the wire
26052 		 *
26053 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26054 		 * either send it on the wire or, in the case of
26055 		 * HW acceleration, call ipsec_hw_putnext.
26056 		 */
26057 		if (ire->ire_nce &&
26058 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26059 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26060 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26061 			/*
26062 			 * If ire's link-layer is unresolved (this
26063 			 * would only happen if the incomplete ire
26064 			 * was added to cachetable via forwarding path)
26065 			 * don't bother going to ip_xmit_v4. Just drop the
26066 			 * packet.
26067 			 * There is a slight risk here, in that, if we
26068 			 * have the forwarding path create an incomplete
26069 			 * IRE, then until the IRE is completed, any
26070 			 * transmitted IPsec packets will be dropped
26071 			 * instead of being queued waiting for resolution.
26072 			 *
26073 			 * But the likelihood of a forwarding packet and a wput
26074 			 * packet sending to the same dst at the same time
26075 			 * and there not yet be an ARP entry for it is small.
26076 			 * Furthermore, if this actually happens, it might
26077 			 * be likely that wput would generate multiple
26078 			 * packets (and forwarding would also have a train
26079 			 * of packets) for that destination. If this is
26080 			 * the case, some of them would have been dropped
26081 			 * anyway, since ARP only queues a few packets while
26082 			 * waiting for resolution
26083 			 *
26084 			 * NOTE: We should really call ip_xmit_v4,
26085 			 * and let it queue the packet and send the
26086 			 * ARP query and have ARP come back thus:
26087 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26088 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26089 			 * hw accel work. But it's too complex to get
26090 			 * the IPsec hw  acceleration approach to fit
26091 			 * well with ip_xmit_v4 doing ARP without
26092 			 * doing IPsec simplification. For now, we just
26093 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26094 			 * that we can continue with the send on the next
26095 			 * attempt.
26096 			 *
26097 			 * XXX THis should be revisited, when
26098 			 * the IPsec/IP interaction is cleaned up
26099 			 */
26100 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26101 			    " - dropping packet\n"));
26102 			freemsg(ipsec_mp);
26103 			/*
26104 			 * Call ip_xmit_v4() to trigger ARP query
26105 			 * in case the nce_state is ND_INITIAL
26106 			 */
26107 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
26108 			goto drop_pkt;
26109 		}
26110 
26111 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26112 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26113 		    mblk_t *, ipsec_mp);
26114 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26115 		    ipst->ips_ipv4firewall_physical_out, NULL,
26116 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26117 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26118 		if (ipsec_mp == NULL)
26119 			goto drop_pkt;
26120 
26121 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26122 		pktxmit_state = ip_xmit_v4(mp, ire,
26123 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE, NULL);
26124 
26125 		if ((pktxmit_state ==  SEND_FAILED) ||
26126 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26127 
26128 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26129 drop_pkt:
26130 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26131 			    ipIfStatsOutDiscards);
26132 			if (ire_need_rele)
26133 				ire_refrele(ire);
26134 			if (ire1 != NULL) {
26135 				ire_refrele(ire1);
26136 				freemsg(next_mp);
26137 			}
26138 			goto done;
26139 		}
26140 
26141 		freeb(ipsec_mp);
26142 		if (ire_need_rele)
26143 			ire_refrele(ire);
26144 
26145 		if (ire1 != NULL) {
26146 			ire = ire1;
26147 			ire_need_rele = B_TRUE;
26148 			ASSERT(next_mp);
26149 			ipsec_mp = next_mp;
26150 			mp = ipsec_mp->b_cont;
26151 			ire1 = NULL;
26152 			next_mp = NULL;
26153 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26154 		} else {
26155 			multirt_send = B_FALSE;
26156 		}
26157 	} while (multirt_send);
26158 done:
26159 	if (ill != NULL && ill_need_rele)
26160 		ill_refrele(ill);
26161 	if (ipif != NULL)
26162 		ipif_refrele(ipif);
26163 }
26164 
26165 /*
26166  * Get the ill corresponding to the specified ire, and compare its
26167  * capabilities with the protocol and algorithms specified by the
26168  * the SA obtained from ipsec_out. If they match, annotate the
26169  * ipsec_out structure to indicate that the packet needs acceleration.
26170  *
26171  *
26172  * A packet is eligible for outbound hardware acceleration if the
26173  * following conditions are satisfied:
26174  *
26175  * 1. the packet will not be fragmented
26176  * 2. the provider supports the algorithm
26177  * 3. there is no pending control message being exchanged
26178  * 4. snoop is not attached
26179  * 5. the destination address is not a broadcast or multicast address.
26180  *
26181  * Rationale:
26182  *	- Hardware drivers do not support fragmentation with
26183  *	  the current interface.
26184  *	- snoop, multicast, and broadcast may result in exposure of
26185  *	  a cleartext datagram.
26186  * We check all five of these conditions here.
26187  *
26188  * XXX would like to nuke "ire_t *" parameter here; problem is that
26189  * IRE is only way to figure out if a v4 address is a broadcast and
26190  * thus ineligible for acceleration...
26191  */
26192 static void
26193 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26194 {
26195 	ipsec_out_t *io;
26196 	mblk_t *data_mp;
26197 	uint_t plen, overhead;
26198 	ip_stack_t	*ipst;
26199 
26200 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26201 		return;
26202 
26203 	if (ill == NULL)
26204 		return;
26205 	ipst = ill->ill_ipst;
26206 	/*
26207 	 * Destination address is a broadcast or multicast.  Punt.
26208 	 */
26209 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26210 	    IRE_LOCAL)))
26211 		return;
26212 
26213 	data_mp = ipsec_mp->b_cont;
26214 
26215 	if (ill->ill_isv6) {
26216 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26217 
26218 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26219 			return;
26220 
26221 		plen = ip6h->ip6_plen;
26222 	} else {
26223 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26224 
26225 		if (CLASSD(ipha->ipha_dst))
26226 			return;
26227 
26228 		plen = ipha->ipha_length;
26229 	}
26230 	/*
26231 	 * Is there a pending DLPI control message being exchanged
26232 	 * between IP/IPsec and the DLS Provider? If there is, it
26233 	 * could be a SADB update, and the state of the DLS Provider
26234 	 * SADB might not be in sync with the SADB maintained by
26235 	 * IPsec. To avoid dropping packets or using the wrong keying
26236 	 * material, we do not accelerate this packet.
26237 	 */
26238 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26239 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26240 		    "ill_dlpi_pending! don't accelerate packet\n"));
26241 		return;
26242 	}
26243 
26244 	/*
26245 	 * Is the Provider in promiscous mode? If it does, we don't
26246 	 * accelerate the packet since it will bounce back up to the
26247 	 * listeners in the clear.
26248 	 */
26249 	if (ill->ill_promisc_on_phys) {
26250 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26251 		    "ill in promiscous mode, don't accelerate packet\n"));
26252 		return;
26253 	}
26254 
26255 	/*
26256 	 * Will the packet require fragmentation?
26257 	 */
26258 
26259 	/*
26260 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26261 	 * as is used elsewhere.
26262 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26263 	 *	+ 2-byte trailer
26264 	 */
26265 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26266 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26267 
26268 	if ((plen + overhead) > ill->ill_max_mtu)
26269 		return;
26270 
26271 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26272 
26273 	/*
26274 	 * Can the ill accelerate this IPsec protocol and algorithm
26275 	 * specified by the SA?
26276 	 */
26277 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26278 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26279 		return;
26280 	}
26281 
26282 	/*
26283 	 * Tell AH or ESP that the outbound ill is capable of
26284 	 * accelerating this packet.
26285 	 */
26286 	io->ipsec_out_is_capab_ill = B_TRUE;
26287 }
26288 
26289 /*
26290  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26291  *
26292  * If this function returns B_TRUE, the requested SA's have been filled
26293  * into the ipsec_out_*_sa pointers.
26294  *
26295  * If the function returns B_FALSE, the packet has been "consumed", most
26296  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26297  *
26298  * The SA references created by the protocol-specific "select"
26299  * function will be released when the ipsec_mp is freed, thanks to the
26300  * ipsec_out_free destructor -- see spd.c.
26301  */
26302 static boolean_t
26303 ipsec_out_select_sa(mblk_t *ipsec_mp)
26304 {
26305 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26306 	ipsec_out_t *io;
26307 	ipsec_policy_t *pp;
26308 	ipsec_action_t *ap;
26309 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26310 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26311 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26312 
26313 	if (!io->ipsec_out_secure) {
26314 		/*
26315 		 * We came here by mistake.
26316 		 * Don't bother with ipsec processing
26317 		 * We should "discourage" this path in the future.
26318 		 */
26319 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26320 		return (B_FALSE);
26321 	}
26322 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26323 	ASSERT((io->ipsec_out_policy != NULL) ||
26324 	    (io->ipsec_out_act != NULL));
26325 
26326 	ASSERT(io->ipsec_out_failed == B_FALSE);
26327 
26328 	/*
26329 	 * IPsec processing has started.
26330 	 */
26331 	io->ipsec_out_proc_begin = B_TRUE;
26332 	ap = io->ipsec_out_act;
26333 	if (ap == NULL) {
26334 		pp = io->ipsec_out_policy;
26335 		ASSERT(pp != NULL);
26336 		ap = pp->ipsp_act;
26337 		ASSERT(ap != NULL);
26338 	}
26339 
26340 	/*
26341 	 * We have an action.  now, let's select SA's.
26342 	 * (In the future, we can cache this in the conn_t..)
26343 	 */
26344 	if (ap->ipa_want_esp) {
26345 		if (io->ipsec_out_esp_sa == NULL) {
26346 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26347 			    IPPROTO_ESP);
26348 		}
26349 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26350 	}
26351 
26352 	if (ap->ipa_want_ah) {
26353 		if (io->ipsec_out_ah_sa == NULL) {
26354 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26355 			    IPPROTO_AH);
26356 		}
26357 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26358 		/*
26359 		 * The ESP and AH processing order needs to be preserved
26360 		 * when both protocols are required (ESP should be applied
26361 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26362 		 * when both ESP and AH are required, and an AH ACQUIRE
26363 		 * is needed.
26364 		 */
26365 		if (ap->ipa_want_esp && need_ah_acquire)
26366 			need_esp_acquire = B_TRUE;
26367 	}
26368 
26369 	/*
26370 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26371 	 * Release SAs that got referenced, but will not be used until we
26372 	 * acquire _all_ of the SAs we need.
26373 	 */
26374 	if (need_ah_acquire || need_esp_acquire) {
26375 		if (io->ipsec_out_ah_sa != NULL) {
26376 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26377 			io->ipsec_out_ah_sa = NULL;
26378 		}
26379 		if (io->ipsec_out_esp_sa != NULL) {
26380 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26381 			io->ipsec_out_esp_sa = NULL;
26382 		}
26383 
26384 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26385 		return (B_FALSE);
26386 	}
26387 
26388 	return (B_TRUE);
26389 }
26390 
26391 /*
26392  * Process an IPSEC_OUT message and see what you can
26393  * do with it.
26394  * IPQoS Notes:
26395  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26396  * IPsec.
26397  * XXX would like to nuke ire_t.
26398  * XXX ill_index better be "real"
26399  */
26400 void
26401 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26402 {
26403 	ipsec_out_t *io;
26404 	ipsec_policy_t *pp;
26405 	ipsec_action_t *ap;
26406 	ipha_t *ipha;
26407 	ip6_t *ip6h;
26408 	mblk_t *mp;
26409 	ill_t *ill;
26410 	zoneid_t zoneid;
26411 	ipsec_status_t ipsec_rc;
26412 	boolean_t ill_need_rele = B_FALSE;
26413 	ip_stack_t	*ipst;
26414 	ipsec_stack_t	*ipss;
26415 
26416 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26417 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26418 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26419 	ipst = io->ipsec_out_ns->netstack_ip;
26420 	mp = ipsec_mp->b_cont;
26421 
26422 	/*
26423 	 * Initiate IPPF processing. We do it here to account for packets
26424 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26425 	 * We can check for ipsec_out_proc_begin even for such packets, as
26426 	 * they will always be false (asserted below).
26427 	 */
26428 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26429 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26430 		    io->ipsec_out_ill_index : ill_index);
26431 		if (mp == NULL) {
26432 			ip2dbg(("ipsec_out_process: packet dropped "\
26433 			    "during IPPF processing\n"));
26434 			freeb(ipsec_mp);
26435 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26436 			return;
26437 		}
26438 	}
26439 
26440 	if (!io->ipsec_out_secure) {
26441 		/*
26442 		 * We came here by mistake.
26443 		 * Don't bother with ipsec processing
26444 		 * Should "discourage" this path in the future.
26445 		 */
26446 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26447 		goto done;
26448 	}
26449 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26450 	ASSERT((io->ipsec_out_policy != NULL) ||
26451 	    (io->ipsec_out_act != NULL));
26452 	ASSERT(io->ipsec_out_failed == B_FALSE);
26453 
26454 	ipss = ipst->ips_netstack->netstack_ipsec;
26455 	if (!ipsec_loaded(ipss)) {
26456 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26457 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26458 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26459 		} else {
26460 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26461 		}
26462 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26463 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26464 		    &ipss->ipsec_dropper);
26465 		return;
26466 	}
26467 
26468 	/*
26469 	 * IPsec processing has started.
26470 	 */
26471 	io->ipsec_out_proc_begin = B_TRUE;
26472 	ap = io->ipsec_out_act;
26473 	if (ap == NULL) {
26474 		pp = io->ipsec_out_policy;
26475 		ASSERT(pp != NULL);
26476 		ap = pp->ipsp_act;
26477 		ASSERT(ap != NULL);
26478 	}
26479 
26480 	/*
26481 	 * Save the outbound ill index. When the packet comes back
26482 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26483 	 * before sending it the accelerated packet.
26484 	 */
26485 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26486 		ill = ire_to_ill(ire);
26487 		io->ipsec_out_capab_ill_index = ill->ill_phyint->phyint_ifindex;
26488 	}
26489 
26490 	/*
26491 	 * The order of processing is first insert a IP header if needed.
26492 	 * Then insert the ESP header and then the AH header.
26493 	 */
26494 	if ((io->ipsec_out_se_done == B_FALSE) &&
26495 	    (ap->ipa_want_se)) {
26496 		/*
26497 		 * First get the outer IP header before sending
26498 		 * it to ESP.
26499 		 */
26500 		ipha_t *oipha, *iipha;
26501 		mblk_t *outer_mp, *inner_mp;
26502 
26503 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26504 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26505 			    "ipsec_out_process: "
26506 			    "Self-Encapsulation failed: Out of memory\n");
26507 			freemsg(ipsec_mp);
26508 			if (ill != NULL) {
26509 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26510 			} else {
26511 				BUMP_MIB(&ipst->ips_ip_mib,
26512 				    ipIfStatsOutDiscards);
26513 			}
26514 			return;
26515 		}
26516 		inner_mp = ipsec_mp->b_cont;
26517 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26518 		oipha = (ipha_t *)outer_mp->b_rptr;
26519 		iipha = (ipha_t *)inner_mp->b_rptr;
26520 		*oipha = *iipha;
26521 		outer_mp->b_wptr += sizeof (ipha_t);
26522 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26523 		    sizeof (ipha_t));
26524 		oipha->ipha_protocol = IPPROTO_ENCAP;
26525 		oipha->ipha_version_and_hdr_length =
26526 		    IP_SIMPLE_HDR_VERSION;
26527 		oipha->ipha_hdr_checksum = 0;
26528 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26529 		outer_mp->b_cont = inner_mp;
26530 		ipsec_mp->b_cont = outer_mp;
26531 
26532 		io->ipsec_out_se_done = B_TRUE;
26533 		io->ipsec_out_tunnel = B_TRUE;
26534 	}
26535 
26536 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26537 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26538 	    !ipsec_out_select_sa(ipsec_mp))
26539 		return;
26540 
26541 	/*
26542 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26543 	 * to do the heavy lifting.
26544 	 */
26545 	zoneid = io->ipsec_out_zoneid;
26546 	ASSERT(zoneid != ALL_ZONES);
26547 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26548 		ASSERT(io->ipsec_out_esp_sa != NULL);
26549 		io->ipsec_out_esp_done = B_TRUE;
26550 		/*
26551 		 * Note that since hw accel can only apply one transform,
26552 		 * not two, we skip hw accel for ESP if we also have AH
26553 		 * This is an design limitation of the interface
26554 		 * which should be revisited.
26555 		 */
26556 		ASSERT(ire != NULL);
26557 		if (io->ipsec_out_ah_sa == NULL) {
26558 			ill = (ill_t *)ire->ire_stq->q_ptr;
26559 			ipsec_out_is_accelerated(ipsec_mp,
26560 			    io->ipsec_out_esp_sa, ill, ire);
26561 		}
26562 
26563 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26564 		switch (ipsec_rc) {
26565 		case IPSEC_STATUS_SUCCESS:
26566 			break;
26567 		case IPSEC_STATUS_FAILED:
26568 			if (ill != NULL) {
26569 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26570 			} else {
26571 				BUMP_MIB(&ipst->ips_ip_mib,
26572 				    ipIfStatsOutDiscards);
26573 			}
26574 			/* FALLTHRU */
26575 		case IPSEC_STATUS_PENDING:
26576 			return;
26577 		}
26578 	}
26579 
26580 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26581 		ASSERT(io->ipsec_out_ah_sa != NULL);
26582 		io->ipsec_out_ah_done = B_TRUE;
26583 		if (ire == NULL) {
26584 			int idx = io->ipsec_out_capab_ill_index;
26585 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26586 			    NULL, NULL, NULL, NULL, ipst);
26587 			ill_need_rele = B_TRUE;
26588 		} else {
26589 			ill = (ill_t *)ire->ire_stq->q_ptr;
26590 		}
26591 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26592 		    ire);
26593 
26594 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26595 		switch (ipsec_rc) {
26596 		case IPSEC_STATUS_SUCCESS:
26597 			break;
26598 		case IPSEC_STATUS_FAILED:
26599 			if (ill != NULL) {
26600 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26601 			} else {
26602 				BUMP_MIB(&ipst->ips_ip_mib,
26603 				    ipIfStatsOutDiscards);
26604 			}
26605 			/* FALLTHRU */
26606 		case IPSEC_STATUS_PENDING:
26607 			if (ill != NULL && ill_need_rele)
26608 				ill_refrele(ill);
26609 			return;
26610 		}
26611 	}
26612 	/*
26613 	 * We are done with IPsec processing. Send it over the wire.
26614 	 */
26615 done:
26616 	mp = ipsec_mp->b_cont;
26617 	ipha = (ipha_t *)mp->b_rptr;
26618 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26619 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ire->ire_ipif->ipif_ill,
26620 		    ire);
26621 	} else {
26622 		ip6h = (ip6_t *)ipha;
26623 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ire->ire_ipif->ipif_ill,
26624 		    ire);
26625 	}
26626 	if (ill != NULL && ill_need_rele)
26627 		ill_refrele(ill);
26628 }
26629 
26630 /* ARGSUSED */
26631 void
26632 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26633 {
26634 	opt_restart_t	*or;
26635 	int	err;
26636 	conn_t	*connp;
26637 
26638 	ASSERT(CONN_Q(q));
26639 	connp = Q_TO_CONN(q);
26640 
26641 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26642 	or = (opt_restart_t *)first_mp->b_rptr;
26643 	/*
26644 	 * We don't need to pass any credentials here since this is just
26645 	 * a restart. The credentials are passed in when svr4_optcom_req
26646 	 * is called the first time (from ip_wput_nondata).
26647 	 */
26648 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26649 		err = svr4_optcom_req(q, first_mp, NULL,
26650 		    &ip_opt_obj, B_FALSE);
26651 	} else {
26652 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26653 		err = tpi_optcom_req(q, first_mp, NULL,
26654 		    &ip_opt_obj, B_FALSE);
26655 	}
26656 	if (err != EINPROGRESS) {
26657 		/* operation is done */
26658 		CONN_OPER_PENDING_DONE(connp);
26659 	}
26660 }
26661 
26662 /*
26663  * ioctls that go through a down/up sequence may need to wait for the down
26664  * to complete. This involves waiting for the ire and ipif refcnts to go down
26665  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26666  */
26667 /* ARGSUSED */
26668 void
26669 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26670 {
26671 	struct iocblk *iocp;
26672 	mblk_t *mp1;
26673 	ip_ioctl_cmd_t *ipip;
26674 	int err;
26675 	sin_t	*sin;
26676 	struct lifreq *lifr;
26677 	struct ifreq *ifr;
26678 
26679 	iocp = (struct iocblk *)mp->b_rptr;
26680 	ASSERT(ipsq != NULL);
26681 	/* Existence of mp1 verified in ip_wput_nondata */
26682 	mp1 = mp->b_cont->b_cont;
26683 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26684 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26685 		/*
26686 		 * Special case where ipx_current_ipif is not set:
26687 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26688 		 * We are here as were not able to complete the operation in
26689 		 * ipif_set_values because we could not become exclusive on
26690 		 * the new ipsq.
26691 		 */
26692 		ill_t *ill = q->q_ptr;
26693 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26694 	}
26695 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
26696 
26697 	if (ipip->ipi_cmd_type == IF_CMD) {
26698 		/* This a old style SIOC[GS]IF* command */
26699 		ifr = (struct ifreq *)mp1->b_rptr;
26700 		sin = (sin_t *)&ifr->ifr_addr;
26701 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26702 		/* This a new style SIOC[GS]LIF* command */
26703 		lifr = (struct lifreq *)mp1->b_rptr;
26704 		sin = (sin_t *)&lifr->lifr_addr;
26705 	} else {
26706 		sin = NULL;
26707 	}
26708 
26709 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
26710 	    q, mp, ipip, mp1->b_rptr);
26711 
26712 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26713 }
26714 
26715 /*
26716  * ioctl processing
26717  *
26718  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26719  * the ioctl command in the ioctl tables, determines the copyin data size
26720  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26721  *
26722  * ioctl processing then continues when the M_IOCDATA makes its way down to
26723  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26724  * associated 'conn' is refheld till the end of the ioctl and the general
26725  * ioctl processing function ip_process_ioctl() is called to extract the
26726  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26727  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26728  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26729  * is used to extract the ioctl's arguments.
26730  *
26731  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26732  * so goes thru the serialization primitive ipsq_try_enter. Then the
26733  * appropriate function to handle the ioctl is called based on the entry in
26734  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26735  * which also refreleases the 'conn' that was refheld at the start of the
26736  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26737  *
26738  * Many exclusive ioctls go thru an internal down up sequence as part of
26739  * the operation. For example an attempt to change the IP address of an
26740  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26741  * does all the cleanup such as deleting all ires that use this address.
26742  * Then we need to wait till all references to the interface go away.
26743  */
26744 void
26745 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26746 {
26747 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26748 	ip_ioctl_cmd_t *ipip = arg;
26749 	ip_extract_func_t *extract_funcp;
26750 	cmd_info_t ci;
26751 	int err;
26752 	boolean_t entered_ipsq = B_FALSE;
26753 
26754 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26755 
26756 	if (ipip == NULL)
26757 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26758 
26759 	/*
26760 	 * SIOCLIFADDIF needs to go thru a special path since the
26761 	 * ill may not exist yet. This happens in the case of lo0
26762 	 * which is created using this ioctl.
26763 	 */
26764 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26765 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26766 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26767 		return;
26768 	}
26769 
26770 	ci.ci_ipif = NULL;
26771 	if (ipip->ipi_cmd_type == MISC_CMD) {
26772 		/*
26773 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26774 		 */
26775 		if (ipip->ipi_cmd == IF_UNITSEL) {
26776 			/* ioctl comes down the ill */
26777 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26778 			ipif_refhold(ci.ci_ipif);
26779 		}
26780 		err = 0;
26781 		ci.ci_sin = NULL;
26782 		ci.ci_sin6 = NULL;
26783 		ci.ci_lifr = NULL;
26784 	} else {
26785 		switch (ipip->ipi_cmd_type) {
26786 		case IF_CMD:
26787 		case LIF_CMD:
26788 			extract_funcp = ip_extract_lifreq;
26789 			break;
26790 
26791 		case ARP_CMD:
26792 		case XARP_CMD:
26793 			extract_funcp = ip_extract_arpreq;
26794 			break;
26795 
26796 		case TUN_CMD:
26797 			extract_funcp = ip_extract_tunreq;
26798 			break;
26799 
26800 		case MSFILT_CMD:
26801 			extract_funcp = ip_extract_msfilter;
26802 			break;
26803 
26804 		default:
26805 			ASSERT(0);
26806 		}
26807 
26808 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
26809 		if (err != 0) {
26810 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26811 			return;
26812 		}
26813 
26814 		/*
26815 		 * All of the extraction functions return a refheld ipif.
26816 		 */
26817 		ASSERT(ci.ci_ipif != NULL);
26818 	}
26819 
26820 	if (!(ipip->ipi_flags & IPI_WR)) {
26821 		/*
26822 		 * A return value of EINPROGRESS means the ioctl is
26823 		 * either queued and waiting for some reason or has
26824 		 * already completed.
26825 		 */
26826 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26827 		    ci.ci_lifr);
26828 		if (ci.ci_ipif != NULL)
26829 			ipif_refrele(ci.ci_ipif);
26830 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26831 		return;
26832 	}
26833 
26834 	ASSERT(ci.ci_ipif != NULL);
26835 
26836 	/*
26837 	 * If ipsq is non-NULL, we are already being called exclusively.
26838 	 */
26839 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26840 	if (ipsq == NULL) {
26841 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
26842 		    NEW_OP, B_TRUE);
26843 		if (ipsq == NULL) {
26844 			ipif_refrele(ci.ci_ipif);
26845 			return;
26846 		}
26847 		entered_ipsq = B_TRUE;
26848 	}
26849 
26850 	/*
26851 	 * Release the ipif so that ipif_down and friends that wait for
26852 	 * references to go away are not misled about the current ipif_refcnt
26853 	 * values. We are writer so we can access the ipif even after releasing
26854 	 * the ipif.
26855 	 */
26856 	ipif_refrele(ci.ci_ipif);
26857 
26858 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
26859 
26860 	/*
26861 	 * For most set ioctls that come here, this serves as a single point
26862 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
26863 	 * be any new references to the ipif. This helps functions that go
26864 	 * through this path and end up trying to wait for the refcnts
26865 	 * associated with the ipif to go down to zero.  The exception is
26866 	 * SIOCSLIFREMOVEIF, which sets IPIF_CONDEMNED internally after
26867 	 * identifying the right ipif to operate on.
26868 	 */
26869 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
26870 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF)
26871 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
26872 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
26873 
26874 	/*
26875 	 * A return value of EINPROGRESS means the ioctl is
26876 	 * either queued and waiting for some reason or has
26877 	 * already completed.
26878 	 */
26879 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
26880 
26881 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26882 
26883 	if (entered_ipsq)
26884 		ipsq_exit(ipsq);
26885 }
26886 
26887 /*
26888  * Complete the ioctl. Typically ioctls use the mi package and need to
26889  * do mi_copyout/mi_copy_done.
26890  */
26891 void
26892 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
26893 {
26894 	conn_t	*connp = NULL;
26895 
26896 	if (err == EINPROGRESS)
26897 		return;
26898 
26899 	if (CONN_Q(q)) {
26900 		connp = Q_TO_CONN(q);
26901 		ASSERT(connp->conn_ref >= 2);
26902 	}
26903 
26904 	switch (mode) {
26905 	case COPYOUT:
26906 		if (err == 0)
26907 			mi_copyout(q, mp);
26908 		else
26909 			mi_copy_done(q, mp, err);
26910 		break;
26911 
26912 	case NO_COPYOUT:
26913 		mi_copy_done(q, mp, err);
26914 		break;
26915 
26916 	default:
26917 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
26918 		break;
26919 	}
26920 
26921 	/*
26922 	 * The refhold placed at the start of the ioctl is released here.
26923 	 */
26924 	if (connp != NULL)
26925 		CONN_OPER_PENDING_DONE(connp);
26926 
26927 	if (ipsq != NULL)
26928 		ipsq_current_finish(ipsq);
26929 }
26930 
26931 /* Called from ip_wput for all non data messages */
26932 /* ARGSUSED */
26933 void
26934 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26935 {
26936 	mblk_t		*mp1;
26937 	ire_t		*ire, *fake_ire;
26938 	ill_t		*ill;
26939 	struct iocblk	*iocp;
26940 	ip_ioctl_cmd_t	*ipip;
26941 	cred_t		*cr;
26942 	conn_t		*connp;
26943 	int		err;
26944 	nce_t		*nce;
26945 	ipif_t		*ipif;
26946 	ip_stack_t	*ipst;
26947 	char		*proto_str;
26948 
26949 	if (CONN_Q(q)) {
26950 		connp = Q_TO_CONN(q);
26951 		ipst = connp->conn_netstack->netstack_ip;
26952 	} else {
26953 		connp = NULL;
26954 		ipst = ILLQ_TO_IPST(q);
26955 	}
26956 
26957 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
26958 
26959 	switch (DB_TYPE(mp)) {
26960 	case M_IOCTL:
26961 		/*
26962 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
26963 		 * will arrange to copy in associated control structures.
26964 		 */
26965 		ip_sioctl_copyin_setup(q, mp);
26966 		return;
26967 	case M_IOCDATA:
26968 		/*
26969 		 * Ensure that this is associated with one of our trans-
26970 		 * parent ioctls.  If it's not ours, discard it if we're
26971 		 * running as a driver, or pass it on if we're a module.
26972 		 */
26973 		iocp = (struct iocblk *)mp->b_rptr;
26974 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26975 		if (ipip == NULL) {
26976 			if (q->q_next == NULL) {
26977 				goto nak;
26978 			} else {
26979 				putnext(q, mp);
26980 			}
26981 			return;
26982 		}
26983 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
26984 			/*
26985 			 * the ioctl is one we recognise, but is not
26986 			 * consumed by IP as a module, pass M_IOCDATA
26987 			 * for processing downstream, but only for
26988 			 * common Streams ioctls.
26989 			 */
26990 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
26991 				putnext(q, mp);
26992 				return;
26993 			} else {
26994 				goto nak;
26995 			}
26996 		}
26997 
26998 		/* IOCTL continuation following copyin or copyout. */
26999 		if (mi_copy_state(q, mp, NULL) == -1) {
27000 			/*
27001 			 * The copy operation failed.  mi_copy_state already
27002 			 * cleaned up, so we're out of here.
27003 			 */
27004 			return;
27005 		}
27006 		/*
27007 		 * If we just completed a copy in, we become writer and
27008 		 * continue processing in ip_sioctl_copyin_done.  If it
27009 		 * was a copy out, we call mi_copyout again.  If there is
27010 		 * nothing more to copy out, it will complete the IOCTL.
27011 		 */
27012 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27013 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27014 				mi_copy_done(q, mp, EPROTO);
27015 				return;
27016 			}
27017 			/*
27018 			 * Check for cases that need more copying.  A return
27019 			 * value of 0 means a second copyin has been started,
27020 			 * so we return; a return value of 1 means no more
27021 			 * copying is needed, so we continue.
27022 			 */
27023 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27024 			    MI_COPY_COUNT(mp) == 1) {
27025 				if (ip_copyin_msfilter(q, mp) == 0)
27026 					return;
27027 			}
27028 			/*
27029 			 * Refhold the conn, till the ioctl completes. This is
27030 			 * needed in case the ioctl ends up in the pending mp
27031 			 * list. Every mp in the ill_pending_mp list and
27032 			 * the ipx_pending_mp must have a refhold on the conn
27033 			 * to resume processing. The refhold is released when
27034 			 * the ioctl completes. (normally or abnormally)
27035 			 * In all cases ip_ioctl_finish is called to finish
27036 			 * the ioctl.
27037 			 */
27038 			if (connp != NULL) {
27039 				/* This is not a reentry */
27040 				ASSERT(ipsq == NULL);
27041 				CONN_INC_REF(connp);
27042 			} else {
27043 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27044 					mi_copy_done(q, mp, EINVAL);
27045 					return;
27046 				}
27047 			}
27048 
27049 			ip_process_ioctl(ipsq, q, mp, ipip);
27050 
27051 		} else {
27052 			mi_copyout(q, mp);
27053 		}
27054 		return;
27055 nak:
27056 		iocp->ioc_error = EINVAL;
27057 		mp->b_datap->db_type = M_IOCNAK;
27058 		iocp->ioc_count = 0;
27059 		qreply(q, mp);
27060 		return;
27061 
27062 	case M_IOCNAK:
27063 		/*
27064 		 * The only way we could get here is if a resolver didn't like
27065 		 * an IOCTL we sent it.	 This shouldn't happen.
27066 		 */
27067 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27068 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27069 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27070 		freemsg(mp);
27071 		return;
27072 	case M_IOCACK:
27073 		/* /dev/ip shouldn't see this */
27074 		if (CONN_Q(q))
27075 			goto nak;
27076 
27077 		/*
27078 		 * Finish socket ioctls passed through to ARP.  We use the
27079 		 * ioc_cmd values we set in ip_sioctl_arp() to decide whether
27080 		 * we need to become writer before calling ip_sioctl_iocack().
27081 		 * Note that qwriter_ip() will release the refhold, and that a
27082 		 * refhold is OK without ILL_CAN_LOOKUP() since we're on the
27083 		 * ill stream.
27084 		 */
27085 		iocp = (struct iocblk *)mp->b_rptr;
27086 		if (iocp->ioc_cmd == AR_ENTRY_SQUERY) {
27087 			ip_sioctl_iocack(NULL, q, mp, NULL);
27088 			return;
27089 		}
27090 
27091 		ASSERT(iocp->ioc_cmd == AR_ENTRY_DELETE ||
27092 		    iocp->ioc_cmd == AR_ENTRY_ADD);
27093 		ill = q->q_ptr;
27094 		ill_refhold(ill);
27095 		qwriter_ip(ill, q, mp, ip_sioctl_iocack, CUR_OP, B_FALSE);
27096 		return;
27097 	case M_FLUSH:
27098 		if (*mp->b_rptr & FLUSHW)
27099 			flushq(q, FLUSHALL);
27100 		if (q->q_next) {
27101 			putnext(q, mp);
27102 			return;
27103 		}
27104 		if (*mp->b_rptr & FLUSHR) {
27105 			*mp->b_rptr &= ~FLUSHW;
27106 			qreply(q, mp);
27107 			return;
27108 		}
27109 		freemsg(mp);
27110 		return;
27111 	case IRE_DB_REQ_TYPE:
27112 		if (connp == NULL) {
27113 			proto_str = "IRE_DB_REQ_TYPE";
27114 			goto protonak;
27115 		}
27116 		/* An Upper Level Protocol wants a copy of an IRE. */
27117 		ip_ire_req(q, mp);
27118 		return;
27119 	case M_CTL:
27120 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27121 			break;
27122 
27123 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27124 		    TUN_HELLO) {
27125 			ASSERT(connp != NULL);
27126 			connp->conn_flags |= IPCL_IPTUN;
27127 			freeb(mp);
27128 			return;
27129 		}
27130 
27131 		/* M_CTL messages are used by ARP to tell us things. */
27132 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27133 			break;
27134 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27135 		case AR_ENTRY_SQUERY:
27136 			ip_wput_ctl(q, mp);
27137 			return;
27138 		case AR_CLIENT_NOTIFY:
27139 			ip_arp_news(q, mp);
27140 			return;
27141 		case AR_DLPIOP_DONE:
27142 			ASSERT(q->q_next != NULL);
27143 			ill = (ill_t *)q->q_ptr;
27144 			/* qwriter_ip releases the refhold */
27145 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27146 			ill_refhold(ill);
27147 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27148 			return;
27149 		case AR_ARP_CLOSING:
27150 			/*
27151 			 * ARP (above us) is closing. If no ARP bringup is
27152 			 * currently pending, ack the message so that ARP
27153 			 * can complete its close. Also mark ill_arp_closing
27154 			 * so that new ARP bringups will fail. If any
27155 			 * ARP bringup is currently in progress, we will
27156 			 * ack this when the current ARP bringup completes.
27157 			 */
27158 			ASSERT(q->q_next != NULL);
27159 			ill = (ill_t *)q->q_ptr;
27160 			mutex_enter(&ill->ill_lock);
27161 			ill->ill_arp_closing = 1;
27162 			if (!ill->ill_arp_bringup_pending) {
27163 				mutex_exit(&ill->ill_lock);
27164 				qreply(q, mp);
27165 			} else {
27166 				mutex_exit(&ill->ill_lock);
27167 				freemsg(mp);
27168 			}
27169 			return;
27170 		case AR_ARP_EXTEND:
27171 			/*
27172 			 * The ARP module above us is capable of duplicate
27173 			 * address detection.  Old ATM drivers will not send
27174 			 * this message.
27175 			 */
27176 			ASSERT(q->q_next != NULL);
27177 			ill = (ill_t *)q->q_ptr;
27178 			ill->ill_arp_extend = B_TRUE;
27179 			freemsg(mp);
27180 			return;
27181 		default:
27182 			break;
27183 		}
27184 		break;
27185 	case M_PROTO:
27186 	case M_PCPROTO:
27187 		/*
27188 		 * The only PROTO messages we expect are copies of option
27189 		 * negotiation acknowledgements, AH and ESP bind requests
27190 		 * are also expected.
27191 		 */
27192 		switch (((union T_primitives *)mp->b_rptr)->type) {
27193 		case O_T_BIND_REQ:
27194 		case T_BIND_REQ: {
27195 			/* Request can get queued in bind */
27196 			if (connp == NULL) {
27197 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27198 				goto protonak;
27199 			}
27200 			/*
27201 			 * The transports except SCTP call ip_bind_{v4,v6}()
27202 			 * directly instead of a a putnext. SCTP doesn't
27203 			 * generate any T_BIND_REQ since it has its own
27204 			 * fanout data structures. However, ESP and AH
27205 			 * come in for regular binds; all other cases are
27206 			 * bind retries.
27207 			 */
27208 			ASSERT(!IPCL_IS_SCTP(connp));
27209 
27210 			/* Don't increment refcnt if this is a re-entry */
27211 			if (ipsq == NULL)
27212 				CONN_INC_REF(connp);
27213 
27214 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27215 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27216 			ASSERT(mp != NULL);
27217 
27218 			ASSERT(!IPCL_IS_TCP(connp));
27219 			ASSERT(!IPCL_IS_UDP(connp));
27220 			ASSERT(!IPCL_IS_RAWIP(connp));
27221 
27222 			/* The case of AH and ESP */
27223 			qreply(q, mp);
27224 			CONN_OPER_PENDING_DONE(connp);
27225 			return;
27226 		}
27227 		case T_SVR4_OPTMGMT_REQ:
27228 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27229 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27230 
27231 			if (connp == NULL) {
27232 				proto_str = "T_SVR4_OPTMGMT_REQ";
27233 				goto protonak;
27234 			}
27235 
27236 			if (!snmpcom_req(q, mp, ip_snmp_set,
27237 			    ip_snmp_get, cr)) {
27238 				/*
27239 				 * Call svr4_optcom_req so that it can
27240 				 * generate the ack. We don't come here
27241 				 * if this operation is being restarted.
27242 				 * ip_restart_optmgmt will drop the conn ref.
27243 				 * In the case of ipsec option after the ipsec
27244 				 * load is complete conn_restart_ipsec_waiter
27245 				 * drops the conn ref.
27246 				 */
27247 				ASSERT(ipsq == NULL);
27248 				CONN_INC_REF(connp);
27249 				if (ip_check_for_ipsec_opt(q, mp))
27250 					return;
27251 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27252 				    B_FALSE);
27253 				if (err != EINPROGRESS) {
27254 					/* Operation is done */
27255 					CONN_OPER_PENDING_DONE(connp);
27256 				}
27257 			}
27258 			return;
27259 		case T_OPTMGMT_REQ:
27260 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27261 			/*
27262 			 * Note: No snmpcom_req support through new
27263 			 * T_OPTMGMT_REQ.
27264 			 * Call tpi_optcom_req so that it can
27265 			 * generate the ack.
27266 			 */
27267 			if (connp == NULL) {
27268 				proto_str = "T_OPTMGMT_REQ";
27269 				goto protonak;
27270 			}
27271 
27272 			ASSERT(ipsq == NULL);
27273 			/*
27274 			 * We don't come here for restart. ip_restart_optmgmt
27275 			 * will drop the conn ref. In the case of ipsec option
27276 			 * after the ipsec load is complete
27277 			 * conn_restart_ipsec_waiter drops the conn ref.
27278 			 */
27279 			CONN_INC_REF(connp);
27280 			if (ip_check_for_ipsec_opt(q, mp))
27281 				return;
27282 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27283 			if (err != EINPROGRESS) {
27284 				/* Operation is done */
27285 				CONN_OPER_PENDING_DONE(connp);
27286 			}
27287 			return;
27288 		case T_UNBIND_REQ:
27289 			if (connp == NULL) {
27290 				proto_str = "T_UNBIND_REQ";
27291 				goto protonak;
27292 			}
27293 			ip_unbind(Q_TO_CONN(q));
27294 			mp = mi_tpi_ok_ack_alloc(mp);
27295 			qreply(q, mp);
27296 			return;
27297 		default:
27298 			/*
27299 			 * Have to drop any DLPI messages coming down from
27300 			 * arp (such as an info_req which would cause ip
27301 			 * to receive an extra info_ack if it was passed
27302 			 * through.
27303 			 */
27304 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27305 			    (int)*(uint_t *)mp->b_rptr));
27306 			freemsg(mp);
27307 			return;
27308 		}
27309 		/* NOTREACHED */
27310 	case IRE_DB_TYPE: {
27311 		nce_t		*nce;
27312 		ill_t		*ill;
27313 		in6_addr_t	gw_addr_v6;
27314 
27315 		/*
27316 		 * This is a response back from a resolver.  It
27317 		 * consists of a message chain containing:
27318 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27319 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27320 		 * The LL_HDR_MBLK is the DLPI header to use to get
27321 		 * the attached packet, and subsequent ones for the
27322 		 * same destination, transmitted.
27323 		 */
27324 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27325 			break;
27326 		/*
27327 		 * First, check to make sure the resolution succeeded.
27328 		 * If it failed, the second mblk will be empty.
27329 		 * If it is, free the chain, dropping the packet.
27330 		 * (We must ire_delete the ire; that frees the ire mblk)
27331 		 * We're doing this now to support PVCs for ATM; it's
27332 		 * a partial xresolv implementation. When we fully implement
27333 		 * xresolv interfaces, instead of freeing everything here
27334 		 * we'll initiate neighbor discovery.
27335 		 *
27336 		 * For v4 (ARP and other external resolvers) the resolver
27337 		 * frees the message, so no check is needed. This check
27338 		 * is required, though, for a full xresolve implementation.
27339 		 * Including this code here now both shows how external
27340 		 * resolvers can NACK a resolution request using an
27341 		 * existing design that has no specific provisions for NACKs,
27342 		 * and also takes into account that the current non-ARP
27343 		 * external resolver has been coded to use this method of
27344 		 * NACKing for all IPv6 (xresolv) cases,
27345 		 * whether our xresolv implementation is complete or not.
27346 		 *
27347 		 */
27348 		ire = (ire_t *)mp->b_rptr;
27349 		ill = ire_to_ill(ire);
27350 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27351 		if (mp1->b_rptr == mp1->b_wptr) {
27352 			if (ire->ire_ipversion == IPV6_VERSION) {
27353 				/*
27354 				 * XRESOLV interface.
27355 				 */
27356 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27357 				mutex_enter(&ire->ire_lock);
27358 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27359 				mutex_exit(&ire->ire_lock);
27360 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27361 					nce = ndp_lookup_v6(ill, B_FALSE,
27362 					    &ire->ire_addr_v6, B_FALSE);
27363 				} else {
27364 					nce = ndp_lookup_v6(ill, B_FALSE,
27365 					    &gw_addr_v6, B_FALSE);
27366 				}
27367 				if (nce != NULL) {
27368 					nce_resolv_failed(nce);
27369 					ndp_delete(nce);
27370 					NCE_REFRELE(nce);
27371 				}
27372 			}
27373 			mp->b_cont = NULL;
27374 			freemsg(mp1);		/* frees the pkt as well */
27375 			ASSERT(ire->ire_nce == NULL);
27376 			ire_delete((ire_t *)mp->b_rptr);
27377 			return;
27378 		}
27379 
27380 		/*
27381 		 * Split them into IRE_MBLK and pkt and feed it into
27382 		 * ire_add_then_send. Then in ire_add_then_send
27383 		 * the IRE will be added, and then the packet will be
27384 		 * run back through ip_wput. This time it will make
27385 		 * it to the wire.
27386 		 */
27387 		mp->b_cont = NULL;
27388 		mp = mp1->b_cont;		/* now, mp points to pkt */
27389 		mp1->b_cont = NULL;
27390 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27391 		if (ire->ire_ipversion == IPV6_VERSION) {
27392 			/*
27393 			 * XRESOLV interface. Find the nce and put a copy
27394 			 * of the dl_unitdata_req in nce_res_mp
27395 			 */
27396 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27397 			mutex_enter(&ire->ire_lock);
27398 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27399 			mutex_exit(&ire->ire_lock);
27400 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27401 				nce = ndp_lookup_v6(ill, B_FALSE,
27402 				    &ire->ire_addr_v6, B_FALSE);
27403 			} else {
27404 				nce = ndp_lookup_v6(ill, B_FALSE,
27405 				    &gw_addr_v6, B_FALSE);
27406 			}
27407 			if (nce != NULL) {
27408 				/*
27409 				 * We have to protect nce_res_mp here
27410 				 * from being accessed by other threads
27411 				 * while we change the mblk pointer.
27412 				 * Other functions will also lock the nce when
27413 				 * accessing nce_res_mp.
27414 				 *
27415 				 * The reason we change the mblk pointer
27416 				 * here rather than copying the resolved address
27417 				 * into the template is that, unlike with
27418 				 * ethernet, we have no guarantee that the
27419 				 * resolved address length will be
27420 				 * smaller than or equal to the lla length
27421 				 * with which the template was allocated,
27422 				 * (for ethernet, they're equal)
27423 				 * so we have to use the actual resolved
27424 				 * address mblk - which holds the real
27425 				 * dl_unitdata_req with the resolved address.
27426 				 *
27427 				 * Doing this is the same behavior as was
27428 				 * previously used in the v4 ARP case.
27429 				 */
27430 				mutex_enter(&nce->nce_lock);
27431 				if (nce->nce_res_mp != NULL)
27432 					freemsg(nce->nce_res_mp);
27433 				nce->nce_res_mp = mp1;
27434 				mutex_exit(&nce->nce_lock);
27435 				/*
27436 				 * We do a fastpath probe here because
27437 				 * we have resolved the address without
27438 				 * using Neighbor Discovery.
27439 				 * In the non-XRESOLV v6 case, the fastpath
27440 				 * probe is done right after neighbor
27441 				 * discovery completes.
27442 				 */
27443 				if (nce->nce_res_mp != NULL) {
27444 					int res;
27445 					nce_fastpath_list_add(nce);
27446 					res = ill_fastpath_probe(ill,
27447 					    nce->nce_res_mp);
27448 					if (res != 0 && res != EAGAIN)
27449 						nce_fastpath_list_delete(nce);
27450 				}
27451 
27452 				ire_add_then_send(q, ire, mp);
27453 				/*
27454 				 * Now we have to clean out any packets
27455 				 * that may have been queued on the nce
27456 				 * while it was waiting for address resolution
27457 				 * to complete.
27458 				 */
27459 				mutex_enter(&nce->nce_lock);
27460 				mp1 = nce->nce_qd_mp;
27461 				nce->nce_qd_mp = NULL;
27462 				mutex_exit(&nce->nce_lock);
27463 				while (mp1 != NULL) {
27464 					mblk_t *nxt_mp;
27465 					queue_t *fwdq = NULL;
27466 					ill_t   *inbound_ill;
27467 					uint_t ifindex;
27468 
27469 					nxt_mp = mp1->b_next;
27470 					mp1->b_next = NULL;
27471 					/*
27472 					 * Retrieve ifindex stored in
27473 					 * ip_rput_data_v6()
27474 					 */
27475 					ifindex =
27476 					    (uint_t)(uintptr_t)mp1->b_prev;
27477 					inbound_ill =
27478 					    ill_lookup_on_ifindex(ifindex,
27479 					    B_TRUE, NULL, NULL, NULL,
27480 					    NULL, ipst);
27481 					mp1->b_prev = NULL;
27482 					if (inbound_ill != NULL)
27483 						fwdq = inbound_ill->ill_rq;
27484 
27485 					if (fwdq != NULL) {
27486 						put(fwdq, mp1);
27487 						ill_refrele(inbound_ill);
27488 					} else
27489 						put(WR(ill->ill_rq), mp1);
27490 					mp1 = nxt_mp;
27491 				}
27492 				NCE_REFRELE(nce);
27493 			} else {	/* nce is NULL; clean up */
27494 				ire_delete(ire);
27495 				freemsg(mp);
27496 				freemsg(mp1);
27497 				return;
27498 			}
27499 		} else {
27500 			nce_t *arpce;
27501 			/*
27502 			 * Link layer resolution succeeded. Recompute the
27503 			 * ire_nce.
27504 			 */
27505 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27506 			if ((arpce = ndp_lookup_v4(ill,
27507 			    (ire->ire_gateway_addr != INADDR_ANY ?
27508 			    &ire->ire_gateway_addr : &ire->ire_addr),
27509 			    B_FALSE)) == NULL) {
27510 				freeb(ire->ire_mp);
27511 				freeb(mp1);
27512 				freemsg(mp);
27513 				return;
27514 			}
27515 			mutex_enter(&arpce->nce_lock);
27516 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27517 			if (arpce->nce_state == ND_REACHABLE) {
27518 				/*
27519 				 * Someone resolved this before us;
27520 				 * cleanup the res_mp. Since ire has
27521 				 * not been added yet, the call to ire_add_v4
27522 				 * from ire_add_then_send (when a dup is
27523 				 * detected) will clean up the ire.
27524 				 */
27525 				freeb(mp1);
27526 			} else {
27527 				ASSERT(arpce->nce_res_mp == NULL);
27528 				arpce->nce_res_mp = mp1;
27529 				arpce->nce_state = ND_REACHABLE;
27530 			}
27531 			mutex_exit(&arpce->nce_lock);
27532 			if (ire->ire_marks & IRE_MARK_NOADD) {
27533 				/*
27534 				 * this ire will not be added to the ire
27535 				 * cache table, so we can set the ire_nce
27536 				 * here, as there are no atomicity constraints.
27537 				 */
27538 				ire->ire_nce = arpce;
27539 				/*
27540 				 * We are associating this nce with the ire
27541 				 * so change the nce ref taken in
27542 				 * ndp_lookup_v4() from
27543 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27544 				 */
27545 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27546 			} else {
27547 				NCE_REFRELE(arpce);
27548 			}
27549 			ire_add_then_send(q, ire, mp);
27550 		}
27551 		return;	/* All is well, the packet has been sent. */
27552 	}
27553 	case IRE_ARPRESOLVE_TYPE: {
27554 
27555 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27556 			break;
27557 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27558 		mp->b_cont = NULL;
27559 		/*
27560 		 * First, check to make sure the resolution succeeded.
27561 		 * If it failed, the second mblk will be empty.
27562 		 */
27563 		if (mp1->b_rptr == mp1->b_wptr) {
27564 			/* cleanup  the incomplete ire, free queued packets */
27565 			freemsg(mp); /* fake ire */
27566 			freeb(mp1);  /* dl_unitdata response */
27567 			return;
27568 		}
27569 
27570 		/*
27571 		 * Update any incomplete nce_t found. We search the ctable
27572 		 * and find the nce from the ire->ire_nce because we need
27573 		 * to pass the ire to ip_xmit_v4 later, and can find both
27574 		 * ire and nce in one lookup.
27575 		 */
27576 		fake_ire = (ire_t *)mp->b_rptr;
27577 
27578 		/*
27579 		 * By the time we come back here from ARP the logical outgoing
27580 		 * interface of the incomplete ire we added in ire_forward()
27581 		 * could have disappeared, causing the incomplete ire to also
27582 		 * disappear.  So we need to retreive the proper ipif for the
27583 		 * ire before looking in ctable.  In the case of IPMP, the
27584 		 * ipif may be on the IPMP ill, so look it up based on the
27585 		 * ire_ipif_ifindex we stashed back in ire_init_common().
27586 		 * Then, we can verify that ire_ipif_seqid still exists.
27587 		 */
27588 		ill = ill_lookup_on_ifindex(fake_ire->ire_ipif_ifindex, B_FALSE,
27589 		    NULL, NULL, NULL, NULL, ipst);
27590 		if (ill == NULL) {
27591 			ip1dbg(("ill for incomplete ire vanished\n"));
27592 			freemsg(mp); /* fake ire */
27593 			freeb(mp1);  /* dl_unitdata response */
27594 			return;
27595 		}
27596 
27597 		/* Get the outgoing ipif */
27598 		mutex_enter(&ill->ill_lock);
27599 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27600 		if (ipif == NULL) {
27601 			mutex_exit(&ill->ill_lock);
27602 			ill_refrele(ill);
27603 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27604 			freemsg(mp); /* fake_ire */
27605 			freeb(mp1);  /* dl_unitdata response */
27606 			return;
27607 		}
27608 
27609 		ipif_refhold_locked(ipif);
27610 		mutex_exit(&ill->ill_lock);
27611 		ill_refrele(ill);
27612 		ire = ire_arpresolve_lookup(fake_ire->ire_addr,
27613 		    fake_ire->ire_gateway_addr, ipif, fake_ire->ire_zoneid,
27614 		    ipst, ((ill_t *)q->q_ptr)->ill_wq);
27615 		ipif_refrele(ipif);
27616 		if (ire == NULL) {
27617 			/*
27618 			 * no ire was found; check if there is an nce
27619 			 * for this lookup; if it has no ire's pointing at it
27620 			 * cleanup.
27621 			 */
27622 			if ((nce = ndp_lookup_v4(q->q_ptr,
27623 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27624 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27625 			    B_FALSE)) != NULL) {
27626 				/*
27627 				 * cleanup:
27628 				 * We check for refcnt 2 (one for the nce
27629 				 * hash list + 1 for the ref taken by
27630 				 * ndp_lookup_v4) to check that there are
27631 				 * no ire's pointing at the nce.
27632 				 */
27633 				if (nce->nce_refcnt == 2)
27634 					ndp_delete(nce);
27635 				NCE_REFRELE(nce);
27636 			}
27637 			freeb(mp1);  /* dl_unitdata response */
27638 			freemsg(mp); /* fake ire */
27639 			return;
27640 		}
27641 
27642 		nce = ire->ire_nce;
27643 		DTRACE_PROBE2(ire__arpresolve__type,
27644 		    ire_t *, ire, nce_t *, nce);
27645 		ASSERT(nce->nce_state != ND_INITIAL);
27646 		mutex_enter(&nce->nce_lock);
27647 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27648 		if (nce->nce_state == ND_REACHABLE) {
27649 			/*
27650 			 * Someone resolved this before us;
27651 			 * our response is not needed any more.
27652 			 */
27653 			mutex_exit(&nce->nce_lock);
27654 			freeb(mp1);  /* dl_unitdata response */
27655 		} else {
27656 			ASSERT(nce->nce_res_mp == NULL);
27657 			nce->nce_res_mp = mp1;
27658 			nce->nce_state = ND_REACHABLE;
27659 			mutex_exit(&nce->nce_lock);
27660 			nce_fastpath(nce);
27661 		}
27662 		/*
27663 		 * The cached nce_t has been updated to be reachable;
27664 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27665 		 */
27666 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27667 		freemsg(mp);
27668 		/*
27669 		 * send out queued packets.
27670 		 */
27671 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
27672 
27673 		IRE_REFRELE(ire);
27674 		return;
27675 	}
27676 	default:
27677 		break;
27678 	}
27679 	if (q->q_next) {
27680 		putnext(q, mp);
27681 	} else
27682 		freemsg(mp);
27683 	return;
27684 
27685 protonak:
27686 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27687 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27688 		qreply(q, mp);
27689 }
27690 
27691 /*
27692  * Process IP options in an outbound packet.  Modify the destination if there
27693  * is a source route option.
27694  * Returns non-zero if something fails in which case an ICMP error has been
27695  * sent and mp freed.
27696  */
27697 static int
27698 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27699     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27700 {
27701 	ipoptp_t	opts;
27702 	uchar_t		*opt;
27703 	uint8_t		optval;
27704 	uint8_t		optlen;
27705 	ipaddr_t	dst;
27706 	intptr_t	code = 0;
27707 	mblk_t		*mp;
27708 	ire_t		*ire = NULL;
27709 
27710 	ip2dbg(("ip_wput_options\n"));
27711 	mp = ipsec_mp;
27712 	if (mctl_present) {
27713 		mp = ipsec_mp->b_cont;
27714 	}
27715 
27716 	dst = ipha->ipha_dst;
27717 	for (optval = ipoptp_first(&opts, ipha);
27718 	    optval != IPOPT_EOL;
27719 	    optval = ipoptp_next(&opts)) {
27720 		opt = opts.ipoptp_cur;
27721 		optlen = opts.ipoptp_len;
27722 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27723 		    optval, optlen));
27724 		switch (optval) {
27725 			uint32_t off;
27726 		case IPOPT_SSRR:
27727 		case IPOPT_LSRR:
27728 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27729 				ip1dbg((
27730 				    "ip_wput_options: bad option offset\n"));
27731 				code = (char *)&opt[IPOPT_OLEN] -
27732 				    (char *)ipha;
27733 				goto param_prob;
27734 			}
27735 			off = opt[IPOPT_OFFSET];
27736 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27737 			    ntohl(dst)));
27738 			/*
27739 			 * For strict: verify that dst is directly
27740 			 * reachable.
27741 			 */
27742 			if (optval == IPOPT_SSRR) {
27743 				ire = ire_ftable_lookup(dst, 0, 0,
27744 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27745 				    MBLK_GETLABEL(mp),
27746 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27747 				if (ire == NULL) {
27748 					ip1dbg(("ip_wput_options: SSRR not"
27749 					    " directly reachable: 0x%x\n",
27750 					    ntohl(dst)));
27751 					goto bad_src_route;
27752 				}
27753 				ire_refrele(ire);
27754 			}
27755 			break;
27756 		case IPOPT_RR:
27757 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27758 				ip1dbg((
27759 				    "ip_wput_options: bad option offset\n"));
27760 				code = (char *)&opt[IPOPT_OLEN] -
27761 				    (char *)ipha;
27762 				goto param_prob;
27763 			}
27764 			break;
27765 		case IPOPT_TS:
27766 			/*
27767 			 * Verify that length >=5 and that there is either
27768 			 * room for another timestamp or that the overflow
27769 			 * counter is not maxed out.
27770 			 */
27771 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27772 			if (optlen < IPOPT_MINLEN_IT) {
27773 				goto param_prob;
27774 			}
27775 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27776 				ip1dbg((
27777 				    "ip_wput_options: bad option offset\n"));
27778 				code = (char *)&opt[IPOPT_OFFSET] -
27779 				    (char *)ipha;
27780 				goto param_prob;
27781 			}
27782 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27783 			case IPOPT_TS_TSONLY:
27784 				off = IPOPT_TS_TIMELEN;
27785 				break;
27786 			case IPOPT_TS_TSANDADDR:
27787 			case IPOPT_TS_PRESPEC:
27788 			case IPOPT_TS_PRESPEC_RFC791:
27789 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27790 				break;
27791 			default:
27792 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27793 				    (char *)ipha;
27794 				goto param_prob;
27795 			}
27796 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27797 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27798 				/*
27799 				 * No room and the overflow counter is 15
27800 				 * already.
27801 				 */
27802 				goto param_prob;
27803 			}
27804 			break;
27805 		}
27806 	}
27807 
27808 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27809 		return (0);
27810 
27811 	ip1dbg(("ip_wput_options: error processing IP options."));
27812 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27813 
27814 param_prob:
27815 	/*
27816 	 * Since ip_wput() isn't close to finished, we fill
27817 	 * in enough of the header for credible error reporting.
27818 	 */
27819 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27820 		/* Failed */
27821 		freemsg(ipsec_mp);
27822 		return (-1);
27823 	}
27824 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
27825 	return (-1);
27826 
27827 bad_src_route:
27828 	/*
27829 	 * Since ip_wput() isn't close to finished, we fill
27830 	 * in enough of the header for credible error reporting.
27831 	 */
27832 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27833 		/* Failed */
27834 		freemsg(ipsec_mp);
27835 		return (-1);
27836 	}
27837 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
27838 	return (-1);
27839 }
27840 
27841 /*
27842  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
27843  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
27844  * thru /etc/system.
27845  */
27846 #define	CONN_MAXDRAINCNT	64
27847 
27848 static void
27849 conn_drain_init(ip_stack_t *ipst)
27850 {
27851 	int i;
27852 
27853 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
27854 
27855 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
27856 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
27857 		/*
27858 		 * Default value of the number of drainers is the
27859 		 * number of cpus, subject to maximum of 8 drainers.
27860 		 */
27861 		if (boot_max_ncpus != -1)
27862 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
27863 		else
27864 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
27865 	}
27866 
27867 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
27868 	    sizeof (idl_t), KM_SLEEP);
27869 
27870 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
27871 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
27872 		    MUTEX_DEFAULT, NULL);
27873 	}
27874 }
27875 
27876 static void
27877 conn_drain_fini(ip_stack_t *ipst)
27878 {
27879 	int i;
27880 
27881 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
27882 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
27883 	kmem_free(ipst->ips_conn_drain_list,
27884 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
27885 	ipst->ips_conn_drain_list = NULL;
27886 }
27887 
27888 /*
27889  * Note: For an overview of how flowcontrol is handled in IP please see the
27890  * IP Flowcontrol notes at the top of this file.
27891  *
27892  * Flow control has blocked us from proceeding. Insert the given conn in one
27893  * of the conn drain lists. These conn wq's will be qenabled later on when
27894  * STREAMS flow control does a backenable. conn_walk_drain will enable
27895  * the first conn in each of these drain lists. Each of these qenabled conns
27896  * in turn enables the next in the list, after it runs, or when it closes,
27897  * thus sustaining the drain process.
27898  *
27899  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
27900  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
27901  * running at any time, on a given conn, since there can be only 1 service proc
27902  * running on a queue at any time.
27903  */
27904 void
27905 conn_drain_insert(conn_t *connp)
27906 {
27907 	idl_t	*idl;
27908 	uint_t	index;
27909 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
27910 
27911 	mutex_enter(&connp->conn_lock);
27912 	if (connp->conn_state_flags & CONN_CLOSING) {
27913 		/*
27914 		 * The conn is closing as a result of which CONN_CLOSING
27915 		 * is set. Return.
27916 		 */
27917 		mutex_exit(&connp->conn_lock);
27918 		return;
27919 	} else if (connp->conn_idl == NULL) {
27920 		/*
27921 		 * Assign the next drain list round robin. We dont' use
27922 		 * a lock, and thus it may not be strictly round robin.
27923 		 * Atomicity of load/stores is enough to make sure that
27924 		 * conn_drain_list_index is always within bounds.
27925 		 */
27926 		index = ipst->ips_conn_drain_list_index;
27927 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
27928 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
27929 		index++;
27930 		if (index == ipst->ips_conn_drain_list_cnt)
27931 			index = 0;
27932 		ipst->ips_conn_drain_list_index = index;
27933 	}
27934 	mutex_exit(&connp->conn_lock);
27935 
27936 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27937 	if ((connp->conn_drain_prev != NULL) ||
27938 	    (connp->conn_state_flags & CONN_CLOSING)) {
27939 		/*
27940 		 * The conn is already in the drain list, OR
27941 		 * the conn is closing. We need to check again for
27942 		 * the closing case again since close can happen
27943 		 * after we drop the conn_lock, and before we
27944 		 * acquire the CONN_DRAIN_LIST_LOCK.
27945 		 */
27946 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27947 		return;
27948 	} else {
27949 		idl = connp->conn_idl;
27950 	}
27951 
27952 	/*
27953 	 * The conn is not in the drain list. Insert it at the
27954 	 * tail of the drain list. The drain list is circular
27955 	 * and doubly linked. idl_conn points to the 1st element
27956 	 * in the list.
27957 	 */
27958 	if (idl->idl_conn == NULL) {
27959 		idl->idl_conn = connp;
27960 		connp->conn_drain_next = connp;
27961 		connp->conn_drain_prev = connp;
27962 	} else {
27963 		conn_t *head = idl->idl_conn;
27964 
27965 		connp->conn_drain_next = head;
27966 		connp->conn_drain_prev = head->conn_drain_prev;
27967 		head->conn_drain_prev->conn_drain_next = connp;
27968 		head->conn_drain_prev = connp;
27969 	}
27970 	/*
27971 	 * For non streams based sockets assert flow control.
27972 	 */
27973 	if (IPCL_IS_NONSTR(connp)) {
27974 		(*connp->conn_upcalls->su_txq_full)
27975 		    (connp->conn_upper_handle, B_TRUE);
27976 	}
27977 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27978 }
27979 
27980 /*
27981  * This conn is closing, and we are called from ip_close. OR
27982  * This conn has been serviced by ip_wsrv, and we need to do the tail
27983  * processing.
27984  * If this conn is part of the drain list, we may need to sustain the drain
27985  * process by qenabling the next conn in the drain list. We may also need to
27986  * remove this conn from the list, if it is done.
27987  */
27988 static void
27989 conn_drain_tail(conn_t *connp, boolean_t closing)
27990 {
27991 	idl_t *idl;
27992 
27993 	/*
27994 	 * connp->conn_idl is stable at this point, and no lock is needed
27995 	 * to check it. If we are called from ip_close, close has already
27996 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
27997 	 * called us only because conn_idl is non-null. If we are called thru
27998 	 * service, conn_idl could be null, but it cannot change because
27999 	 * service is single-threaded per queue, and there cannot be another
28000 	 * instance of service trying to call conn_drain_insert on this conn
28001 	 * now.
28002 	 */
28003 	ASSERT(!closing || (connp->conn_idl != NULL));
28004 
28005 	/*
28006 	 * If connp->conn_idl is null, the conn has not been inserted into any
28007 	 * drain list even once since creation of the conn. Just return.
28008 	 */
28009 	if (connp->conn_idl == NULL)
28010 		return;
28011 
28012 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28013 
28014 	if (connp->conn_drain_prev == NULL) {
28015 		/* This conn is currently not in the drain list.  */
28016 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28017 		return;
28018 	}
28019 	idl = connp->conn_idl;
28020 	if (idl->idl_conn_draining == connp) {
28021 		/*
28022 		 * This conn is the current drainer. If this is the last conn
28023 		 * in the drain list, we need to do more checks, in the 'if'
28024 		 * below. Otherwwise we need to just qenable the next conn,
28025 		 * to sustain the draining, and is handled in the 'else'
28026 		 * below.
28027 		 */
28028 		if (connp->conn_drain_next == idl->idl_conn) {
28029 			/*
28030 			 * This conn is the last in this list. This round
28031 			 * of draining is complete. If idl_repeat is set,
28032 			 * it means another flow enabling has happened from
28033 			 * the driver/streams and we need to another round
28034 			 * of draining.
28035 			 * If there are more than 2 conns in the drain list,
28036 			 * do a left rotate by 1, so that all conns except the
28037 			 * conn at the head move towards the head by 1, and the
28038 			 * the conn at the head goes to the tail. This attempts
28039 			 * a more even share for all queues that are being
28040 			 * drained.
28041 			 */
28042 			if ((connp->conn_drain_next != connp) &&
28043 			    (idl->idl_conn->conn_drain_next != connp)) {
28044 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28045 			}
28046 			if (idl->idl_repeat) {
28047 				qenable(idl->idl_conn->conn_wq);
28048 				idl->idl_conn_draining = idl->idl_conn;
28049 				idl->idl_repeat = 0;
28050 			} else {
28051 				idl->idl_conn_draining = NULL;
28052 			}
28053 		} else {
28054 			/*
28055 			 * If the next queue that we are now qenable'ing,
28056 			 * is closing, it will remove itself from this list
28057 			 * and qenable the subsequent queue in ip_close().
28058 			 * Serialization is acheived thru idl_lock.
28059 			 */
28060 			qenable(connp->conn_drain_next->conn_wq);
28061 			idl->idl_conn_draining = connp->conn_drain_next;
28062 		}
28063 	}
28064 	if (!connp->conn_did_putbq || closing) {
28065 		/*
28066 		 * Remove ourself from the drain list, if we did not do
28067 		 * a putbq, or if the conn is closing.
28068 		 * Note: It is possible that q->q_first is non-null. It means
28069 		 * that these messages landed after we did a enableok() in
28070 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28071 		 * service them.
28072 		 */
28073 		if (connp->conn_drain_next == connp) {
28074 			/* Singleton in the list */
28075 			ASSERT(connp->conn_drain_prev == connp);
28076 			idl->idl_conn = NULL;
28077 			idl->idl_conn_draining = NULL;
28078 		} else {
28079 			connp->conn_drain_prev->conn_drain_next =
28080 			    connp->conn_drain_next;
28081 			connp->conn_drain_next->conn_drain_prev =
28082 			    connp->conn_drain_prev;
28083 			if (idl->idl_conn == connp)
28084 				idl->idl_conn = connp->conn_drain_next;
28085 			ASSERT(idl->idl_conn_draining != connp);
28086 
28087 		}
28088 		connp->conn_drain_next = NULL;
28089 		connp->conn_drain_prev = NULL;
28090 
28091 		/*
28092 		 * For non streams based sockets open up flow control.
28093 		 */
28094 		if (IPCL_IS_NONSTR(connp)) {
28095 			(*connp->conn_upcalls->su_txq_full)
28096 			    (connp->conn_upper_handle, B_FALSE);
28097 		}
28098 	}
28099 
28100 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28101 }
28102 
28103 /*
28104  * Write service routine. Shared perimeter entry point.
28105  * ip_wsrv can be called in any of the following ways.
28106  * 1. The device queue's messages has fallen below the low water mark
28107  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28108  *    the drain lists and backenable the first conn in each list.
28109  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28110  *    qenabled non-tcp upper layers. We start dequeing messages and call
28111  *    ip_wput for each message.
28112  */
28113 
28114 void
28115 ip_wsrv(queue_t *q)
28116 {
28117 	conn_t	*connp;
28118 	ill_t	*ill;
28119 	mblk_t	*mp;
28120 
28121 	if (q->q_next) {
28122 		ill = (ill_t *)q->q_ptr;
28123 		if (ill->ill_state_flags == 0) {
28124 			/*
28125 			 * The device flow control has opened up.
28126 			 * Walk through conn drain lists and qenable the
28127 			 * first conn in each list. This makes sense only
28128 			 * if the stream is fully plumbed and setup.
28129 			 * Hence the if check above.
28130 			 */
28131 			ip1dbg(("ip_wsrv: walking\n"));
28132 			conn_walk_drain(ill->ill_ipst);
28133 		}
28134 		return;
28135 	}
28136 
28137 	connp = Q_TO_CONN(q);
28138 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28139 
28140 	/*
28141 	 * 1. Set conn_draining flag to signal that service is active.
28142 	 *
28143 	 * 2. ip_output determines whether it has been called from service,
28144 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28145 	 *    has been called from service.
28146 	 *
28147 	 * 3. Message ordering is preserved by the following logic.
28148 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28149 	 *    the message at the tail, if conn_draining is set (i.e. service
28150 	 *    is running) or if q->q_first is non-null.
28151 	 *
28152 	 *    ii. If ip_output is called from service, and if ip_output cannot
28153 	 *    putnext due to flow control, it does a putbq.
28154 	 *
28155 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28156 	 *    (causing an infinite loop).
28157 	 */
28158 	ASSERT(!connp->conn_did_putbq);
28159 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28160 		connp->conn_draining = 1;
28161 		noenable(q);
28162 		while ((mp = getq(q)) != NULL) {
28163 			ASSERT(CONN_Q(q));
28164 
28165 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28166 			if (connp->conn_did_putbq) {
28167 				/* ip_wput did a putbq */
28168 				break;
28169 			}
28170 		}
28171 		/*
28172 		 * At this point, a thread coming down from top, calling
28173 		 * ip_wput, may end up queueing the message. We have not yet
28174 		 * enabled the queue, so ip_wsrv won't be called again.
28175 		 * To avoid this race, check q->q_first again (in the loop)
28176 		 * If the other thread queued the message before we call
28177 		 * enableok(), we will catch it in the q->q_first check.
28178 		 * If the other thread queues the message after we call
28179 		 * enableok(), ip_wsrv will be called again by STREAMS.
28180 		 */
28181 		connp->conn_draining = 0;
28182 		enableok(q);
28183 
28184 	}
28185 
28186 	/* Enable the next conn for draining */
28187 	conn_drain_tail(connp, B_FALSE);
28188 
28189 	connp->conn_did_putbq = 0;
28190 }
28191 
28192 /*
28193  * Callback to disable flow control in IP.
28194  *
28195  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
28196  * is enabled.
28197  *
28198  * When MAC_TX() is not able to send any more packets, dld sets its queue
28199  * to QFULL and enable the STREAMS flow control. Later, when the underlying
28200  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
28201  * function and wakes up corresponding mac worker threads, which in turn
28202  * calls this callback function, and disables flow control.
28203  */
28204 /* ARGSUSED */
28205 void
28206 ill_flow_enable(void *ill, ip_mac_tx_cookie_t cookie)
28207 {
28208 	qenable(((ill_t *)ill)->ill_wq);
28209 }
28210 
28211 /*
28212  * Walk the list of all conn's calling the function provided with the
28213  * specified argument for each.	 Note that this only walks conn's that
28214  * have been bound.
28215  * Applies to both IPv4 and IPv6.
28216  */
28217 static void
28218 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28219 {
28220 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28221 	    ipst->ips_ipcl_udp_fanout_size,
28222 	    func, arg, zoneid);
28223 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28224 	    ipst->ips_ipcl_conn_fanout_size,
28225 	    func, arg, zoneid);
28226 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28227 	    ipst->ips_ipcl_bind_fanout_size,
28228 	    func, arg, zoneid);
28229 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28230 	    IPPROTO_MAX, func, arg, zoneid);
28231 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28232 	    IPPROTO_MAX, func, arg, zoneid);
28233 }
28234 
28235 /*
28236  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28237  * of conns that need to be drained, check if drain is already in progress.
28238  * If so set the idl_repeat bit, indicating that the last conn in the list
28239  * needs to reinitiate the drain once again, for the list. If drain is not
28240  * in progress for the list, initiate the draining, by qenabling the 1st
28241  * conn in the list. The drain is self-sustaining, each qenabled conn will
28242  * in turn qenable the next conn, when it is done/blocked/closing.
28243  */
28244 static void
28245 conn_walk_drain(ip_stack_t *ipst)
28246 {
28247 	int i;
28248 	idl_t *idl;
28249 
28250 	IP_STAT(ipst, ip_conn_walk_drain);
28251 
28252 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28253 		idl = &ipst->ips_conn_drain_list[i];
28254 		mutex_enter(&idl->idl_lock);
28255 		if (idl->idl_conn == NULL) {
28256 			mutex_exit(&idl->idl_lock);
28257 			continue;
28258 		}
28259 		/*
28260 		 * If this list is not being drained currently by
28261 		 * an ip_wsrv thread, start the process.
28262 		 */
28263 		if (idl->idl_conn_draining == NULL) {
28264 			ASSERT(idl->idl_repeat == 0);
28265 			qenable(idl->idl_conn->conn_wq);
28266 			idl->idl_conn_draining = idl->idl_conn;
28267 		} else {
28268 			idl->idl_repeat = 1;
28269 		}
28270 		mutex_exit(&idl->idl_lock);
28271 	}
28272 }
28273 
28274 /*
28275  * Walk an conn hash table of `count' buckets, calling func for each entry.
28276  */
28277 static void
28278 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28279     zoneid_t zoneid)
28280 {
28281 	conn_t	*connp;
28282 
28283 	while (count-- > 0) {
28284 		mutex_enter(&connfp->connf_lock);
28285 		for (connp = connfp->connf_head; connp != NULL;
28286 		    connp = connp->conn_next) {
28287 			if (zoneid == GLOBAL_ZONEID ||
28288 			    zoneid == connp->conn_zoneid) {
28289 				CONN_INC_REF(connp);
28290 				mutex_exit(&connfp->connf_lock);
28291 				(*func)(connp, arg);
28292 				mutex_enter(&connfp->connf_lock);
28293 				CONN_DEC_REF(connp);
28294 			}
28295 		}
28296 		mutex_exit(&connfp->connf_lock);
28297 		connfp++;
28298 	}
28299 }
28300 
28301 /* conn_walk_fanout routine invoked for ip_conn_report for each conn. */
28302 static void
28303 conn_report1(conn_t *connp, void *mp)
28304 {
28305 	char	buf1[INET6_ADDRSTRLEN];
28306 	char	buf2[INET6_ADDRSTRLEN];
28307 	uint_t	print_len, buf_len;
28308 
28309 	ASSERT(connp != NULL);
28310 
28311 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28312 	if (buf_len <= 0)
28313 		return;
28314 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28315 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28316 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28317 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28318 	    "%5d %s/%05d %s/%05d\n",
28319 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28320 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28321 	    buf1, connp->conn_lport,
28322 	    buf2, connp->conn_fport);
28323 	if (print_len < buf_len) {
28324 		((mblk_t *)mp)->b_wptr += print_len;
28325 	} else {
28326 		((mblk_t *)mp)->b_wptr += buf_len;
28327 	}
28328 }
28329 
28330 /*
28331  * Named Dispatch routine to produce a formatted report on all conns
28332  * that are listed in one of the fanout tables.
28333  * This report is accessed by using the ndd utility to "get" ND variable
28334  * "ip_conn_status".
28335  */
28336 /* ARGSUSED */
28337 static int
28338 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28339 {
28340 	conn_t *connp = Q_TO_CONN(q);
28341 
28342 	(void) mi_mpprintf(mp,
28343 	    "CONN      " MI_COL_HDRPAD_STR
28344 	    "rfq      " MI_COL_HDRPAD_STR
28345 	    "stq      " MI_COL_HDRPAD_STR
28346 	    " zone local		 remote");
28347 
28348 	/*
28349 	 * Because of the ndd constraint, at most we can have 64K buffer
28350 	 * to put in all conn info.  So to be more efficient, just
28351 	 * allocate a 64K buffer here, assuming we need that large buffer.
28352 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28353 	 */
28354 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28355 		/* The following may work even if we cannot get a large buf. */
28356 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28357 		return (0);
28358 	}
28359 
28360 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28361 	    connp->conn_netstack->netstack_ip);
28362 	return (0);
28363 }
28364 
28365 /*
28366  * Determine if the ill and multicast aspects of that packets
28367  * "matches" the conn.
28368  */
28369 boolean_t
28370 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28371     zoneid_t zoneid)
28372 {
28373 	ill_t *bound_ill;
28374 	boolean_t found;
28375 	ipif_t *ipif;
28376 	ire_t *ire;
28377 	ipaddr_t dst, src;
28378 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28379 
28380 	dst = ipha->ipha_dst;
28381 	src = ipha->ipha_src;
28382 
28383 	/*
28384 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28385 	 * unicast, broadcast and multicast reception to
28386 	 * conn_incoming_ill. conn_wantpacket itself is called
28387 	 * only for BROADCAST and multicast.
28388 	 */
28389 	bound_ill = connp->conn_incoming_ill;
28390 	if (bound_ill != NULL) {
28391 		if (IS_IPMP(bound_ill)) {
28392 			if (bound_ill->ill_grp != ill->ill_grp)
28393 				return (B_FALSE);
28394 		} else {
28395 			if (bound_ill != ill)
28396 				return (B_FALSE);
28397 		}
28398 	}
28399 
28400 	if (!CLASSD(dst)) {
28401 		if (IPCL_ZONE_MATCH(connp, zoneid))
28402 			return (B_TRUE);
28403 		/*
28404 		 * The conn is in a different zone; we need to check that this
28405 		 * broadcast address is configured in the application's zone.
28406 		 */
28407 		ipif = ipif_get_next_ipif(NULL, ill);
28408 		if (ipif == NULL)
28409 			return (B_FALSE);
28410 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28411 		    connp->conn_zoneid, NULL,
28412 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL), ipst);
28413 		ipif_refrele(ipif);
28414 		if (ire != NULL) {
28415 			ire_refrele(ire);
28416 			return (B_TRUE);
28417 		} else {
28418 			return (B_FALSE);
28419 		}
28420 	}
28421 
28422 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28423 	    connp->conn_zoneid == zoneid) {
28424 		/*
28425 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28426 		 * disabled, therefore we don't dispatch the multicast packet to
28427 		 * the sending zone.
28428 		 */
28429 		return (B_FALSE);
28430 	}
28431 
28432 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28433 		/*
28434 		 * Multicast packet on the loopback interface: we only match
28435 		 * conns who joined the group in the specified zone.
28436 		 */
28437 		return (B_FALSE);
28438 	}
28439 
28440 	if (connp->conn_multi_router) {
28441 		/* multicast packet and multicast router socket: send up */
28442 		return (B_TRUE);
28443 	}
28444 
28445 	mutex_enter(&connp->conn_lock);
28446 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28447 	mutex_exit(&connp->conn_lock);
28448 	return (found);
28449 }
28450 
28451 /*
28452  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28453  */
28454 /* ARGSUSED */
28455 static void
28456 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28457 {
28458 	ill_t *ill = (ill_t *)q->q_ptr;
28459 	mblk_t	*mp1, *mp2;
28460 	ipif_t  *ipif;
28461 	int err = 0;
28462 	conn_t *connp = NULL;
28463 	ipsq_t	*ipsq;
28464 	arc_t	*arc;
28465 
28466 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28467 
28468 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28469 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28470 
28471 	ASSERT(IAM_WRITER_ILL(ill));
28472 	mp2 = mp->b_cont;
28473 	mp->b_cont = NULL;
28474 
28475 	/*
28476 	 * We have now received the arp bringup completion message
28477 	 * from ARP. Mark the arp bringup as done. Also if the arp
28478 	 * stream has already started closing, send up the AR_ARP_CLOSING
28479 	 * ack now since ARP is waiting in close for this ack.
28480 	 */
28481 	mutex_enter(&ill->ill_lock);
28482 	ill->ill_arp_bringup_pending = 0;
28483 	if (ill->ill_arp_closing) {
28484 		mutex_exit(&ill->ill_lock);
28485 		/* Let's reuse the mp for sending the ack */
28486 		arc = (arc_t *)mp->b_rptr;
28487 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28488 		arc->arc_cmd = AR_ARP_CLOSING;
28489 		qreply(q, mp);
28490 	} else {
28491 		mutex_exit(&ill->ill_lock);
28492 		freeb(mp);
28493 	}
28494 
28495 	ipsq = ill->ill_phyint->phyint_ipsq;
28496 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
28497 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28498 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28499 	if (mp1 == NULL) {
28500 		/* bringup was aborted by the user */
28501 		freemsg(mp2);
28502 		return;
28503 	}
28504 
28505 	/*
28506 	 * If an IOCTL is waiting on this (ipx_current_ioctl != 0), then we
28507 	 * must have an associated conn_t.  Otherwise, we're bringing this
28508 	 * interface back up as part of handling an asynchronous event (e.g.,
28509 	 * physical address change).
28510 	 */
28511 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0) {
28512 		ASSERT(connp != NULL);
28513 		q = CONNP_TO_WQ(connp);
28514 	} else {
28515 		ASSERT(connp == NULL);
28516 		q = ill->ill_rq;
28517 	}
28518 
28519 	/*
28520 	 * If the DL_BIND_REQ fails, it is noted
28521 	 * in arc_name_offset.
28522 	 */
28523 	err = *((int *)mp2->b_rptr);
28524 	if (err == 0) {
28525 		if (ipif->ipif_isv6) {
28526 			if ((err = ipif_up_done_v6(ipif)) != 0)
28527 				ip0dbg(("ip_arp_done: init failed\n"));
28528 		} else {
28529 			if ((err = ipif_up_done(ipif)) != 0)
28530 				ip0dbg(("ip_arp_done: init failed\n"));
28531 		}
28532 	} else {
28533 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28534 	}
28535 
28536 	freemsg(mp2);
28537 
28538 	if ((err == 0) && (ill->ill_up_ipifs)) {
28539 		err = ill_up_ipifs(ill, q, mp1);
28540 		if (err == EINPROGRESS)
28541 			return;
28542 	}
28543 
28544 	/*
28545 	 * If we have a moved ipif to bring up, and everything has succeeded
28546 	 * to this point, bring it up on the IPMP ill.  Otherwise, leave it
28547 	 * down -- the admin can try to bring it up by hand if need be.
28548 	 */
28549 	if (ill->ill_move_ipif != NULL) {
28550 		ipif = ill->ill_move_ipif;
28551 		ill->ill_move_ipif = NULL;
28552 		if (err == 0) {
28553 			err = ipif_up(ipif, q, mp1);
28554 			if (err == EINPROGRESS)
28555 				return;
28556 		}
28557 	}
28558 
28559 	/*
28560 	 * The operation must complete without EINPROGRESS since
28561 	 * ipsq_pending_mp_get() has removed the mblk.  Otherwise, the
28562 	 * operation will be stuck forever in the ipsq.
28563 	 */
28564 	ASSERT(err != EINPROGRESS);
28565 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0)
28566 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28567 	else
28568 		ipsq_current_finish(ipsq);
28569 }
28570 
28571 /* Allocate the private structure */
28572 static int
28573 ip_priv_alloc(void **bufp)
28574 {
28575 	void	*buf;
28576 
28577 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28578 		return (ENOMEM);
28579 
28580 	*bufp = buf;
28581 	return (0);
28582 }
28583 
28584 /* Function to delete the private structure */
28585 void
28586 ip_priv_free(void *buf)
28587 {
28588 	ASSERT(buf != NULL);
28589 	kmem_free(buf, sizeof (ip_priv_t));
28590 }
28591 
28592 /*
28593  * The entry point for IPPF processing.
28594  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28595  * routine just returns.
28596  *
28597  * When called, ip_process generates an ipp_packet_t structure
28598  * which holds the state information for this packet and invokes the
28599  * the classifier (via ipp_packet_process). The classification, depending on
28600  * configured filters, results in a list of actions for this packet. Invoking
28601  * an action may cause the packet to be dropped, in which case the resulting
28602  * mblk (*mpp) is NULL. proc indicates the callout position for
28603  * this packet and ill_index is the interface this packet on or will leave
28604  * on (inbound and outbound resp.).
28605  */
28606 void
28607 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28608 {
28609 	mblk_t		*mp;
28610 	ip_priv_t	*priv;
28611 	ipp_action_id_t	aid;
28612 	int		rc = 0;
28613 	ipp_packet_t	*pp;
28614 #define	IP_CLASS	"ip"
28615 
28616 	/* If the classifier is not loaded, return  */
28617 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28618 		return;
28619 	}
28620 
28621 	mp = *mpp;
28622 	ASSERT(mp != NULL);
28623 
28624 	/* Allocate the packet structure */
28625 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28626 	if (rc != 0) {
28627 		*mpp = NULL;
28628 		freemsg(mp);
28629 		return;
28630 	}
28631 
28632 	/* Allocate the private structure */
28633 	rc = ip_priv_alloc((void **)&priv);
28634 	if (rc != 0) {
28635 		*mpp = NULL;
28636 		freemsg(mp);
28637 		ipp_packet_free(pp);
28638 		return;
28639 	}
28640 	priv->proc = proc;
28641 	priv->ill_index = ill_index;
28642 	ipp_packet_set_private(pp, priv, ip_priv_free);
28643 	ipp_packet_set_data(pp, mp);
28644 
28645 	/* Invoke the classifier */
28646 	rc = ipp_packet_process(&pp);
28647 	if (pp != NULL) {
28648 		mp = ipp_packet_get_data(pp);
28649 		ipp_packet_free(pp);
28650 		if (rc != 0) {
28651 			freemsg(mp);
28652 			*mpp = NULL;
28653 		}
28654 	} else {
28655 		*mpp = NULL;
28656 	}
28657 #undef	IP_CLASS
28658 }
28659 
28660 /*
28661  * Propagate a multicast group membership operation (add/drop) on
28662  * all the interfaces crossed by the related multirt routes.
28663  * The call is considered successful if the operation succeeds
28664  * on at least one interface.
28665  */
28666 static int
28667 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28668     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28669     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28670     mblk_t *first_mp)
28671 {
28672 	ire_t		*ire_gw;
28673 	irb_t		*irb;
28674 	int		error = 0;
28675 	opt_restart_t	*or;
28676 	ip_stack_t	*ipst = ire->ire_ipst;
28677 
28678 	irb = ire->ire_bucket;
28679 	ASSERT(irb != NULL);
28680 
28681 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28682 
28683 	or = (opt_restart_t *)first_mp->b_rptr;
28684 	IRB_REFHOLD(irb);
28685 	for (; ire != NULL; ire = ire->ire_next) {
28686 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28687 			continue;
28688 		if (ire->ire_addr != group)
28689 			continue;
28690 
28691 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28692 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28693 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28694 		/* No resolver exists for the gateway; skip this ire. */
28695 		if (ire_gw == NULL)
28696 			continue;
28697 
28698 		/*
28699 		 * This function can return EINPROGRESS. If so the operation
28700 		 * will be restarted from ip_restart_optmgmt which will
28701 		 * call ip_opt_set and option processing will restart for
28702 		 * this option. So we may end up calling 'fn' more than once.
28703 		 * This requires that 'fn' is idempotent except for the
28704 		 * return value. The operation is considered a success if
28705 		 * it succeeds at least once on any one interface.
28706 		 */
28707 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28708 		    NULL, fmode, src, first_mp);
28709 		if (error == 0)
28710 			or->or_private = CGTP_MCAST_SUCCESS;
28711 
28712 		if (ip_debug > 0) {
28713 			ulong_t	off;
28714 			char	*ksym;
28715 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28716 			ip2dbg(("ip_multirt_apply_membership: "
28717 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28718 			    "error %d [success %u]\n",
28719 			    ksym ? ksym : "?",
28720 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28721 			    error, or->or_private));
28722 		}
28723 
28724 		ire_refrele(ire_gw);
28725 		if (error == EINPROGRESS) {
28726 			IRB_REFRELE(irb);
28727 			return (error);
28728 		}
28729 	}
28730 	IRB_REFRELE(irb);
28731 	/*
28732 	 * Consider the call as successful if we succeeded on at least
28733 	 * one interface. Otherwise, return the last encountered error.
28734 	 */
28735 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28736 }
28737 
28738 /*
28739  * Issue a warning regarding a route crossing an interface with an
28740  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28741  * amount of time is logged.
28742  */
28743 static void
28744 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28745 {
28746 	hrtime_t	current = gethrtime();
28747 	char		buf[INET_ADDRSTRLEN];
28748 	ip_stack_t	*ipst = ire->ire_ipst;
28749 
28750 	/* Convert interval in ms to hrtime in ns */
28751 	if (ipst->ips_multirt_bad_mtu_last_time +
28752 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28753 	    current) {
28754 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28755 		    "to %s, incorrect MTU %u (expected %u)\n",
28756 		    ip_dot_addr(ire->ire_addr, buf),
28757 		    ire->ire_max_frag, max_frag);
28758 
28759 		ipst->ips_multirt_bad_mtu_last_time = current;
28760 	}
28761 }
28762 
28763 /*
28764  * Get the CGTP (multirouting) filtering status.
28765  * If 0, the CGTP hooks are transparent.
28766  */
28767 /* ARGSUSED */
28768 static int
28769 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28770 {
28771 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28772 
28773 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28774 	return (0);
28775 }
28776 
28777 /*
28778  * Set the CGTP (multirouting) filtering status.
28779  * If the status is changed from active to transparent
28780  * or from transparent to active, forward the new status
28781  * to the filtering module (if loaded).
28782  */
28783 /* ARGSUSED */
28784 static int
28785 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28786     cred_t *ioc_cr)
28787 {
28788 	long		new_value;
28789 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28790 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28791 
28792 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
28793 		return (EPERM);
28794 
28795 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28796 	    new_value < 0 || new_value > 1) {
28797 		return (EINVAL);
28798 	}
28799 
28800 	if ((!*ip_cgtp_filter_value) && new_value) {
28801 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28802 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28803 		    " (module not loaded)" : "");
28804 	}
28805 	if (*ip_cgtp_filter_value && (!new_value)) {
28806 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28807 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28808 		    " (module not loaded)" : "");
28809 	}
28810 
28811 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28812 		int	res;
28813 		netstackid_t stackid;
28814 
28815 		stackid = ipst->ips_netstack->netstack_stackid;
28816 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
28817 		    new_value);
28818 		if (res)
28819 			return (res);
28820 	}
28821 
28822 	*ip_cgtp_filter_value = (boolean_t)new_value;
28823 
28824 	return (0);
28825 }
28826 
28827 /*
28828  * Return the expected CGTP hooks version number.
28829  */
28830 int
28831 ip_cgtp_filter_supported(void)
28832 {
28833 	return (ip_cgtp_filter_rev);
28834 }
28835 
28836 /*
28837  * CGTP hooks can be registered by invoking this function.
28838  * Checks that the version number matches.
28839  */
28840 int
28841 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
28842 {
28843 	netstack_t *ns;
28844 	ip_stack_t *ipst;
28845 
28846 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28847 		return (ENOTSUP);
28848 
28849 	ns = netstack_find_by_stackid(stackid);
28850 	if (ns == NULL)
28851 		return (EINVAL);
28852 	ipst = ns->netstack_ip;
28853 	ASSERT(ipst != NULL);
28854 
28855 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28856 		netstack_rele(ns);
28857 		return (EALREADY);
28858 	}
28859 
28860 	ipst->ips_ip_cgtp_filter_ops = ops;
28861 	netstack_rele(ns);
28862 	return (0);
28863 }
28864 
28865 /*
28866  * CGTP hooks can be unregistered by invoking this function.
28867  * Returns ENXIO if there was no registration.
28868  * Returns EBUSY if the ndd variable has not been turned off.
28869  */
28870 int
28871 ip_cgtp_filter_unregister(netstackid_t stackid)
28872 {
28873 	netstack_t *ns;
28874 	ip_stack_t *ipst;
28875 
28876 	ns = netstack_find_by_stackid(stackid);
28877 	if (ns == NULL)
28878 		return (EINVAL);
28879 	ipst = ns->netstack_ip;
28880 	ASSERT(ipst != NULL);
28881 
28882 	if (ipst->ips_ip_cgtp_filter) {
28883 		netstack_rele(ns);
28884 		return (EBUSY);
28885 	}
28886 
28887 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
28888 		netstack_rele(ns);
28889 		return (ENXIO);
28890 	}
28891 	ipst->ips_ip_cgtp_filter_ops = NULL;
28892 	netstack_rele(ns);
28893 	return (0);
28894 }
28895 
28896 /*
28897  * Check whether there is a CGTP filter registration.
28898  * Returns non-zero if there is a registration, otherwise returns zero.
28899  * Note: returns zero if bad stackid.
28900  */
28901 int
28902 ip_cgtp_filter_is_registered(netstackid_t stackid)
28903 {
28904 	netstack_t *ns;
28905 	ip_stack_t *ipst;
28906 	int ret;
28907 
28908 	ns = netstack_find_by_stackid(stackid);
28909 	if (ns == NULL)
28910 		return (0);
28911 	ipst = ns->netstack_ip;
28912 	ASSERT(ipst != NULL);
28913 
28914 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
28915 		ret = 1;
28916 	else
28917 		ret = 0;
28918 
28919 	netstack_rele(ns);
28920 	return (ret);
28921 }
28922 
28923 static int
28924 ip_squeue_switch(int val)
28925 {
28926 	int rval = SQ_FILL;
28927 
28928 	switch (val) {
28929 	case IP_SQUEUE_ENTER_NODRAIN:
28930 		rval = SQ_NODRAIN;
28931 		break;
28932 	case IP_SQUEUE_ENTER:
28933 		rval = SQ_PROCESS;
28934 		break;
28935 	default:
28936 		break;
28937 	}
28938 	return (rval);
28939 }
28940 
28941 /* ARGSUSED */
28942 static int
28943 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
28944     caddr_t addr, cred_t *cr)
28945 {
28946 	int *v = (int *)addr;
28947 	long new_value;
28948 
28949 	if (secpolicy_net_config(cr, B_FALSE) != 0)
28950 		return (EPERM);
28951 
28952 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28953 		return (EINVAL);
28954 
28955 	ip_squeue_flag = ip_squeue_switch(new_value);
28956 	*v = new_value;
28957 	return (0);
28958 }
28959 
28960 /*
28961  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
28962  * ip_debug.
28963  */
28964 /* ARGSUSED */
28965 static int
28966 ip_int_set(queue_t *q, mblk_t *mp, char *value,
28967     caddr_t addr, cred_t *cr)
28968 {
28969 	int *v = (int *)addr;
28970 	long new_value;
28971 
28972 	if (secpolicy_net_config(cr, B_FALSE) != 0)
28973 		return (EPERM);
28974 
28975 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28976 		return (EINVAL);
28977 
28978 	*v = new_value;
28979 	return (0);
28980 }
28981 
28982 static void *
28983 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
28984 {
28985 	kstat_t *ksp;
28986 
28987 	ip_stat_t template = {
28988 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
28989 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
28990 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
28991 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
28992 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
28993 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
28994 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
28995 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
28996 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
28997 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
28998 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
28999 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29000 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29001 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29002 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29003 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29004 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29005 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29006 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29007 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29008 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29009 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29010 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29011 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29012 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29013 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29014 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29015 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29016 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29017 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29018 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29019 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29020 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29021 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29022 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29023 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29024 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29025 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29026 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29027 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29028 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29029 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29030 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29031 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29032 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29033 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29034 	};
29035 
29036 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29037 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29038 	    KSTAT_FLAG_VIRTUAL, stackid);
29039 
29040 	if (ksp == NULL)
29041 		return (NULL);
29042 
29043 	bcopy(&template, ip_statisticsp, sizeof (template));
29044 	ksp->ks_data = (void *)ip_statisticsp;
29045 	ksp->ks_private = (void *)(uintptr_t)stackid;
29046 
29047 	kstat_install(ksp);
29048 	return (ksp);
29049 }
29050 
29051 static void
29052 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29053 {
29054 	if (ksp != NULL) {
29055 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29056 		kstat_delete_netstack(ksp, stackid);
29057 	}
29058 }
29059 
29060 static void *
29061 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29062 {
29063 	kstat_t	*ksp;
29064 
29065 	ip_named_kstat_t template = {
29066 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29067 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29068 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29069 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29070 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29071 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29072 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29073 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29074 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29075 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29076 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29077 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29078 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29079 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29080 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29081 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29082 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29083 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29084 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29085 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29086 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29087 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29088 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29089 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29090 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29091 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29092 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29093 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29094 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29095 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29096 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29097 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29098 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29099 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29100 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29101 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29102 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29103 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29104 	};
29105 
29106 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29107 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29108 	if (ksp == NULL || ksp->ks_data == NULL)
29109 		return (NULL);
29110 
29111 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29112 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29113 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29114 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29115 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29116 
29117 	template.netToMediaEntrySize.value.i32 =
29118 	    sizeof (mib2_ipNetToMediaEntry_t);
29119 
29120 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29121 
29122 	bcopy(&template, ksp->ks_data, sizeof (template));
29123 	ksp->ks_update = ip_kstat_update;
29124 	ksp->ks_private = (void *)(uintptr_t)stackid;
29125 
29126 	kstat_install(ksp);
29127 	return (ksp);
29128 }
29129 
29130 static void
29131 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29132 {
29133 	if (ksp != NULL) {
29134 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29135 		kstat_delete_netstack(ksp, stackid);
29136 	}
29137 }
29138 
29139 static int
29140 ip_kstat_update(kstat_t *kp, int rw)
29141 {
29142 	ip_named_kstat_t *ipkp;
29143 	mib2_ipIfStatsEntry_t ipmib;
29144 	ill_walk_context_t ctx;
29145 	ill_t *ill;
29146 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29147 	netstack_t	*ns;
29148 	ip_stack_t	*ipst;
29149 
29150 	if (kp == NULL || kp->ks_data == NULL)
29151 		return (EIO);
29152 
29153 	if (rw == KSTAT_WRITE)
29154 		return (EACCES);
29155 
29156 	ns = netstack_find_by_stackid(stackid);
29157 	if (ns == NULL)
29158 		return (-1);
29159 	ipst = ns->netstack_ip;
29160 	if (ipst == NULL) {
29161 		netstack_rele(ns);
29162 		return (-1);
29163 	}
29164 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29165 
29166 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29167 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29168 	ill = ILL_START_WALK_V4(&ctx, ipst);
29169 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29170 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29171 	rw_exit(&ipst->ips_ill_g_lock);
29172 
29173 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29174 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29175 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29176 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29177 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29178 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29179 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29180 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29181 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29182 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29183 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29184 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29185 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29186 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29187 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29188 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29189 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29190 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29191 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29192 
29193 	ipkp->routingDiscards.value.ui32 =	0;
29194 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29195 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29196 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29197 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29198 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29199 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29200 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29201 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29202 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29203 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29204 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29205 
29206 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29207 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29208 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29209 
29210 	netstack_rele(ns);
29211 
29212 	return (0);
29213 }
29214 
29215 static void *
29216 icmp_kstat_init(netstackid_t stackid)
29217 {
29218 	kstat_t	*ksp;
29219 
29220 	icmp_named_kstat_t template = {
29221 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29222 		{ "inErrors",		KSTAT_DATA_UINT32 },
29223 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29224 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29225 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29226 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29227 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29228 		{ "inEchos",		KSTAT_DATA_UINT32 },
29229 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29230 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29231 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29232 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29233 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29234 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29235 		{ "outErrors",		KSTAT_DATA_UINT32 },
29236 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29237 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29238 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29239 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29240 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29241 		{ "outEchos",		KSTAT_DATA_UINT32 },
29242 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29243 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29244 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29245 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29246 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29247 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29248 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29249 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29250 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29251 		{ "outDrops",		KSTAT_DATA_UINT32 },
29252 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29253 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29254 	};
29255 
29256 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29257 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29258 	if (ksp == NULL || ksp->ks_data == NULL)
29259 		return (NULL);
29260 
29261 	bcopy(&template, ksp->ks_data, sizeof (template));
29262 
29263 	ksp->ks_update = icmp_kstat_update;
29264 	ksp->ks_private = (void *)(uintptr_t)stackid;
29265 
29266 	kstat_install(ksp);
29267 	return (ksp);
29268 }
29269 
29270 static void
29271 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29272 {
29273 	if (ksp != NULL) {
29274 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29275 		kstat_delete_netstack(ksp, stackid);
29276 	}
29277 }
29278 
29279 static int
29280 icmp_kstat_update(kstat_t *kp, int rw)
29281 {
29282 	icmp_named_kstat_t *icmpkp;
29283 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29284 	netstack_t	*ns;
29285 	ip_stack_t	*ipst;
29286 
29287 	if ((kp == NULL) || (kp->ks_data == NULL))
29288 		return (EIO);
29289 
29290 	if (rw == KSTAT_WRITE)
29291 		return (EACCES);
29292 
29293 	ns = netstack_find_by_stackid(stackid);
29294 	if (ns == NULL)
29295 		return (-1);
29296 	ipst = ns->netstack_ip;
29297 	if (ipst == NULL) {
29298 		netstack_rele(ns);
29299 		return (-1);
29300 	}
29301 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29302 
29303 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29304 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29305 	icmpkp->inDestUnreachs.value.ui32 =
29306 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29307 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29308 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29309 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29310 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29311 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29312 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29313 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29314 	icmpkp->inTimestampReps.value.ui32 =
29315 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29316 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29317 	icmpkp->inAddrMaskReps.value.ui32 =
29318 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29319 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29320 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29321 	icmpkp->outDestUnreachs.value.ui32 =
29322 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29323 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29324 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29325 	icmpkp->outSrcQuenchs.value.ui32 =
29326 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29327 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29328 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29329 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29330 	icmpkp->outTimestamps.value.ui32 =
29331 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29332 	icmpkp->outTimestampReps.value.ui32 =
29333 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29334 	icmpkp->outAddrMasks.value.ui32 =
29335 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29336 	icmpkp->outAddrMaskReps.value.ui32 =
29337 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29338 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29339 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29340 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29341 	icmpkp->outFragNeeded.value.ui32 =
29342 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29343 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29344 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29345 	icmpkp->inBadRedirects.value.ui32 =
29346 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29347 
29348 	netstack_rele(ns);
29349 	return (0);
29350 }
29351 
29352 /*
29353  * This is the fanout function for raw socket opened for SCTP.  Note
29354  * that it is called after SCTP checks that there is no socket which
29355  * wants a packet.  Then before SCTP handles this out of the blue packet,
29356  * this function is called to see if there is any raw socket for SCTP.
29357  * If there is and it is bound to the correct address, the packet will
29358  * be sent to that socket.  Note that only one raw socket can be bound to
29359  * a port.  This is assured in ipcl_sctp_hash_insert();
29360  */
29361 void
29362 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29363     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29364     zoneid_t zoneid)
29365 {
29366 	conn_t		*connp;
29367 	queue_t		*rq;
29368 	mblk_t		*first_mp;
29369 	boolean_t	secure;
29370 	ip6_t		*ip6h;
29371 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29372 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29373 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29374 	boolean_t	sctp_csum_err = B_FALSE;
29375 
29376 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29377 		sctp_csum_err = B_TRUE;
29378 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29379 	}
29380 
29381 	first_mp = mp;
29382 	if (mctl_present) {
29383 		mp = first_mp->b_cont;
29384 		secure = ipsec_in_is_secure(first_mp);
29385 		ASSERT(mp != NULL);
29386 	} else {
29387 		secure = B_FALSE;
29388 	}
29389 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29390 
29391 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29392 	if (connp == NULL) {
29393 		/*
29394 		 * Although raw sctp is not summed, OOB chunks must be.
29395 		 * Drop the packet here if the sctp checksum failed.
29396 		 */
29397 		if (sctp_csum_err) {
29398 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29399 			freemsg(first_mp);
29400 			return;
29401 		}
29402 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29403 		return;
29404 	}
29405 	rq = connp->conn_rq;
29406 	if (!canputnext(rq)) {
29407 		CONN_DEC_REF(connp);
29408 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29409 		freemsg(first_mp);
29410 		return;
29411 	}
29412 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29413 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29414 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29415 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29416 		if (first_mp == NULL) {
29417 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29418 			CONN_DEC_REF(connp);
29419 			return;
29420 		}
29421 	}
29422 	/*
29423 	 * We probably should not send M_CTL message up to
29424 	 * raw socket.
29425 	 */
29426 	if (mctl_present)
29427 		freeb(first_mp);
29428 
29429 	/* Initiate IPPF processing here if needed. */
29430 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29431 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29432 		ip_process(IPP_LOCAL_IN, &mp,
29433 		    recv_ill->ill_phyint->phyint_ifindex);
29434 		if (mp == NULL) {
29435 			CONN_DEC_REF(connp);
29436 			return;
29437 		}
29438 	}
29439 
29440 	if (connp->conn_recvif || connp->conn_recvslla ||
29441 	    ((connp->conn_ip_recvpktinfo ||
29442 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29443 	    (flags & IP_FF_IPINFO))) {
29444 		int in_flags = 0;
29445 
29446 		/*
29447 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29448 		 * IPF_RECVIF.
29449 		 */
29450 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29451 			in_flags = IPF_RECVIF;
29452 		}
29453 		if (connp->conn_recvslla) {
29454 			in_flags |= IPF_RECVSLLA;
29455 		}
29456 		if (isv4) {
29457 			mp = ip_add_info(mp, recv_ill, in_flags,
29458 			    IPCL_ZONEID(connp), ipst);
29459 		} else {
29460 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29461 			if (mp == NULL) {
29462 				BUMP_MIB(recv_ill->ill_ip_mib,
29463 				    ipIfStatsInDiscards);
29464 				CONN_DEC_REF(connp);
29465 				return;
29466 			}
29467 		}
29468 	}
29469 
29470 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29471 	/*
29472 	 * We are sending the IPSEC_IN message also up. Refer
29473 	 * to comments above this function.
29474 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29475 	 */
29476 	(connp->conn_recv)(connp, mp, NULL);
29477 	CONN_DEC_REF(connp);
29478 }
29479 
29480 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29481 {									\
29482 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29483 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29484 }
29485 /*
29486  * This function should be called only if all packet processing
29487  * including fragmentation is complete. Callers of this function
29488  * must set mp->b_prev to one of these values:
29489  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29490  * prior to handing over the mp as first argument to this function.
29491  *
29492  * If the ire passed by caller is incomplete, this function
29493  * queues the packet and if necessary, sends ARP request and bails.
29494  * If the ire passed is fully resolved, we simply prepend
29495  * the link-layer header to the packet, do ipsec hw acceleration
29496  * work if necessary, and send the packet out on the wire.
29497  *
29498  * NOTE: IPsec will only call this function with fully resolved
29499  * ires if hw acceleration is involved.
29500  * TODO list :
29501  * 	a Handle M_MULTIDATA so that
29502  *	  tcp_multisend->tcp_multisend_data can
29503  *	  call ip_xmit_v4 directly
29504  *	b Handle post-ARP work for fragments so that
29505  *	  ip_wput_frag can call this function.
29506  */
29507 ipxmit_state_t
29508 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io,
29509     boolean_t flow_ctl_enabled, conn_t *connp)
29510 {
29511 	nce_t		*arpce;
29512 	ipha_t		*ipha;
29513 	queue_t		*q;
29514 	int		ill_index;
29515 	mblk_t		*nxt_mp, *first_mp;
29516 	boolean_t	xmit_drop = B_FALSE;
29517 	ip_proc_t	proc;
29518 	ill_t		*out_ill;
29519 	int		pkt_len;
29520 
29521 	arpce = ire->ire_nce;
29522 	ASSERT(arpce != NULL);
29523 
29524 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29525 
29526 	mutex_enter(&arpce->nce_lock);
29527 	switch (arpce->nce_state) {
29528 	case ND_REACHABLE:
29529 		/* If there are other queued packets, queue this packet */
29530 		if (arpce->nce_qd_mp != NULL) {
29531 			if (mp != NULL)
29532 				nce_queue_mp_common(arpce, mp, B_FALSE);
29533 			mp = arpce->nce_qd_mp;
29534 		}
29535 		arpce->nce_qd_mp = NULL;
29536 		mutex_exit(&arpce->nce_lock);
29537 
29538 		/*
29539 		 * Flush the queue.  In the common case, where the
29540 		 * ARP is already resolved,  it will go through the
29541 		 * while loop only once.
29542 		 */
29543 		while (mp != NULL) {
29544 
29545 			nxt_mp = mp->b_next;
29546 			mp->b_next = NULL;
29547 			ASSERT(mp->b_datap->db_type != M_CTL);
29548 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29549 			/*
29550 			 * This info is needed for IPQOS to do COS marking
29551 			 * in ip_wput_attach_llhdr->ip_process.
29552 			 */
29553 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29554 			mp->b_prev = NULL;
29555 
29556 			/* set up ill index for outbound qos processing */
29557 			out_ill = ire_to_ill(ire);
29558 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29559 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29560 			    ill_index, &ipha);
29561 			if (first_mp == NULL) {
29562 				xmit_drop = B_TRUE;
29563 				BUMP_MIB(out_ill->ill_ip_mib,
29564 				    ipIfStatsOutDiscards);
29565 				goto next_mp;
29566 			}
29567 
29568 			/* non-ipsec hw accel case */
29569 			if (io == NULL || !io->ipsec_out_accelerated) {
29570 				/* send it */
29571 				q = ire->ire_stq;
29572 				if (proc == IPP_FWD_OUT) {
29573 					UPDATE_IB_PKT_COUNT(ire);
29574 				} else {
29575 					UPDATE_OB_PKT_COUNT(ire);
29576 				}
29577 				ire->ire_last_used_time = lbolt;
29578 
29579 				if (flow_ctl_enabled || canputnext(q)) {
29580 					if (proc == IPP_FWD_OUT) {
29581 
29582 					BUMP_MIB(out_ill->ill_ip_mib,
29583 					    ipIfStatsHCOutForwDatagrams);
29584 
29585 					}
29586 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29587 					    pkt_len);
29588 
29589 					DTRACE_IP7(send, mblk_t *, first_mp,
29590 					    conn_t *, NULL, void_ip_t *, ipha,
29591 					    __dtrace_ipsr_ill_t *, out_ill,
29592 					    ipha_t *, ipha, ip6_t *, NULL, int,
29593 					    0);
29594 
29595 					ILL_SEND_TX(out_ill,
29596 					    ire, connp, first_mp, 0);
29597 				} else {
29598 					BUMP_MIB(out_ill->ill_ip_mib,
29599 					    ipIfStatsOutDiscards);
29600 					xmit_drop = B_TRUE;
29601 					freemsg(first_mp);
29602 				}
29603 			} else {
29604 				/*
29605 				 * Safety Pup says: make sure this
29606 				 *  is going to the right interface!
29607 				 */
29608 				ill_t *ill1 =
29609 				    (ill_t *)ire->ire_stq->q_ptr;
29610 				int ifindex =
29611 				    ill1->ill_phyint->phyint_ifindex;
29612 				if (ifindex !=
29613 				    io->ipsec_out_capab_ill_index) {
29614 					xmit_drop = B_TRUE;
29615 					freemsg(mp);
29616 				} else {
29617 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29618 					    pkt_len);
29619 
29620 					DTRACE_IP7(send, mblk_t *, first_mp,
29621 					    conn_t *, NULL, void_ip_t *, ipha,
29622 					    __dtrace_ipsr_ill_t *, ill1,
29623 					    ipha_t *, ipha, ip6_t *, NULL,
29624 					    int, 0);
29625 
29626 					ipsec_hw_putnext(ire->ire_stq, mp);
29627 				}
29628 			}
29629 next_mp:
29630 			mp = nxt_mp;
29631 		} /* while (mp != NULL) */
29632 		if (xmit_drop)
29633 			return (SEND_FAILED);
29634 		else
29635 			return (SEND_PASSED);
29636 
29637 	case ND_INITIAL:
29638 	case ND_INCOMPLETE:
29639 
29640 		/*
29641 		 * While we do send off packets to dests that
29642 		 * use fully-resolved CGTP routes, we do not
29643 		 * handle unresolved CGTP routes.
29644 		 */
29645 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29646 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29647 
29648 		if (mp != NULL) {
29649 			/* queue the packet */
29650 			nce_queue_mp_common(arpce, mp, B_FALSE);
29651 		}
29652 
29653 		if (arpce->nce_state == ND_INCOMPLETE) {
29654 			mutex_exit(&arpce->nce_lock);
29655 			DTRACE_PROBE3(ip__xmit__incomplete,
29656 			    (ire_t *), ire, (mblk_t *), mp,
29657 			    (ipsec_out_t *), io);
29658 			return (LOOKUP_IN_PROGRESS);
29659 		}
29660 
29661 		arpce->nce_state = ND_INCOMPLETE;
29662 		mutex_exit(&arpce->nce_lock);
29663 
29664 		/*
29665 		 * Note that ire_add() (called from ire_forward())
29666 		 * holds a ref on the ire until ARP is completed.
29667 		 */
29668 		ire_arpresolve(ire);
29669 		return (LOOKUP_IN_PROGRESS);
29670 	default:
29671 		ASSERT(0);
29672 		mutex_exit(&arpce->nce_lock);
29673 		return (LLHDR_RESLV_FAILED);
29674 	}
29675 }
29676 
29677 #undef	UPDATE_IP_MIB_OB_COUNTERS
29678 
29679 /*
29680  * Return B_TRUE if the buffers differ in length or content.
29681  * This is used for comparing extension header buffers.
29682  * Note that an extension header would be declared different
29683  * even if all that changed was the next header value in that header i.e.
29684  * what really changed is the next extension header.
29685  */
29686 boolean_t
29687 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29688     uint_t blen)
29689 {
29690 	if (!b_valid)
29691 		blen = 0;
29692 
29693 	if (alen != blen)
29694 		return (B_TRUE);
29695 	if (alen == 0)
29696 		return (B_FALSE);	/* Both zero length */
29697 	return (bcmp(abuf, bbuf, alen));
29698 }
29699 
29700 /*
29701  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29702  * Return B_FALSE if memory allocation fails - don't change any state!
29703  */
29704 boolean_t
29705 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29706     const void *src, uint_t srclen)
29707 {
29708 	void *dst;
29709 
29710 	if (!src_valid)
29711 		srclen = 0;
29712 
29713 	ASSERT(*dstlenp == 0);
29714 	if (src != NULL && srclen != 0) {
29715 		dst = mi_alloc(srclen, BPRI_MED);
29716 		if (dst == NULL)
29717 			return (B_FALSE);
29718 	} else {
29719 		dst = NULL;
29720 	}
29721 	if (*dstp != NULL)
29722 		mi_free(*dstp);
29723 	*dstp = dst;
29724 	*dstlenp = dst == NULL ? 0 : srclen;
29725 	return (B_TRUE);
29726 }
29727 
29728 /*
29729  * Replace what is in *dst, *dstlen with the source.
29730  * Assumes ip_allocbuf has already been called.
29731  */
29732 void
29733 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29734     const void *src, uint_t srclen)
29735 {
29736 	if (!src_valid)
29737 		srclen = 0;
29738 
29739 	ASSERT(*dstlenp == srclen);
29740 	if (src != NULL && srclen != 0)
29741 		bcopy(src, *dstp, srclen);
29742 }
29743 
29744 /*
29745  * Free the storage pointed to by the members of an ip6_pkt_t.
29746  */
29747 void
29748 ip6_pkt_free(ip6_pkt_t *ipp)
29749 {
29750 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29751 
29752 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29753 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
29754 		ipp->ipp_hopopts = NULL;
29755 		ipp->ipp_hopoptslen = 0;
29756 	}
29757 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29758 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29759 		ipp->ipp_rtdstopts = NULL;
29760 		ipp->ipp_rtdstoptslen = 0;
29761 	}
29762 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
29763 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
29764 		ipp->ipp_dstopts = NULL;
29765 		ipp->ipp_dstoptslen = 0;
29766 	}
29767 	if (ipp->ipp_fields & IPPF_RTHDR) {
29768 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29769 		ipp->ipp_rthdr = NULL;
29770 		ipp->ipp_rthdrlen = 0;
29771 	}
29772 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
29773 	    IPPF_RTHDR);
29774 }
29775 
29776 zoneid_t
29777 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_stack_t *ipst,
29778     zoneid_t lookup_zoneid)
29779 {
29780 	ire_t		*ire;
29781 	int		ire_flags = MATCH_IRE_TYPE;
29782 	zoneid_t	zoneid = ALL_ZONES;
29783 
29784 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
29785 		return (ALL_ZONES);
29786 
29787 	if (lookup_zoneid != ALL_ZONES)
29788 		ire_flags |= MATCH_IRE_ZONEONLY;
29789 	ire = ire_ctable_lookup(addr, NULL, IRE_LOCAL | IRE_LOOPBACK, NULL,
29790 	    lookup_zoneid, NULL, ire_flags, ipst);
29791 	if (ire != NULL) {
29792 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
29793 		ire_refrele(ire);
29794 	}
29795 	return (zoneid);
29796 }
29797 
29798 zoneid_t
29799 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
29800     ip_stack_t *ipst, zoneid_t lookup_zoneid)
29801 {
29802 	ire_t		*ire;
29803 	int		ire_flags = MATCH_IRE_TYPE;
29804 	zoneid_t	zoneid = ALL_ZONES;
29805 	ipif_t		*ipif_arg = NULL;
29806 
29807 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
29808 		return (ALL_ZONES);
29809 
29810 	if (IN6_IS_ADDR_LINKLOCAL(addr)) {
29811 		ire_flags |= MATCH_IRE_ILL;
29812 		ipif_arg = ill->ill_ipif;
29813 	}
29814 	if (lookup_zoneid != ALL_ZONES)
29815 		ire_flags |= MATCH_IRE_ZONEONLY;
29816 	ire = ire_ctable_lookup_v6(addr, NULL, IRE_LOCAL | IRE_LOOPBACK,
29817 	    ipif_arg, lookup_zoneid, NULL, ire_flags, ipst);
29818 	if (ire != NULL) {
29819 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
29820 		ire_refrele(ire);
29821 	}
29822 	return (zoneid);
29823 }
29824 
29825 /*
29826  * IP obserability hook support functions.
29827  */
29828 
29829 static void
29830 ipobs_init(ip_stack_t *ipst)
29831 {
29832 	ipst->ips_ipobs_enabled = B_FALSE;
29833 	list_create(&ipst->ips_ipobs_cb_list, sizeof (ipobs_cb_t),
29834 	    offsetof(ipobs_cb_t, ipobs_cbnext));
29835 	mutex_init(&ipst->ips_ipobs_cb_lock, NULL, MUTEX_DEFAULT, NULL);
29836 	ipst->ips_ipobs_cb_nwalkers = 0;
29837 	cv_init(&ipst->ips_ipobs_cb_cv, NULL, CV_DRIVER, NULL);
29838 }
29839 
29840 static void
29841 ipobs_fini(ip_stack_t *ipst)
29842 {
29843 	ipobs_cb_t *cb;
29844 
29845 	mutex_enter(&ipst->ips_ipobs_cb_lock);
29846 	while (ipst->ips_ipobs_cb_nwalkers != 0)
29847 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
29848 
29849 	while ((cb = list_head(&ipst->ips_ipobs_cb_list)) != NULL) {
29850 		list_remove(&ipst->ips_ipobs_cb_list, cb);
29851 		kmem_free(cb, sizeof (*cb));
29852 	}
29853 	list_destroy(&ipst->ips_ipobs_cb_list);
29854 	mutex_exit(&ipst->ips_ipobs_cb_lock);
29855 	mutex_destroy(&ipst->ips_ipobs_cb_lock);
29856 	cv_destroy(&ipst->ips_ipobs_cb_cv);
29857 }
29858 
29859 void
29860 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
29861     const ill_t *ill, int ipver, uint32_t hlen, ip_stack_t *ipst)
29862 {
29863 	mblk_t *mp2;
29864 	ipobs_cb_t *ipobs_cb;
29865 	ipobs_hook_data_t *ihd;
29866 	uint64_t grifindex = 0;
29867 
29868 	ASSERT(DB_TYPE(mp) == M_DATA);
29869 
29870 	if (IS_UNDER_IPMP(ill))
29871 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
29872 
29873 	mutex_enter(&ipst->ips_ipobs_cb_lock);
29874 	ipst->ips_ipobs_cb_nwalkers++;
29875 	mutex_exit(&ipst->ips_ipobs_cb_lock);
29876 	for (ipobs_cb = list_head(&ipst->ips_ipobs_cb_list); ipobs_cb != NULL;
29877 	    ipobs_cb = list_next(&ipst->ips_ipobs_cb_list, ipobs_cb)) {
29878 		mp2 = allocb(sizeof (ipobs_hook_data_t), BPRI_HI);
29879 		if (mp2 != NULL) {
29880 			ihd = (ipobs_hook_data_t *)mp2->b_rptr;
29881 			if (((ihd->ihd_mp = dupmsg(mp)) == NULL) &&
29882 			    ((ihd->ihd_mp = copymsg(mp)) == NULL)) {
29883 				freemsg(mp2);
29884 				continue;
29885 			}
29886 			ihd->ihd_mp->b_rptr += hlen;
29887 			ihd->ihd_htype = htype;
29888 			ihd->ihd_ipver = ipver;
29889 			ihd->ihd_zsrc = zsrc;
29890 			ihd->ihd_zdst = zdst;
29891 			ihd->ihd_ifindex = ill->ill_phyint->phyint_ifindex;
29892 			ihd->ihd_grifindex = grifindex;
29893 			ihd->ihd_stack = ipst->ips_netstack;
29894 			mp2->b_wptr += sizeof (*ihd);
29895 			ipobs_cb->ipobs_cbfunc(mp2);
29896 		}
29897 	}
29898 	mutex_enter(&ipst->ips_ipobs_cb_lock);
29899 	ipst->ips_ipobs_cb_nwalkers--;
29900 	if (ipst->ips_ipobs_cb_nwalkers == 0)
29901 		cv_broadcast(&ipst->ips_ipobs_cb_cv);
29902 	mutex_exit(&ipst->ips_ipobs_cb_lock);
29903 }
29904 
29905 void
29906 ipobs_register_hook(netstack_t *ns, pfv_t func)
29907 {
29908 	ipobs_cb_t   *cb;
29909 	ip_stack_t *ipst = ns->netstack_ip;
29910 
29911 	cb = kmem_alloc(sizeof (*cb), KM_SLEEP);
29912 
29913 	mutex_enter(&ipst->ips_ipobs_cb_lock);
29914 	while (ipst->ips_ipobs_cb_nwalkers != 0)
29915 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
29916 	ASSERT(ipst->ips_ipobs_cb_nwalkers == 0);
29917 
29918 	cb->ipobs_cbfunc = func;
29919 	list_insert_head(&ipst->ips_ipobs_cb_list, cb);
29920 	ipst->ips_ipobs_enabled = B_TRUE;
29921 	mutex_exit(&ipst->ips_ipobs_cb_lock);
29922 }
29923 
29924 void
29925 ipobs_unregister_hook(netstack_t *ns, pfv_t func)
29926 {
29927 	ipobs_cb_t	*curcb;
29928 	ip_stack_t	*ipst = ns->netstack_ip;
29929 
29930 	mutex_enter(&ipst->ips_ipobs_cb_lock);
29931 	while (ipst->ips_ipobs_cb_nwalkers != 0)
29932 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
29933 
29934 	for (curcb = list_head(&ipst->ips_ipobs_cb_list); curcb != NULL;
29935 	    curcb = list_next(&ipst->ips_ipobs_cb_list, curcb)) {
29936 		if (func == curcb->ipobs_cbfunc) {
29937 			list_remove(&ipst->ips_ipobs_cb_list, curcb);
29938 			kmem_free(curcb, sizeof (*curcb));
29939 			break;
29940 		}
29941 	}
29942 	if (list_is_empty(&ipst->ips_ipobs_cb_list))
29943 		ipst->ips_ipobs_enabled = B_FALSE;
29944 	mutex_exit(&ipst->ips_ipobs_cb_lock);
29945 }
29946