xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision b9175c69691c8949bec97fb8f689b7d1efdb05bb)
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 #define	IPNDP_IPMP_HOOK_OFFSET		10
932 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
933 	    "ip_debug" },
934 };
935 
936 /*
937  * Table of IP ioctls encoding the various properties of the ioctl and
938  * indexed based on the last byte of the ioctl command. Occasionally there
939  * is a clash, and there is more than 1 ioctl with the same last byte.
940  * In such a case 1 ioctl is encoded in the ndx table and the remaining
941  * ioctls are encoded in the misc table. An entry in the ndx table is
942  * retrieved by indexing on the last byte of the ioctl command and comparing
943  * the ioctl command with the value in the ndx table. In the event of a
944  * mismatch the misc table is then searched sequentially for the desired
945  * ioctl command.
946  *
947  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
948  */
949 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
950 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
951 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
952 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
953 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
954 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
955 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
956 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
957 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
958 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
959 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
960 
961 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
962 			MISC_CMD, ip_siocaddrt, NULL },
963 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
964 			MISC_CMD, ip_siocdelrt, NULL },
965 
966 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
967 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
968 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
969 			IF_CMD, ip_sioctl_get_addr, NULL },
970 
971 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
972 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
973 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
974 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
975 
976 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
977 			IPI_PRIV | IPI_WR,
978 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
979 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
980 			IPI_MODOK | IPI_GET_CMD,
981 			IF_CMD, ip_sioctl_get_flags, NULL },
982 
983 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
984 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
985 
986 	/* copyin size cannot be coded for SIOCGIFCONF */
987 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
988 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
989 
990 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
991 			IF_CMD, ip_sioctl_mtu, NULL },
992 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD,
993 			IF_CMD, ip_sioctl_get_mtu, NULL },
994 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
995 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
996 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
997 			IF_CMD, ip_sioctl_brdaddr, NULL },
998 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
999 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
1000 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1001 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1002 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1003 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
1004 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1005 			IF_CMD, ip_sioctl_metric, NULL },
1006 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1007 
1008 	/* See 166-168 below for extended SIOC*XARP ioctls */
1009 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1010 			ARP_CMD, ip_sioctl_arp, NULL },
1011 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
1012 			ARP_CMD, ip_sioctl_arp, NULL },
1013 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1014 			ARP_CMD, ip_sioctl_arp, NULL },
1015 
1016 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1017 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1018 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1019 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1020 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1021 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1022 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1023 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1024 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1025 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1037 
1038 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1039 			MISC_CMD, if_unitsel, if_unitsel_restart },
1040 
1041 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1042 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 
1060 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1061 			IPI_PRIV | IPI_WR | IPI_MODOK,
1062 			IF_CMD, ip_sioctl_sifname, NULL },
1063 
1064 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1065 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1066 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 
1078 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
1079 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1080 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
1081 			IF_CMD, ip_sioctl_get_muxid, NULL },
1082 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1083 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
1084 
1085 	/* Both if and lif variants share same func */
1086 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
1087 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1088 	/* Both if and lif variants share same func */
1089 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1090 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
1091 
1092 	/* copyin size cannot be coded for SIOCGIFCONF */
1093 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1094 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1095 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1096 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1097 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 
1113 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1114 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
1115 			ip_sioctl_removeif_restart },
1116 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1117 			IPI_GET_CMD | IPI_PRIV | IPI_WR,
1118 			LIF_CMD, ip_sioctl_addif, NULL },
1119 #define	SIOCLIFADDR_NDX 112
1120 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1121 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1122 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1123 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
1124 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1125 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1126 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1127 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1128 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1129 			IPI_PRIV | IPI_WR,
1130 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1131 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1132 			IPI_GET_CMD | IPI_MODOK,
1133 			LIF_CMD, ip_sioctl_get_flags, NULL },
1134 
1135 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1136 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1137 
1138 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1139 			ip_sioctl_get_lifconf, NULL },
1140 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1141 			LIF_CMD, ip_sioctl_mtu, NULL },
1142 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
1143 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1144 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1145 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1146 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1147 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1148 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1149 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
1150 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1151 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1152 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1153 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
1154 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1155 			LIF_CMD, ip_sioctl_metric, NULL },
1156 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1157 			IPI_PRIV | IPI_WR | IPI_MODOK,
1158 			LIF_CMD, ip_sioctl_slifname,
1159 			ip_sioctl_slifname_restart },
1160 
1161 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
1162 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1163 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1164 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
1165 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1166 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
1167 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1168 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
1169 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1170 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
1171 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1172 			LIF_CMD, ip_sioctl_token, NULL },
1173 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1174 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1175 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1176 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1177 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1178 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1179 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1180 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1181 
1182 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1183 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1184 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1185 			LIF_CMD, ip_siocdelndp_v6, NULL },
1186 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1187 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1188 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1189 			LIF_CMD, ip_siocsetndp_v6, NULL },
1190 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1191 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1192 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1193 			MISC_CMD, ip_sioctl_tonlink, NULL },
1194 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1195 			MISC_CMD, ip_sioctl_tmysite, NULL },
1196 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), 0,
1197 			TUN_CMD, ip_sioctl_tunparam, NULL },
1198 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1199 		    IPI_PRIV | IPI_WR,
1200 		    TUN_CMD, ip_sioctl_tunparam, NULL },
1201 
1202 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1203 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1204 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1205 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1206 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1207 
1208 	/* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1209 
1210 	/* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD |
1211 			IPI_WR, LIF_CMD, ip_sioctl_get_binding, NULL },
1212 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1213 			IPI_PRIV | IPI_WR,
1214 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1215 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1216 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1217 	/* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1218 			IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1219 
1220 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1221 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1222 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1223 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1224 
1225 	/* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1226 
1227 	/* These are handled in ip_sioctl_copyin_setup itself */
1228 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1229 			MISC_CMD, NULL, NULL },
1230 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1231 			MISC_CMD, NULL, NULL },
1232 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1233 
1234 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1235 			ip_sioctl_get_lifconf, NULL },
1236 
1237 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1238 			XARP_CMD, ip_sioctl_arp, NULL },
1239 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1240 			XARP_CMD, ip_sioctl_arp, NULL },
1241 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1242 			XARP_CMD, ip_sioctl_arp, NULL },
1243 
1244 	/* SIOCPOPSOCKFS is not handled by IP */
1245 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1246 
1247 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1248 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1249 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1250 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1251 			ip_sioctl_slifzone_restart },
1252 	/* 172-174 are SCTP ioctls and not handled by IP */
1253 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1254 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1255 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1256 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1257 			IPI_GET_CMD, LIF_CMD,
1258 			ip_sioctl_get_lifusesrc, 0 },
1259 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1260 			IPI_PRIV | IPI_WR,
1261 			LIF_CMD, ip_sioctl_slifusesrc,
1262 			NULL },
1263 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1264 			ip_sioctl_get_lifsrcof, NULL },
1265 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1266 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1267 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1268 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1269 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1270 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1271 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1272 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1273 	/* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1274 	/* SIOCSENABLESDP is handled by SDP */
1275 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1276 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1277 };
1278 
1279 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1280 
1281 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1282 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1283 		IPI_GET_CMD, TUN_CMD, ip_sioctl_tunparam, NULL },
1284 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1285 		TUN_CMD, ip_sioctl_tunparam, NULL },
1286 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1287 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1288 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1289 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1290 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1291 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1292 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1293 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1294 		MISC_CMD, mrt_ioctl},
1295 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_GET_CMD,
1296 		MISC_CMD, mrt_ioctl},
1297 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1298 		MISC_CMD, mrt_ioctl}
1299 };
1300 
1301 int ip_misc_ioctl_count =
1302     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1303 
1304 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1305 					/* Settable in /etc/system */
1306 /* Defined in ip_ire.c */
1307 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1308 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1309 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1310 
1311 static nv_t	ire_nv_arr[] = {
1312 	{ IRE_BROADCAST, "BROADCAST" },
1313 	{ IRE_LOCAL, "LOCAL" },
1314 	{ IRE_LOOPBACK, "LOOPBACK" },
1315 	{ IRE_CACHE, "CACHE" },
1316 	{ IRE_DEFAULT, "DEFAULT" },
1317 	{ IRE_PREFIX, "PREFIX" },
1318 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1319 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1320 	{ IRE_HOST, "HOST" },
1321 	{ 0 }
1322 };
1323 
1324 nv_t	*ire_nv_tbl = ire_nv_arr;
1325 
1326 /* Simple ICMP IP Header Template */
1327 static ipha_t icmp_ipha = {
1328 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1329 };
1330 
1331 struct module_info ip_mod_info = {
1332 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1333 	IP_MOD_LOWAT
1334 };
1335 
1336 /*
1337  * Duplicate static symbols within a module confuses mdb; so we avoid the
1338  * problem by making the symbols here distinct from those in udp.c.
1339  */
1340 
1341 /*
1342  * Entry points for IP as a device and as a module.
1343  * FIXME: down the road we might want a separate module and driver qinit.
1344  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1345  */
1346 static struct qinit iprinitv4 = {
1347 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1348 	&ip_mod_info
1349 };
1350 
1351 struct qinit iprinitv6 = {
1352 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1353 	&ip_mod_info
1354 };
1355 
1356 static struct qinit ipwinitv4 = {
1357 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1358 	&ip_mod_info
1359 };
1360 
1361 struct qinit ipwinitv6 = {
1362 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1363 	&ip_mod_info
1364 };
1365 
1366 static struct qinit iplrinit = {
1367 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1368 	&ip_mod_info
1369 };
1370 
1371 static struct qinit iplwinit = {
1372 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1373 	&ip_mod_info
1374 };
1375 
1376 /* For AF_INET aka /dev/ip */
1377 struct streamtab ipinfov4 = {
1378 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1379 };
1380 
1381 /* For AF_INET6 aka /dev/ip6 */
1382 struct streamtab ipinfov6 = {
1383 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1384 };
1385 
1386 #ifdef	DEBUG
1387 static boolean_t skip_sctp_cksum = B_FALSE;
1388 #endif
1389 
1390 /*
1391  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1392  * ip_rput_v6(), ip_output(), etc.  If the message
1393  * block already has a M_CTL at the front of it, then simply set the zoneid
1394  * appropriately.
1395  */
1396 mblk_t *
1397 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1398 {
1399 	mblk_t		*first_mp;
1400 	ipsec_out_t	*io;
1401 
1402 	ASSERT(zoneid != ALL_ZONES);
1403 	if (mp->b_datap->db_type == M_CTL) {
1404 		io = (ipsec_out_t *)mp->b_rptr;
1405 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1406 		io->ipsec_out_zoneid = zoneid;
1407 		return (mp);
1408 	}
1409 
1410 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1411 	if (first_mp == NULL)
1412 		return (NULL);
1413 	io = (ipsec_out_t *)first_mp->b_rptr;
1414 	/* This is not a secure packet */
1415 	io->ipsec_out_secure = B_FALSE;
1416 	io->ipsec_out_zoneid = zoneid;
1417 	first_mp->b_cont = mp;
1418 	return (first_mp);
1419 }
1420 
1421 /*
1422  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1423  */
1424 mblk_t *
1425 ip_copymsg(mblk_t *mp)
1426 {
1427 	mblk_t *nmp;
1428 	ipsec_info_t *in;
1429 
1430 	if (mp->b_datap->db_type != M_CTL)
1431 		return (copymsg(mp));
1432 
1433 	in = (ipsec_info_t *)mp->b_rptr;
1434 
1435 	/*
1436 	 * Note that M_CTL is also used for delivering ICMP error messages
1437 	 * upstream to transport layers.
1438 	 */
1439 	if (in->ipsec_info_type != IPSEC_OUT &&
1440 	    in->ipsec_info_type != IPSEC_IN)
1441 		return (copymsg(mp));
1442 
1443 	nmp = copymsg(mp->b_cont);
1444 
1445 	if (in->ipsec_info_type == IPSEC_OUT) {
1446 		return (ipsec_out_tag(mp, nmp,
1447 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1448 	} else {
1449 		return (ipsec_in_tag(mp, nmp,
1450 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1451 	}
1452 }
1453 
1454 /* Generate an ICMP fragmentation needed message. */
1455 static void
1456 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1457     ip_stack_t *ipst)
1458 {
1459 	icmph_t	icmph;
1460 	mblk_t *first_mp;
1461 	boolean_t mctl_present;
1462 
1463 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1464 
1465 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1466 		if (mctl_present)
1467 			freeb(first_mp);
1468 		return;
1469 	}
1470 
1471 	bzero(&icmph, sizeof (icmph_t));
1472 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1473 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1474 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1475 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1476 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1477 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1478 	    ipst);
1479 }
1480 
1481 /*
1482  * icmp_inbound deals with ICMP messages in the following ways.
1483  *
1484  * 1) It needs to send a reply back and possibly delivering it
1485  *    to the "interested" upper clients.
1486  * 2) It needs to send it to the upper clients only.
1487  * 3) It needs to change some values in IP only.
1488  * 4) It needs to change some values in IP and upper layers e.g TCP.
1489  *
1490  * We need to accomodate icmp messages coming in clear until we get
1491  * everything secure from the wire. If icmp_accept_clear_messages
1492  * is zero we check with the global policy and act accordingly. If
1493  * it is non-zero, we accept the message without any checks. But
1494  * *this does not mean* that this will be delivered to the upper
1495  * clients. By accepting we might send replies back, change our MTU
1496  * value etc. but delivery to the ULP/clients depends on their policy
1497  * dispositions.
1498  *
1499  * We handle the above 4 cases in the context of IPsec in the
1500  * following way :
1501  *
1502  * 1) Send the reply back in the same way as the request came in.
1503  *    If it came in encrypted, it goes out encrypted. If it came in
1504  *    clear, it goes out in clear. Thus, this will prevent chosen
1505  *    plain text attack.
1506  * 2) The client may or may not expect things to come in secure.
1507  *    If it comes in secure, the policy constraints are checked
1508  *    before delivering it to the upper layers. If it comes in
1509  *    clear, ipsec_inbound_accept_clear will decide whether to
1510  *    accept this in clear or not. In both the cases, if the returned
1511  *    message (IP header + 8 bytes) that caused the icmp message has
1512  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1513  *    sending up. If there are only 8 bytes of returned message, then
1514  *    upper client will not be notified.
1515  * 3) Check with global policy to see whether it matches the constaints.
1516  *    But this will be done only if icmp_accept_messages_in_clear is
1517  *    zero.
1518  * 4) If we need to change both in IP and ULP, then the decision taken
1519  *    while affecting the values in IP and while delivering up to TCP
1520  *    should be the same.
1521  *
1522  * 	There are two cases.
1523  *
1524  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1525  *	   failed), we will not deliver it to the ULP, even though they
1526  *	   are *willing* to accept in *clear*. This is fine as our global
1527  *	   disposition to icmp messages asks us reject the datagram.
1528  *
1529  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1530  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1531  *	   to deliver it to ULP (policy failed), it can lead to
1532  *	   consistency problems. The cases known at this time are
1533  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1534  *	   values :
1535  *
1536  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1537  *	     and Upper layer rejects. Then the communication will
1538  *	     come to a stop. This is solved by making similar decisions
1539  *	     at both levels. Currently, when we are unable to deliver
1540  *	     to the Upper Layer (due to policy failures) while IP has
1541  *	     adjusted ire_max_frag, the next outbound datagram would
1542  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1543  *	     will be with the right level of protection. Thus the right
1544  *	     value will be communicated even if we are not able to
1545  *	     communicate when we get from the wire initially. But this
1546  *	     assumes there would be at least one outbound datagram after
1547  *	     IP has adjusted its ire_max_frag value. To make things
1548  *	     simpler, we accept in clear after the validation of
1549  *	     AH/ESP headers.
1550  *
1551  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1552  *	     upper layer depending on the level of protection the upper
1553  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1554  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1555  *	     should be accepted in clear when the Upper layer expects secure.
1556  *	     Thus the communication may get aborted by some bad ICMP
1557  *	     packets.
1558  *
1559  * IPQoS Notes:
1560  * The only instance when a packet is sent for processing is when there
1561  * isn't an ICMP client and if we are interested in it.
1562  * If there is a client, IPPF processing will take place in the
1563  * ip_fanout_proto routine.
1564  *
1565  * Zones notes:
1566  * The packet is only processed in the context of the specified zone: typically
1567  * only this zone will reply to an echo request, and only interested clients in
1568  * this zone will receive a copy of the packet. This means that the caller must
1569  * call icmp_inbound() for each relevant zone.
1570  */
1571 static void
1572 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1573     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1574     ill_t *recv_ill, zoneid_t zoneid)
1575 {
1576 	icmph_t	*icmph;
1577 	ipha_t	*ipha;
1578 	int	iph_hdr_length;
1579 	int	hdr_length;
1580 	boolean_t	interested;
1581 	uint32_t	ts;
1582 	uchar_t	*wptr;
1583 	ipif_t	*ipif;
1584 	mblk_t *first_mp;
1585 	ipsec_in_t *ii;
1586 	timestruc_t now;
1587 	uint32_t ill_index;
1588 	ip_stack_t *ipst;
1589 
1590 	ASSERT(ill != NULL);
1591 	ipst = ill->ill_ipst;
1592 
1593 	first_mp = mp;
1594 	if (mctl_present) {
1595 		mp = first_mp->b_cont;
1596 		ASSERT(mp != NULL);
1597 	}
1598 
1599 	ipha = (ipha_t *)mp->b_rptr;
1600 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1601 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1602 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1603 		if (first_mp == NULL)
1604 			return;
1605 	}
1606 
1607 	/*
1608 	 * On a labeled system, we have to check whether the zone itself is
1609 	 * permitted to receive raw traffic.
1610 	 */
1611 	if (is_system_labeled()) {
1612 		if (zoneid == ALL_ZONES)
1613 			zoneid = tsol_packet_to_zoneid(mp);
1614 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1615 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1616 			    zoneid));
1617 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1618 			freemsg(first_mp);
1619 			return;
1620 		}
1621 	}
1622 
1623 	/*
1624 	 * We have accepted the ICMP message. It means that we will
1625 	 * respond to the packet if needed. It may not be delivered
1626 	 * to the upper client depending on the policy constraints
1627 	 * and the disposition in ipsec_inbound_accept_clear.
1628 	 */
1629 
1630 	ASSERT(ill != NULL);
1631 
1632 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1633 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1634 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1635 		/* Last chance to get real. */
1636 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1637 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1638 			freemsg(first_mp);
1639 			return;
1640 		}
1641 		/* Refresh iph following the pullup. */
1642 		ipha = (ipha_t *)mp->b_rptr;
1643 	}
1644 	/* ICMP header checksum, including checksum field, should be zero. */
1645 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1646 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1647 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1648 		freemsg(first_mp);
1649 		return;
1650 	}
1651 	/* The IP header will always be a multiple of four bytes */
1652 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1653 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1654 	    icmph->icmph_code));
1655 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1656 	/* We will set "interested" to "true" if we want a copy */
1657 	interested = B_FALSE;
1658 	switch (icmph->icmph_type) {
1659 	case ICMP_ECHO_REPLY:
1660 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1661 		break;
1662 	case ICMP_DEST_UNREACHABLE:
1663 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1664 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1665 		interested = B_TRUE;	/* Pass up to transport */
1666 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1667 		break;
1668 	case ICMP_SOURCE_QUENCH:
1669 		interested = B_TRUE;	/* Pass up to transport */
1670 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1671 		break;
1672 	case ICMP_REDIRECT:
1673 		if (!ipst->ips_ip_ignore_redirect)
1674 			interested = B_TRUE;
1675 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1676 		break;
1677 	case ICMP_ECHO_REQUEST:
1678 		/*
1679 		 * Whether to respond to echo requests that come in as IP
1680 		 * broadcasts or as IP multicast is subject to debate
1681 		 * (what isn't?).  We aim to please, you pick it.
1682 		 * Default is do it.
1683 		 */
1684 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1685 			/* unicast: always respond */
1686 			interested = B_TRUE;
1687 		} else if (CLASSD(ipha->ipha_dst)) {
1688 			/* multicast: respond based on tunable */
1689 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1690 		} else if (broadcast) {
1691 			/* broadcast: respond based on tunable */
1692 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1693 		}
1694 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1695 		break;
1696 	case ICMP_ROUTER_ADVERTISEMENT:
1697 	case ICMP_ROUTER_SOLICITATION:
1698 		break;
1699 	case ICMP_TIME_EXCEEDED:
1700 		interested = B_TRUE;	/* Pass up to transport */
1701 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1702 		break;
1703 	case ICMP_PARAM_PROBLEM:
1704 		interested = B_TRUE;	/* Pass up to transport */
1705 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1706 		break;
1707 	case ICMP_TIME_STAMP_REQUEST:
1708 		/* Response to Time Stamp Requests is local policy. */
1709 		if (ipst->ips_ip_g_resp_to_timestamp &&
1710 		    /* So is whether to respond if it was an IP broadcast. */
1711 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1712 			int tstamp_len = 3 * sizeof (uint32_t);
1713 
1714 			if (wptr +  tstamp_len > mp->b_wptr) {
1715 				if (!pullupmsg(mp, wptr + tstamp_len -
1716 				    mp->b_rptr)) {
1717 					BUMP_MIB(ill->ill_ip_mib,
1718 					    ipIfStatsInDiscards);
1719 					freemsg(first_mp);
1720 					return;
1721 				}
1722 				/* Refresh ipha following the pullup. */
1723 				ipha = (ipha_t *)mp->b_rptr;
1724 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1725 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1726 			}
1727 			interested = B_TRUE;
1728 		}
1729 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1730 		break;
1731 	case ICMP_TIME_STAMP_REPLY:
1732 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1733 		break;
1734 	case ICMP_INFO_REQUEST:
1735 		/* Per RFC 1122 3.2.2.7, ignore this. */
1736 	case ICMP_INFO_REPLY:
1737 		break;
1738 	case ICMP_ADDRESS_MASK_REQUEST:
1739 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1740 		    !broadcast) &&
1741 		    /* TODO m_pullup of complete header? */
1742 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1743 			interested = B_TRUE;
1744 		}
1745 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1746 		break;
1747 	case ICMP_ADDRESS_MASK_REPLY:
1748 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1749 		break;
1750 	default:
1751 		interested = B_TRUE;	/* Pass up to transport */
1752 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1753 		break;
1754 	}
1755 	/* See if there is an ICMP client. */
1756 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1757 		/* If there is an ICMP client and we want one too, copy it. */
1758 		mblk_t *first_mp1;
1759 
1760 		if (!interested) {
1761 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1762 			    ip_policy, recv_ill, zoneid);
1763 			return;
1764 		}
1765 		first_mp1 = ip_copymsg(first_mp);
1766 		if (first_mp1 != NULL) {
1767 			ip_fanout_proto(q, first_mp1, ill, ipha,
1768 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1769 		}
1770 	} else if (!interested) {
1771 		freemsg(first_mp);
1772 		return;
1773 	} else {
1774 		/*
1775 		 * Initiate policy processing for this packet if ip_policy
1776 		 * is true.
1777 		 */
1778 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1779 			ill_index = ill->ill_phyint->phyint_ifindex;
1780 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1781 			if (mp == NULL) {
1782 				if (mctl_present) {
1783 					freeb(first_mp);
1784 				}
1785 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1786 				return;
1787 			}
1788 		}
1789 	}
1790 	/* We want to do something with it. */
1791 	/* Check db_ref to make sure we can modify the packet. */
1792 	if (mp->b_datap->db_ref > 1) {
1793 		mblk_t	*first_mp1;
1794 
1795 		first_mp1 = ip_copymsg(first_mp);
1796 		freemsg(first_mp);
1797 		if (!first_mp1) {
1798 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1799 			return;
1800 		}
1801 		first_mp = first_mp1;
1802 		if (mctl_present) {
1803 			mp = first_mp->b_cont;
1804 			ASSERT(mp != NULL);
1805 		} else {
1806 			mp = first_mp;
1807 		}
1808 		ipha = (ipha_t *)mp->b_rptr;
1809 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1810 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1811 	}
1812 	switch (icmph->icmph_type) {
1813 	case ICMP_ADDRESS_MASK_REQUEST:
1814 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1815 		if (ipif == NULL) {
1816 			freemsg(first_mp);
1817 			return;
1818 		}
1819 		/*
1820 		 * outging interface must be IPv4
1821 		 */
1822 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1823 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1824 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1825 		ipif_refrele(ipif);
1826 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1827 		break;
1828 	case ICMP_ECHO_REQUEST:
1829 		icmph->icmph_type = ICMP_ECHO_REPLY;
1830 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1831 		break;
1832 	case ICMP_TIME_STAMP_REQUEST: {
1833 		uint32_t *tsp;
1834 
1835 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1836 		tsp = (uint32_t *)wptr;
1837 		tsp++;		/* Skip past 'originate time' */
1838 		/* Compute # of milliseconds since midnight */
1839 		gethrestime(&now);
1840 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1841 		    now.tv_nsec / (NANOSEC / MILLISEC);
1842 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1843 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1844 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1845 		break;
1846 	}
1847 	default:
1848 		ipha = (ipha_t *)&icmph[1];
1849 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1850 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1851 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1852 				freemsg(first_mp);
1853 				return;
1854 			}
1855 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1856 			ipha = (ipha_t *)&icmph[1];
1857 		}
1858 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1859 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1860 			freemsg(first_mp);
1861 			return;
1862 		}
1863 		hdr_length = IPH_HDR_LENGTH(ipha);
1864 		if (hdr_length < sizeof (ipha_t)) {
1865 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1866 			freemsg(first_mp);
1867 			return;
1868 		}
1869 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1870 			if (!pullupmsg(mp,
1871 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1872 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1873 				freemsg(first_mp);
1874 				return;
1875 			}
1876 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1877 			ipha = (ipha_t *)&icmph[1];
1878 		}
1879 		switch (icmph->icmph_type) {
1880 		case ICMP_REDIRECT:
1881 			/*
1882 			 * As there is no upper client to deliver, we don't
1883 			 * need the first_mp any more.
1884 			 */
1885 			if (mctl_present) {
1886 				freeb(first_mp);
1887 			}
1888 			icmp_redirect(ill, mp);
1889 			return;
1890 		case ICMP_DEST_UNREACHABLE:
1891 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1892 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1893 				    zoneid, mp, iph_hdr_length, ipst)) {
1894 					freemsg(first_mp);
1895 					return;
1896 				}
1897 				/*
1898 				 * icmp_inbound_too_big() may alter mp.
1899 				 * Resynch ipha and icmph accordingly.
1900 				 */
1901 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1902 				ipha = (ipha_t *)&icmph[1];
1903 			}
1904 			/* FALLTHRU */
1905 		default :
1906 			/*
1907 			 * IPQoS notes: Since we have already done IPQoS
1908 			 * processing we don't want to do it again in
1909 			 * the fanout routines called by
1910 			 * icmp_inbound_error_fanout, hence the last
1911 			 * argument, ip_policy, is B_FALSE.
1912 			 */
1913 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1914 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1915 			    B_FALSE, recv_ill, zoneid);
1916 		}
1917 		return;
1918 	}
1919 	/* Send out an ICMP packet */
1920 	icmph->icmph_checksum = 0;
1921 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1922 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1923 		ipif_t	*ipif_chosen;
1924 		/*
1925 		 * Make it look like it was directed to us, so we don't look
1926 		 * like a fool with a broadcast or multicast source address.
1927 		 */
1928 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1929 		/*
1930 		 * Make sure that we haven't grabbed an interface that's DOWN.
1931 		 */
1932 		if (ipif != NULL) {
1933 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1934 			    ipha->ipha_src, zoneid);
1935 			if (ipif_chosen != NULL) {
1936 				ipif_refrele(ipif);
1937 				ipif = ipif_chosen;
1938 			}
1939 		}
1940 		if (ipif == NULL) {
1941 			ip0dbg(("icmp_inbound: "
1942 			    "No source for broadcast/multicast:\n"
1943 			    "\tsrc 0x%x dst 0x%x ill %p "
1944 			    "ipif_lcl_addr 0x%x\n",
1945 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1946 			    (void *)ill,
1947 			    ill->ill_ipif->ipif_lcl_addr));
1948 			freemsg(first_mp);
1949 			return;
1950 		}
1951 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1952 		ipha->ipha_dst = ipif->ipif_src_addr;
1953 		ipif_refrele(ipif);
1954 	}
1955 	/* Reset time to live. */
1956 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1957 	{
1958 		/* Swap source and destination addresses */
1959 		ipaddr_t tmp;
1960 
1961 		tmp = ipha->ipha_src;
1962 		ipha->ipha_src = ipha->ipha_dst;
1963 		ipha->ipha_dst = tmp;
1964 	}
1965 	ipha->ipha_ident = 0;
1966 	if (!IS_SIMPLE_IPH(ipha))
1967 		icmp_options_update(ipha);
1968 
1969 	if (!mctl_present) {
1970 		/*
1971 		 * This packet should go out the same way as it
1972 		 * came in i.e in clear. To make sure that global
1973 		 * policy will not be applied to this in ip_wput_ire,
1974 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
1975 		 */
1976 		ASSERT(first_mp == mp);
1977 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
1978 		if (first_mp == NULL) {
1979 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1980 			freemsg(mp);
1981 			return;
1982 		}
1983 		ii = (ipsec_in_t *)first_mp->b_rptr;
1984 
1985 		/* This is not a secure packet */
1986 		ii->ipsec_in_secure = B_FALSE;
1987 		first_mp->b_cont = mp;
1988 	} else {
1989 		ii = (ipsec_in_t *)first_mp->b_rptr;
1990 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
1991 	}
1992 	ii->ipsec_in_zoneid = zoneid;
1993 	ASSERT(zoneid != ALL_ZONES);
1994 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
1995 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1996 		return;
1997 	}
1998 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
1999 	put(WR(q), first_mp);
2000 }
2001 
2002 static ipaddr_t
2003 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2004 {
2005 	conn_t *connp;
2006 	connf_t *connfp;
2007 	ipaddr_t nexthop_addr = INADDR_ANY;
2008 	int hdr_length = IPH_HDR_LENGTH(ipha);
2009 	uint16_t *up;
2010 	uint32_t ports;
2011 	ip_stack_t *ipst = ill->ill_ipst;
2012 
2013 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2014 	switch (ipha->ipha_protocol) {
2015 		case IPPROTO_TCP:
2016 		{
2017 			tcph_t *tcph;
2018 
2019 			/* do a reverse lookup */
2020 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2021 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2022 			    TCPS_LISTEN, ipst);
2023 			break;
2024 		}
2025 		case IPPROTO_UDP:
2026 		{
2027 			uint32_t dstport, srcport;
2028 
2029 			((uint16_t *)&ports)[0] = up[1];
2030 			((uint16_t *)&ports)[1] = up[0];
2031 
2032 			/* Extract ports in net byte order */
2033 			dstport = htons(ntohl(ports) & 0xFFFF);
2034 			srcport = htons(ntohl(ports) >> 16);
2035 
2036 			connfp = &ipst->ips_ipcl_udp_fanout[
2037 			    IPCL_UDP_HASH(dstport, ipst)];
2038 			mutex_enter(&connfp->connf_lock);
2039 			connp = connfp->connf_head;
2040 
2041 			/* do a reverse lookup */
2042 			while ((connp != NULL) &&
2043 			    (!IPCL_UDP_MATCH(connp, dstport,
2044 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2045 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2046 				connp = connp->conn_next;
2047 			}
2048 			if (connp != NULL)
2049 				CONN_INC_REF(connp);
2050 			mutex_exit(&connfp->connf_lock);
2051 			break;
2052 		}
2053 		case IPPROTO_SCTP:
2054 		{
2055 			in6_addr_t map_src, map_dst;
2056 
2057 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2058 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2059 			((uint16_t *)&ports)[0] = up[1];
2060 			((uint16_t *)&ports)[1] = up[0];
2061 
2062 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2063 			    zoneid, ipst->ips_netstack->netstack_sctp);
2064 			if (connp == NULL) {
2065 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2066 				    zoneid, ports, ipha, ipst);
2067 			} else {
2068 				CONN_INC_REF(connp);
2069 				SCTP_REFRELE(CONN2SCTP(connp));
2070 			}
2071 			break;
2072 		}
2073 		default:
2074 		{
2075 			ipha_t ripha;
2076 
2077 			ripha.ipha_src = ipha->ipha_dst;
2078 			ripha.ipha_dst = ipha->ipha_src;
2079 			ripha.ipha_protocol = ipha->ipha_protocol;
2080 
2081 			connfp = &ipst->ips_ipcl_proto_fanout[
2082 			    ipha->ipha_protocol];
2083 			mutex_enter(&connfp->connf_lock);
2084 			connp = connfp->connf_head;
2085 			for (connp = connfp->connf_head; connp != NULL;
2086 			    connp = connp->conn_next) {
2087 				if (IPCL_PROTO_MATCH(connp,
2088 				    ipha->ipha_protocol, &ripha, ill,
2089 				    0, zoneid)) {
2090 					CONN_INC_REF(connp);
2091 					break;
2092 				}
2093 			}
2094 			mutex_exit(&connfp->connf_lock);
2095 		}
2096 	}
2097 	if (connp != NULL) {
2098 		if (connp->conn_nexthop_set)
2099 			nexthop_addr = connp->conn_nexthop_v4;
2100 		CONN_DEC_REF(connp);
2101 	}
2102 	return (nexthop_addr);
2103 }
2104 
2105 /* Table from RFC 1191 */
2106 static int icmp_frag_size_table[] =
2107 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2108 
2109 /*
2110  * Process received ICMP Packet too big.
2111  * After updating any IRE it does the fanout to any matching transport streams.
2112  * Assumes the message has been pulled up till the IP header that caused
2113  * the error.
2114  *
2115  * Returns B_FALSE on failure and B_TRUE on success.
2116  */
2117 static boolean_t
2118 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2119     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2120     ip_stack_t *ipst)
2121 {
2122 	ire_t	*ire, *first_ire;
2123 	int	mtu, orig_mtu;
2124 	int	hdr_length;
2125 	ipaddr_t nexthop_addr;
2126 	boolean_t disable_pmtud;
2127 
2128 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2129 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2130 	ASSERT(ill != NULL);
2131 
2132 	hdr_length = IPH_HDR_LENGTH(ipha);
2133 
2134 	/* Drop if the original packet contained a source route */
2135 	if (ip_source_route_included(ipha)) {
2136 		return (B_FALSE);
2137 	}
2138 	/*
2139 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2140 	 * header.
2141 	 */
2142 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2143 	    mp->b_wptr) {
2144 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2145 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2146 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2147 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2148 			return (B_FALSE);
2149 		}
2150 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2151 		ipha = (ipha_t *)&icmph[1];
2152 	}
2153 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2154 	if (nexthop_addr != INADDR_ANY) {
2155 		/* nexthop set */
2156 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2157 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2158 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2159 	} else {
2160 		/* nexthop not set */
2161 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2162 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2163 	}
2164 
2165 	if (!first_ire) {
2166 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2167 		    ntohl(ipha->ipha_dst)));
2168 		return (B_FALSE);
2169 	}
2170 
2171 	/* Check for MTU discovery advice as described in RFC 1191 */
2172 	mtu = ntohs(icmph->icmph_du_mtu);
2173 	orig_mtu = mtu;
2174 	disable_pmtud = B_FALSE;
2175 
2176 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2177 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2178 	    ire = ire->ire_next) {
2179 		/*
2180 		 * Look for the connection to which this ICMP message is
2181 		 * directed. If it has the IP_NEXTHOP option set, then the
2182 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2183 		 * option. Else the search is limited to regular IREs.
2184 		 */
2185 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2186 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2187 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2188 		    (nexthop_addr != INADDR_ANY)))
2189 			continue;
2190 
2191 		mutex_enter(&ire->ire_lock);
2192 		if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
2193 			uint32_t length;
2194 			int	i;
2195 
2196 			/*
2197 			 * Use the table from RFC 1191 to figure out
2198 			 * the next "plateau" based on the length in
2199 			 * the original IP packet.
2200 			 */
2201 			length = ntohs(ipha->ipha_length);
2202 			DTRACE_PROBE2(ip4__pmtu__guess, ire_t *, ire,
2203 			    uint32_t, length);
2204 			if (ire->ire_max_frag <= length &&
2205 			    ire->ire_max_frag >= length - hdr_length) {
2206 				/*
2207 				 * Handle broken BSD 4.2 systems that
2208 				 * return the wrong iph_length in ICMP
2209 				 * errors.
2210 				 */
2211 				length -= hdr_length;
2212 			}
2213 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2214 				if (length > icmp_frag_size_table[i])
2215 					break;
2216 			}
2217 			if (i == A_CNT(icmp_frag_size_table)) {
2218 				/* Smaller than 68! */
2219 				disable_pmtud = B_TRUE;
2220 				mtu = ipst->ips_ip_pmtu_min;
2221 			} else {
2222 				mtu = icmp_frag_size_table[i];
2223 				if (mtu < ipst->ips_ip_pmtu_min) {
2224 					mtu = ipst->ips_ip_pmtu_min;
2225 					disable_pmtud = B_TRUE;
2226 				}
2227 			}
2228 			/* Fool the ULP into believing our guessed PMTU. */
2229 			icmph->icmph_du_zero = 0;
2230 			icmph->icmph_du_mtu = htons(mtu);
2231 		}
2232 		if (disable_pmtud)
2233 			ire->ire_frag_flag = 0;
2234 		/* Reduce the IRE max frag value as advised. */
2235 		ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2236 		mutex_exit(&ire->ire_lock);
2237 		DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, ire_t *,
2238 		    ire, int, orig_mtu, int, mtu);
2239 	}
2240 	rw_exit(&first_ire->ire_bucket->irb_lock);
2241 	ire_refrele(first_ire);
2242 	return (B_TRUE);
2243 }
2244 
2245 /*
2246  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2247  * calls this function.
2248  */
2249 static mblk_t *
2250 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2251 {
2252 	ipha_t *ipha;
2253 	icmph_t *icmph;
2254 	ipha_t *in_ipha;
2255 	int length;
2256 
2257 	ASSERT(mp->b_datap->db_type == M_DATA);
2258 
2259 	/*
2260 	 * For Self-encapsulated packets, we added an extra IP header
2261 	 * without the options. Inner IP header is the one from which
2262 	 * the outer IP header was formed. Thus, we need to remove the
2263 	 * outer IP header. To do this, we pullup the whole message
2264 	 * and overlay whatever follows the outer IP header over the
2265 	 * outer IP header.
2266 	 */
2267 
2268 	if (!pullupmsg(mp, -1))
2269 		return (NULL);
2270 
2271 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2272 	ipha = (ipha_t *)&icmph[1];
2273 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2274 
2275 	/*
2276 	 * The length that we want to overlay is following the inner
2277 	 * IP header. Subtracting the IP header + icmp header + outer
2278 	 * IP header's length should give us the length that we want to
2279 	 * overlay.
2280 	 */
2281 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2282 	    hdr_length;
2283 	/*
2284 	 * Overlay whatever follows the inner header over the
2285 	 * outer header.
2286 	 */
2287 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2288 
2289 	/* Set the wptr to account for the outer header */
2290 	mp->b_wptr -= hdr_length;
2291 	return (mp);
2292 }
2293 
2294 /*
2295  * Try to pass the ICMP message upstream in case the ULP cares.
2296  *
2297  * If the packet that caused the ICMP error is secure, we send
2298  * it to AH/ESP to make sure that the attached packet has a
2299  * valid association. ipha in the code below points to the
2300  * IP header of the packet that caused the error.
2301  *
2302  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2303  * in the context of IPsec. Normally we tell the upper layer
2304  * whenever we send the ire (including ip_bind), the IPsec header
2305  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2306  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2307  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2308  * same thing. As TCP has the IPsec options size that needs to be
2309  * adjusted, we just pass the MTU unchanged.
2310  *
2311  * IFN could have been generated locally or by some router.
2312  *
2313  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2314  *	    This happens because IP adjusted its value of MTU on an
2315  *	    earlier IFN message and could not tell the upper layer,
2316  *	    the new adjusted value of MTU e.g. Packet was encrypted
2317  *	    or there was not enough information to fanout to upper
2318  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2319  *	    generates the IFN, where IPsec processing has *not* been
2320  *	    done.
2321  *
2322  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2323  *	    could have generated this. This happens because ire_max_frag
2324  *	    value in IP was set to a new value, while the IPsec processing
2325  *	    was being done and after we made the fragmentation check in
2326  *	    ip_wput_ire. Thus on return from IPsec processing,
2327  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2328  *	    and generates the IFN. As IPsec processing is over, we fanout
2329  *	    to AH/ESP to remove the header.
2330  *
2331  *	    In both these cases, ipsec_in_loopback will be set indicating
2332  *	    that IFN was generated locally.
2333  *
2334  * ROUTER : IFN could be secure or non-secure.
2335  *
2336  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2337  *	      packet in error has AH/ESP headers to validate the AH/ESP
2338  *	      headers. AH/ESP will verify whether there is a valid SA or
2339  *	      not and send it back. We will fanout again if we have more
2340  *	      data in the packet.
2341  *
2342  *	      If the packet in error does not have AH/ESP, we handle it
2343  *	      like any other case.
2344  *
2345  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2346  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2347  *	      for validation. AH/ESP will verify whether there is a
2348  *	      valid SA or not and send it back. We will fanout again if
2349  *	      we have more data in the packet.
2350  *
2351  *	      If the packet in error does not have AH/ESP, we handle it
2352  *	      like any other case.
2353  */
2354 static void
2355 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2356     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2357     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2358     zoneid_t zoneid)
2359 {
2360 	uint16_t *up;	/* Pointer to ports in ULP header */
2361 	uint32_t ports;	/* reversed ports for fanout */
2362 	ipha_t ripha;	/* With reversed addresses */
2363 	mblk_t *first_mp;
2364 	ipsec_in_t *ii;
2365 	tcph_t	*tcph;
2366 	conn_t	*connp;
2367 	ip_stack_t *ipst;
2368 
2369 	ASSERT(ill != NULL);
2370 
2371 	ASSERT(recv_ill != NULL);
2372 	ipst = recv_ill->ill_ipst;
2373 
2374 	first_mp = mp;
2375 	if (mctl_present) {
2376 		mp = first_mp->b_cont;
2377 		ASSERT(mp != NULL);
2378 
2379 		ii = (ipsec_in_t *)first_mp->b_rptr;
2380 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2381 	} else {
2382 		ii = NULL;
2383 	}
2384 
2385 	switch (ipha->ipha_protocol) {
2386 	case IPPROTO_UDP:
2387 		/*
2388 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2389 		 * transport header.
2390 		 */
2391 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2392 		    mp->b_wptr) {
2393 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2394 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2395 				goto discard_pkt;
2396 			}
2397 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2398 			ipha = (ipha_t *)&icmph[1];
2399 		}
2400 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2401 
2402 		/*
2403 		 * Attempt to find a client stream based on port.
2404 		 * Note that we do a reverse lookup since the header is
2405 		 * in the form we sent it out.
2406 		 * The ripha header is only used for the IP_UDP_MATCH and we
2407 		 * only set the src and dst addresses and protocol.
2408 		 */
2409 		ripha.ipha_src = ipha->ipha_dst;
2410 		ripha.ipha_dst = ipha->ipha_src;
2411 		ripha.ipha_protocol = ipha->ipha_protocol;
2412 		((uint16_t *)&ports)[0] = up[1];
2413 		((uint16_t *)&ports)[1] = up[0];
2414 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2415 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2416 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2417 		    icmph->icmph_type, icmph->icmph_code));
2418 
2419 		/* Have to change db_type after any pullupmsg */
2420 		DB_TYPE(mp) = M_CTL;
2421 
2422 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2423 		    mctl_present, ip_policy, recv_ill, zoneid);
2424 		return;
2425 
2426 	case IPPROTO_TCP:
2427 		/*
2428 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2429 		 * transport header.
2430 		 */
2431 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2432 		    mp->b_wptr) {
2433 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2434 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2435 				goto discard_pkt;
2436 			}
2437 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2438 			ipha = (ipha_t *)&icmph[1];
2439 		}
2440 		/*
2441 		 * Find a TCP client stream for this packet.
2442 		 * Note that we do a reverse lookup since the header is
2443 		 * in the form we sent it out.
2444 		 */
2445 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2446 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2447 		    ipst);
2448 		if (connp == NULL)
2449 			goto discard_pkt;
2450 
2451 		/* Have to change db_type after any pullupmsg */
2452 		DB_TYPE(mp) = M_CTL;
2453 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, tcp_input, connp,
2454 		    SQ_FILL, SQTAG_TCP_INPUT_ICMP_ERR);
2455 		return;
2456 
2457 	case IPPROTO_SCTP:
2458 		/*
2459 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2460 		 * transport header.
2461 		 */
2462 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2463 		    mp->b_wptr) {
2464 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2465 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2466 				goto discard_pkt;
2467 			}
2468 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2469 			ipha = (ipha_t *)&icmph[1];
2470 		}
2471 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2472 		/*
2473 		 * Find a SCTP client stream for this packet.
2474 		 * Note that we do a reverse lookup since the header is
2475 		 * in the form we sent it out.
2476 		 * The ripha header is only used for the matching and we
2477 		 * only set the src and dst addresses, protocol, and version.
2478 		 */
2479 		ripha.ipha_src = ipha->ipha_dst;
2480 		ripha.ipha_dst = ipha->ipha_src;
2481 		ripha.ipha_protocol = ipha->ipha_protocol;
2482 		ripha.ipha_version_and_hdr_length =
2483 		    ipha->ipha_version_and_hdr_length;
2484 		((uint16_t *)&ports)[0] = up[1];
2485 		((uint16_t *)&ports)[1] = up[0];
2486 
2487 		/* Have to change db_type after any pullupmsg */
2488 		DB_TYPE(mp) = M_CTL;
2489 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2490 		    mctl_present, ip_policy, zoneid);
2491 		return;
2492 
2493 	case IPPROTO_ESP:
2494 	case IPPROTO_AH: {
2495 		int ipsec_rc;
2496 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2497 
2498 		/*
2499 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2500 		 * We will re-use the IPSEC_IN if it is already present as
2501 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2502 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2503 		 * one and attach it in the front.
2504 		 */
2505 		if (ii != NULL) {
2506 			/*
2507 			 * ip_fanout_proto_again converts the ICMP errors
2508 			 * that come back from AH/ESP to M_DATA so that
2509 			 * if it is non-AH/ESP and we do a pullupmsg in
2510 			 * this function, it would work. Convert it back
2511 			 * to M_CTL before we send up as this is a ICMP
2512 			 * error. This could have been generated locally or
2513 			 * by some router. Validate the inner IPsec
2514 			 * headers.
2515 			 *
2516 			 * NOTE : ill_index is used by ip_fanout_proto_again
2517 			 * to locate the ill.
2518 			 */
2519 			ASSERT(ill != NULL);
2520 			ii->ipsec_in_ill_index =
2521 			    ill->ill_phyint->phyint_ifindex;
2522 			ii->ipsec_in_rill_index =
2523 			    recv_ill->ill_phyint->phyint_ifindex;
2524 			DB_TYPE(first_mp->b_cont) = M_CTL;
2525 		} else {
2526 			/*
2527 			 * IPSEC_IN is not present. We attach a ipsec_in
2528 			 * message and send up to IPsec for validating
2529 			 * and removing the IPsec headers. Clear
2530 			 * ipsec_in_secure so that when we return
2531 			 * from IPsec, we don't mistakenly think that this
2532 			 * is a secure packet came from the network.
2533 			 *
2534 			 * NOTE : ill_index is used by ip_fanout_proto_again
2535 			 * to locate the ill.
2536 			 */
2537 			ASSERT(first_mp == mp);
2538 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2539 			if (first_mp == NULL) {
2540 				freemsg(mp);
2541 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2542 				return;
2543 			}
2544 			ii = (ipsec_in_t *)first_mp->b_rptr;
2545 
2546 			/* This is not a secure packet */
2547 			ii->ipsec_in_secure = B_FALSE;
2548 			first_mp->b_cont = mp;
2549 			DB_TYPE(mp) = M_CTL;
2550 			ASSERT(ill != NULL);
2551 			ii->ipsec_in_ill_index =
2552 			    ill->ill_phyint->phyint_ifindex;
2553 			ii->ipsec_in_rill_index =
2554 			    recv_ill->ill_phyint->phyint_ifindex;
2555 		}
2556 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2557 
2558 		if (!ipsec_loaded(ipss)) {
2559 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2560 			return;
2561 		}
2562 
2563 		if (ipha->ipha_protocol == IPPROTO_ESP)
2564 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2565 		else
2566 			ipsec_rc = ipsecah_icmp_error(first_mp);
2567 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2568 			return;
2569 
2570 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2571 		return;
2572 	}
2573 	default:
2574 		/*
2575 		 * The ripha header is only used for the lookup and we
2576 		 * only set the src and dst addresses and protocol.
2577 		 */
2578 		ripha.ipha_src = ipha->ipha_dst;
2579 		ripha.ipha_dst = ipha->ipha_src;
2580 		ripha.ipha_protocol = ipha->ipha_protocol;
2581 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2582 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2583 		    ntohl(ipha->ipha_dst),
2584 		    icmph->icmph_type, icmph->icmph_code));
2585 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2586 			ipha_t *in_ipha;
2587 
2588 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2589 			    mp->b_wptr) {
2590 				if (!pullupmsg(mp, (uchar_t *)ipha +
2591 				    hdr_length + sizeof (ipha_t) -
2592 				    mp->b_rptr)) {
2593 					goto discard_pkt;
2594 				}
2595 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2596 				ipha = (ipha_t *)&icmph[1];
2597 			}
2598 			/*
2599 			 * Caller has verified that length has to be
2600 			 * at least the size of IP header.
2601 			 */
2602 			ASSERT(hdr_length >= sizeof (ipha_t));
2603 			/*
2604 			 * Check the sanity of the inner IP header like
2605 			 * we did for the outer header.
2606 			 */
2607 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2608 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2609 				goto discard_pkt;
2610 			}
2611 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2612 				goto discard_pkt;
2613 			}
2614 			/* Check for Self-encapsulated tunnels */
2615 			if (in_ipha->ipha_src == ipha->ipha_src &&
2616 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2617 
2618 				mp = icmp_inbound_self_encap_error(mp,
2619 				    iph_hdr_length, hdr_length);
2620 				if (mp == NULL)
2621 					goto discard_pkt;
2622 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2623 				ipha = (ipha_t *)&icmph[1];
2624 				hdr_length = IPH_HDR_LENGTH(ipha);
2625 				/*
2626 				 * The packet in error is self-encapsualted.
2627 				 * And we are finding it further encapsulated
2628 				 * which we could not have possibly generated.
2629 				 */
2630 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2631 					goto discard_pkt;
2632 				}
2633 				icmp_inbound_error_fanout(q, ill, first_mp,
2634 				    icmph, ipha, iph_hdr_length, hdr_length,
2635 				    mctl_present, ip_policy, recv_ill, zoneid);
2636 				return;
2637 			}
2638 		}
2639 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2640 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2641 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2642 		    ii != NULL &&
2643 		    ii->ipsec_in_loopback &&
2644 		    ii->ipsec_in_secure) {
2645 			/*
2646 			 * For IP tunnels that get a looped-back
2647 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2648 			 * reported new MTU to take into account the IPsec
2649 			 * headers protecting this configured tunnel.
2650 			 *
2651 			 * This allows the tunnel module (tun.c) to blindly
2652 			 * accept the MTU reported in an ICMP "too big"
2653 			 * message.
2654 			 *
2655 			 * Non-looped back ICMP messages will just be
2656 			 * handled by the security protocols (if needed),
2657 			 * and the first subsequent packet will hit this
2658 			 * path.
2659 			 */
2660 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2661 			    ipsec_in_extra_length(first_mp));
2662 		}
2663 		/* Have to change db_type after any pullupmsg */
2664 		DB_TYPE(mp) = M_CTL;
2665 
2666 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2667 		    ip_policy, recv_ill, zoneid);
2668 		return;
2669 	}
2670 	/* NOTREACHED */
2671 discard_pkt:
2672 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2673 drop_pkt:;
2674 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2675 	freemsg(first_mp);
2676 }
2677 
2678 /*
2679  * Common IP options parser.
2680  *
2681  * Setup routine: fill in *optp with options-parsing state, then
2682  * tail-call ipoptp_next to return the first option.
2683  */
2684 uint8_t
2685 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2686 {
2687 	uint32_t totallen; /* total length of all options */
2688 
2689 	totallen = ipha->ipha_version_and_hdr_length -
2690 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2691 	totallen <<= 2;
2692 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2693 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2694 	optp->ipoptp_flags = 0;
2695 	return (ipoptp_next(optp));
2696 }
2697 
2698 /*
2699  * Common IP options parser: extract next option.
2700  */
2701 uint8_t
2702 ipoptp_next(ipoptp_t *optp)
2703 {
2704 	uint8_t *end = optp->ipoptp_end;
2705 	uint8_t *cur = optp->ipoptp_next;
2706 	uint8_t opt, len, pointer;
2707 
2708 	/*
2709 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2710 	 * has been corrupted.
2711 	 */
2712 	ASSERT(cur <= end);
2713 
2714 	if (cur == end)
2715 		return (IPOPT_EOL);
2716 
2717 	opt = cur[IPOPT_OPTVAL];
2718 
2719 	/*
2720 	 * Skip any NOP options.
2721 	 */
2722 	while (opt == IPOPT_NOP) {
2723 		cur++;
2724 		if (cur == end)
2725 			return (IPOPT_EOL);
2726 		opt = cur[IPOPT_OPTVAL];
2727 	}
2728 
2729 	if (opt == IPOPT_EOL)
2730 		return (IPOPT_EOL);
2731 
2732 	/*
2733 	 * Option requiring a length.
2734 	 */
2735 	if ((cur + 1) >= end) {
2736 		optp->ipoptp_flags |= IPOPTP_ERROR;
2737 		return (IPOPT_EOL);
2738 	}
2739 	len = cur[IPOPT_OLEN];
2740 	if (len < 2) {
2741 		optp->ipoptp_flags |= IPOPTP_ERROR;
2742 		return (IPOPT_EOL);
2743 	}
2744 	optp->ipoptp_cur = cur;
2745 	optp->ipoptp_len = len;
2746 	optp->ipoptp_next = cur + len;
2747 	if (cur + len > end) {
2748 		optp->ipoptp_flags |= IPOPTP_ERROR;
2749 		return (IPOPT_EOL);
2750 	}
2751 
2752 	/*
2753 	 * For the options which require a pointer field, make sure
2754 	 * its there, and make sure it points to either something
2755 	 * inside this option, or the end of the option.
2756 	 */
2757 	switch (opt) {
2758 	case IPOPT_RR:
2759 	case IPOPT_TS:
2760 	case IPOPT_LSRR:
2761 	case IPOPT_SSRR:
2762 		if (len <= IPOPT_OFFSET) {
2763 			optp->ipoptp_flags |= IPOPTP_ERROR;
2764 			return (opt);
2765 		}
2766 		pointer = cur[IPOPT_OFFSET];
2767 		if (pointer - 1 > len) {
2768 			optp->ipoptp_flags |= IPOPTP_ERROR;
2769 			return (opt);
2770 		}
2771 		break;
2772 	}
2773 
2774 	/*
2775 	 * Sanity check the pointer field based on the type of the
2776 	 * option.
2777 	 */
2778 	switch (opt) {
2779 	case IPOPT_RR:
2780 	case IPOPT_SSRR:
2781 	case IPOPT_LSRR:
2782 		if (pointer < IPOPT_MINOFF_SR)
2783 			optp->ipoptp_flags |= IPOPTP_ERROR;
2784 		break;
2785 	case IPOPT_TS:
2786 		if (pointer < IPOPT_MINOFF_IT)
2787 			optp->ipoptp_flags |= IPOPTP_ERROR;
2788 		/*
2789 		 * Note that the Internet Timestamp option also
2790 		 * contains two four bit fields (the Overflow field,
2791 		 * and the Flag field), which follow the pointer
2792 		 * field.  We don't need to check that these fields
2793 		 * fall within the length of the option because this
2794 		 * was implicitely done above.  We've checked that the
2795 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2796 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2797 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2798 		 */
2799 		ASSERT(len > IPOPT_POS_OV_FLG);
2800 		break;
2801 	}
2802 
2803 	return (opt);
2804 }
2805 
2806 /*
2807  * Use the outgoing IP header to create an IP_OPTIONS option the way
2808  * it was passed down from the application.
2809  */
2810 int
2811 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2812 {
2813 	ipoptp_t	opts;
2814 	const uchar_t	*opt;
2815 	uint8_t		optval;
2816 	uint8_t		optlen;
2817 	uint32_t	len = 0;
2818 	uchar_t	*buf1 = buf;
2819 
2820 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2821 	len += IP_ADDR_LEN;
2822 	bzero(buf1, IP_ADDR_LEN);
2823 
2824 	/*
2825 	 * OK to cast away const here, as we don't store through the returned
2826 	 * opts.ipoptp_cur pointer.
2827 	 */
2828 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2829 	    optval != IPOPT_EOL;
2830 	    optval = ipoptp_next(&opts)) {
2831 		int	off;
2832 
2833 		opt = opts.ipoptp_cur;
2834 		optlen = opts.ipoptp_len;
2835 		switch (optval) {
2836 		case IPOPT_SSRR:
2837 		case IPOPT_LSRR:
2838 
2839 			/*
2840 			 * Insert ipha_dst as the first entry in the source
2841 			 * route and move down the entries on step.
2842 			 * The last entry gets placed at buf1.
2843 			 */
2844 			buf[IPOPT_OPTVAL] = optval;
2845 			buf[IPOPT_OLEN] = optlen;
2846 			buf[IPOPT_OFFSET] = optlen;
2847 
2848 			off = optlen - IP_ADDR_LEN;
2849 			if (off < 0) {
2850 				/* No entries in source route */
2851 				break;
2852 			}
2853 			/* Last entry in source route */
2854 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2855 			off -= IP_ADDR_LEN;
2856 
2857 			while (off > 0) {
2858 				bcopy(opt + off,
2859 				    buf + off + IP_ADDR_LEN,
2860 				    IP_ADDR_LEN);
2861 				off -= IP_ADDR_LEN;
2862 			}
2863 			/* ipha_dst into first slot */
2864 			bcopy(&ipha->ipha_dst,
2865 			    buf + off + IP_ADDR_LEN,
2866 			    IP_ADDR_LEN);
2867 			buf += optlen;
2868 			len += optlen;
2869 			break;
2870 
2871 		case IPOPT_COMSEC:
2872 		case IPOPT_SECURITY:
2873 			/* if passing up a label is not ok, then remove */
2874 			if (is_system_labeled())
2875 				break;
2876 			/* FALLTHROUGH */
2877 		default:
2878 			bcopy(opt, buf, optlen);
2879 			buf += optlen;
2880 			len += optlen;
2881 			break;
2882 		}
2883 	}
2884 done:
2885 	/* Pad the resulting options */
2886 	while (len & 0x3) {
2887 		*buf++ = IPOPT_EOL;
2888 		len++;
2889 	}
2890 	return (len);
2891 }
2892 
2893 /*
2894  * Update any record route or timestamp options to include this host.
2895  * Reverse any source route option.
2896  * This routine assumes that the options are well formed i.e. that they
2897  * have already been checked.
2898  */
2899 static void
2900 icmp_options_update(ipha_t *ipha)
2901 {
2902 	ipoptp_t	opts;
2903 	uchar_t		*opt;
2904 	uint8_t		optval;
2905 	ipaddr_t	src;		/* Our local address */
2906 	ipaddr_t	dst;
2907 
2908 	ip2dbg(("icmp_options_update\n"));
2909 	src = ipha->ipha_src;
2910 	dst = ipha->ipha_dst;
2911 
2912 	for (optval = ipoptp_first(&opts, ipha);
2913 	    optval != IPOPT_EOL;
2914 	    optval = ipoptp_next(&opts)) {
2915 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2916 		opt = opts.ipoptp_cur;
2917 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2918 		    optval, opts.ipoptp_len));
2919 		switch (optval) {
2920 			int off1, off2;
2921 		case IPOPT_SSRR:
2922 		case IPOPT_LSRR:
2923 			/*
2924 			 * Reverse the source route.  The first entry
2925 			 * should be the next to last one in the current
2926 			 * source route (the last entry is our address).
2927 			 * The last entry should be the final destination.
2928 			 */
2929 			off1 = IPOPT_MINOFF_SR - 1;
2930 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2931 			if (off2 < 0) {
2932 				/* No entries in source route */
2933 				ip1dbg((
2934 				    "icmp_options_update: bad src route\n"));
2935 				break;
2936 			}
2937 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
2938 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
2939 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
2940 			off2 -= IP_ADDR_LEN;
2941 
2942 			while (off1 < off2) {
2943 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
2944 				bcopy((char *)opt + off2, (char *)opt + off1,
2945 				    IP_ADDR_LEN);
2946 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
2947 				off1 += IP_ADDR_LEN;
2948 				off2 -= IP_ADDR_LEN;
2949 			}
2950 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
2951 			break;
2952 		}
2953 	}
2954 }
2955 
2956 /*
2957  * Process received ICMP Redirect messages.
2958  */
2959 static void
2960 icmp_redirect(ill_t *ill, mblk_t *mp)
2961 {
2962 	ipha_t	*ipha;
2963 	int	iph_hdr_length;
2964 	icmph_t	*icmph;
2965 	ipha_t	*ipha_err;
2966 	ire_t	*ire;
2967 	ire_t	*prev_ire;
2968 	ire_t	*save_ire;
2969 	ipaddr_t  src, dst, gateway;
2970 	iulp_t	ulp_info = { 0 };
2971 	int	error;
2972 	ip_stack_t *ipst;
2973 
2974 	ASSERT(ill != NULL);
2975 	ipst = ill->ill_ipst;
2976 
2977 	ipha = (ipha_t *)mp->b_rptr;
2978 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
2979 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
2980 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
2981 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
2982 		freemsg(mp);
2983 		return;
2984 	}
2985 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2986 	ipha_err = (ipha_t *)&icmph[1];
2987 	src = ipha->ipha_src;
2988 	dst = ipha_err->ipha_dst;
2989 	gateway = icmph->icmph_rd_gateway;
2990 	/* Make sure the new gateway is reachable somehow. */
2991 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
2992 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2993 	/*
2994 	 * Make sure we had a route for the dest in question and that
2995 	 * that route was pointing to the old gateway (the source of the
2996 	 * redirect packet.)
2997 	 */
2998 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
2999 	    NULL, MATCH_IRE_GW, ipst);
3000 	/*
3001 	 * Check that
3002 	 *	the redirect was not from ourselves
3003 	 *	the new gateway and the old gateway are directly reachable
3004 	 */
3005 	if (!prev_ire ||
3006 	    !ire ||
3007 	    ire->ire_type == IRE_LOCAL) {
3008 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3009 		freemsg(mp);
3010 		if (ire != NULL)
3011 			ire_refrele(ire);
3012 		if (prev_ire != NULL)
3013 			ire_refrele(prev_ire);
3014 		return;
3015 	}
3016 
3017 	/*
3018 	 * Should we use the old ULP info to create the new gateway?  From
3019 	 * a user's perspective, we should inherit the info so that it
3020 	 * is a "smooth" transition.  If we do not do that, then new
3021 	 * connections going thru the new gateway will have no route metrics,
3022 	 * which is counter-intuitive to user.  From a network point of
3023 	 * view, this may or may not make sense even though the new gateway
3024 	 * is still directly connected to us so the route metrics should not
3025 	 * change much.
3026 	 *
3027 	 * But if the old ire_uinfo is not initialized, we do another
3028 	 * recursive lookup on the dest using the new gateway.  There may
3029 	 * be a route to that.  If so, use it to initialize the redirect
3030 	 * route.
3031 	 */
3032 	if (prev_ire->ire_uinfo.iulp_set) {
3033 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3034 	} else {
3035 		ire_t *tmp_ire;
3036 		ire_t *sire;
3037 
3038 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3039 		    ALL_ZONES, 0, NULL,
3040 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3041 		    ipst);
3042 		if (sire != NULL) {
3043 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3044 			/*
3045 			 * If sire != NULL, ire_ftable_lookup() should not
3046 			 * return a NULL value.
3047 			 */
3048 			ASSERT(tmp_ire != NULL);
3049 			ire_refrele(tmp_ire);
3050 			ire_refrele(sire);
3051 		} else if (tmp_ire != NULL) {
3052 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3053 			    sizeof (iulp_t));
3054 			ire_refrele(tmp_ire);
3055 		}
3056 	}
3057 	if (prev_ire->ire_type == IRE_CACHE)
3058 		ire_delete(prev_ire);
3059 	ire_refrele(prev_ire);
3060 	/*
3061 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3062 	 * require TOS routing
3063 	 */
3064 	switch (icmph->icmph_code) {
3065 	case 0:
3066 	case 1:
3067 		/* TODO: TOS specificity for cases 2 and 3 */
3068 	case 2:
3069 	case 3:
3070 		break;
3071 	default:
3072 		freemsg(mp);
3073 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3074 		ire_refrele(ire);
3075 		return;
3076 	}
3077 	/*
3078 	 * Create a Route Association.  This will allow us to remember that
3079 	 * someone we believe told us to use the particular gateway.
3080 	 */
3081 	save_ire = ire;
3082 	ire = ire_create(
3083 	    (uchar_t *)&dst,			/* dest addr */
3084 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3085 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3086 	    (uchar_t *)&gateway,		/* gateway addr */
3087 	    &save_ire->ire_max_frag,		/* max frag */
3088 	    NULL,				/* no src nce */
3089 	    NULL,				/* no rfq */
3090 	    NULL,				/* no stq */
3091 	    IRE_HOST,
3092 	    NULL,				/* ipif */
3093 	    0,					/* cmask */
3094 	    0,					/* phandle */
3095 	    0,					/* ihandle */
3096 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3097 	    &ulp_info,
3098 	    NULL,				/* tsol_gc_t */
3099 	    NULL,				/* gcgrp */
3100 	    ipst);
3101 
3102 	if (ire == NULL) {
3103 		freemsg(mp);
3104 		ire_refrele(save_ire);
3105 		return;
3106 	}
3107 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3108 	ire_refrele(save_ire);
3109 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3110 
3111 	if (error == 0) {
3112 		ire_refrele(ire);		/* Held in ire_add_v4 */
3113 		/* tell routing sockets that we received a redirect */
3114 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3115 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3116 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3117 	}
3118 
3119 	/*
3120 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3121 	 * This together with the added IRE has the effect of
3122 	 * modifying an existing redirect.
3123 	 */
3124 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3125 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3126 	if (prev_ire != NULL) {
3127 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3128 			ire_delete(prev_ire);
3129 		ire_refrele(prev_ire);
3130 	}
3131 
3132 	freemsg(mp);
3133 }
3134 
3135 /*
3136  * Generate an ICMP parameter problem message.
3137  */
3138 static void
3139 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3140 	ip_stack_t *ipst)
3141 {
3142 	icmph_t	icmph;
3143 	boolean_t mctl_present;
3144 	mblk_t *first_mp;
3145 
3146 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3147 
3148 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3149 		if (mctl_present)
3150 			freeb(first_mp);
3151 		return;
3152 	}
3153 
3154 	bzero(&icmph, sizeof (icmph_t));
3155 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3156 	icmph.icmph_pp_ptr = ptr;
3157 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3158 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3159 	    ipst);
3160 }
3161 
3162 /*
3163  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3164  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3165  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3166  * an icmp error packet can be sent.
3167  * Assigns an appropriate source address to the packet. If ipha_dst is
3168  * one of our addresses use it for source. Otherwise pick a source based
3169  * on a route lookup back to ipha_src.
3170  * Note that ipha_src must be set here since the
3171  * packet is likely to arrive on an ill queue in ip_wput() which will
3172  * not set a source address.
3173  */
3174 static void
3175 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3176     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3177 {
3178 	ipaddr_t dst;
3179 	icmph_t	*icmph;
3180 	ipha_t	*ipha;
3181 	uint_t	len_needed;
3182 	size_t	msg_len;
3183 	mblk_t	*mp1;
3184 	ipaddr_t src;
3185 	ire_t	*ire;
3186 	mblk_t *ipsec_mp;
3187 	ipsec_out_t	*io = NULL;
3188 
3189 	if (mctl_present) {
3190 		/*
3191 		 * If it is :
3192 		 *
3193 		 * 1) a IPSEC_OUT, then this is caused by outbound
3194 		 *    datagram originating on this host. IPsec processing
3195 		 *    may or may not have been done. Refer to comments above
3196 		 *    icmp_inbound_error_fanout for details.
3197 		 *
3198 		 * 2) a IPSEC_IN if we are generating a icmp_message
3199 		 *    for an incoming datagram destined for us i.e called
3200 		 *    from ip_fanout_send_icmp.
3201 		 */
3202 		ipsec_info_t *in;
3203 		ipsec_mp = mp;
3204 		mp = ipsec_mp->b_cont;
3205 
3206 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3207 		ipha = (ipha_t *)mp->b_rptr;
3208 
3209 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3210 		    in->ipsec_info_type == IPSEC_IN);
3211 
3212 		if (in->ipsec_info_type == IPSEC_IN) {
3213 			/*
3214 			 * Convert the IPSEC_IN to IPSEC_OUT.
3215 			 */
3216 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3217 				BUMP_MIB(&ipst->ips_ip_mib,
3218 				    ipIfStatsOutDiscards);
3219 				return;
3220 			}
3221 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3222 		} else {
3223 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3224 			io = (ipsec_out_t *)in;
3225 			/*
3226 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3227 			 * ire lookup.
3228 			 */
3229 			io->ipsec_out_proc_begin = B_FALSE;
3230 		}
3231 		ASSERT(zoneid == io->ipsec_out_zoneid);
3232 		ASSERT(zoneid != ALL_ZONES);
3233 	} else {
3234 		/*
3235 		 * This is in clear. The icmp message we are building
3236 		 * here should go out in clear.
3237 		 *
3238 		 * Pardon the convolution of it all, but it's easier to
3239 		 * allocate a "use cleartext" IPSEC_IN message and convert
3240 		 * it than it is to allocate a new one.
3241 		 */
3242 		ipsec_in_t *ii;
3243 		ASSERT(DB_TYPE(mp) == M_DATA);
3244 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3245 		if (ipsec_mp == NULL) {
3246 			freemsg(mp);
3247 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3248 			return;
3249 		}
3250 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3251 
3252 		/* This is not a secure packet */
3253 		ii->ipsec_in_secure = B_FALSE;
3254 		/*
3255 		 * For trusted extensions using a shared IP address we can
3256 		 * send using any zoneid.
3257 		 */
3258 		if (zoneid == ALL_ZONES)
3259 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3260 		else
3261 			ii->ipsec_in_zoneid = zoneid;
3262 		ipsec_mp->b_cont = mp;
3263 		ipha = (ipha_t *)mp->b_rptr;
3264 		/*
3265 		 * Convert the IPSEC_IN to IPSEC_OUT.
3266 		 */
3267 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3268 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3269 			return;
3270 		}
3271 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3272 	}
3273 
3274 	/* Remember our eventual destination */
3275 	dst = ipha->ipha_src;
3276 
3277 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3278 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3279 	if (ire != NULL &&
3280 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3281 		src = ipha->ipha_dst;
3282 	} else {
3283 		if (ire != NULL)
3284 			ire_refrele(ire);
3285 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3286 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3287 		    ipst);
3288 		if (ire == NULL) {
3289 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3290 			freemsg(ipsec_mp);
3291 			return;
3292 		}
3293 		src = ire->ire_src_addr;
3294 	}
3295 
3296 	if (ire != NULL)
3297 		ire_refrele(ire);
3298 
3299 	/*
3300 	 * Check if we can send back more then 8 bytes in addition to
3301 	 * the IP header.  We try to send 64 bytes of data and the internal
3302 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3303 	 */
3304 	len_needed = IPH_HDR_LENGTH(ipha);
3305 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3306 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3307 
3308 		if (!pullupmsg(mp, -1)) {
3309 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3310 			freemsg(ipsec_mp);
3311 			return;
3312 		}
3313 		ipha = (ipha_t *)mp->b_rptr;
3314 
3315 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3316 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3317 			    len_needed));
3318 		} else {
3319 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3320 
3321 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3322 			len_needed += ip_hdr_length_v6(mp, ip6h);
3323 		}
3324 	}
3325 	len_needed += ipst->ips_ip_icmp_return;
3326 	msg_len = msgdsize(mp);
3327 	if (msg_len > len_needed) {
3328 		(void) adjmsg(mp, len_needed - msg_len);
3329 		msg_len = len_needed;
3330 	}
3331 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3332 	if (mp1 == NULL) {
3333 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3334 		freemsg(ipsec_mp);
3335 		return;
3336 	}
3337 	mp1->b_cont = mp;
3338 	mp = mp1;
3339 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3340 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3341 	    io->ipsec_out_type == IPSEC_OUT);
3342 	ipsec_mp->b_cont = mp;
3343 
3344 	/*
3345 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3346 	 * node generates be accepted in peace by all on-host destinations.
3347 	 * If we do NOT assume that all on-host destinations trust
3348 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3349 	 * (Look for ipsec_out_icmp_loopback).
3350 	 */
3351 	io->ipsec_out_icmp_loopback = B_TRUE;
3352 
3353 	ipha = (ipha_t *)mp->b_rptr;
3354 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3355 	*ipha = icmp_ipha;
3356 	ipha->ipha_src = src;
3357 	ipha->ipha_dst = dst;
3358 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3359 	msg_len += sizeof (icmp_ipha) + len;
3360 	if (msg_len > IP_MAXPACKET) {
3361 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3362 		msg_len = IP_MAXPACKET;
3363 	}
3364 	ipha->ipha_length = htons((uint16_t)msg_len);
3365 	icmph = (icmph_t *)&ipha[1];
3366 	bcopy(stuff, icmph, len);
3367 	icmph->icmph_checksum = 0;
3368 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3369 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3370 	put(q, ipsec_mp);
3371 }
3372 
3373 /*
3374  * Determine if an ICMP error packet can be sent given the rate limit.
3375  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3376  * in milliseconds) and a burst size. Burst size number of packets can
3377  * be sent arbitrarely closely spaced.
3378  * The state is tracked using two variables to implement an approximate
3379  * token bucket filter:
3380  *	icmp_pkt_err_last - lbolt value when the last burst started
3381  *	icmp_pkt_err_sent - number of packets sent in current burst
3382  */
3383 boolean_t
3384 icmp_err_rate_limit(ip_stack_t *ipst)
3385 {
3386 	clock_t now = TICK_TO_MSEC(lbolt);
3387 	uint_t refilled; /* Number of packets refilled in tbf since last */
3388 	/* Guard against changes by loading into local variable */
3389 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3390 
3391 	if (err_interval == 0)
3392 		return (B_FALSE);
3393 
3394 	if (ipst->ips_icmp_pkt_err_last > now) {
3395 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3396 		ipst->ips_icmp_pkt_err_last = 0;
3397 		ipst->ips_icmp_pkt_err_sent = 0;
3398 	}
3399 	/*
3400 	 * If we are in a burst update the token bucket filter.
3401 	 * Update the "last" time to be close to "now" but make sure
3402 	 * we don't loose precision.
3403 	 */
3404 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3405 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3406 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3407 			ipst->ips_icmp_pkt_err_sent = 0;
3408 		} else {
3409 			ipst->ips_icmp_pkt_err_sent -= refilled;
3410 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3411 		}
3412 	}
3413 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3414 		/* Start of new burst */
3415 		ipst->ips_icmp_pkt_err_last = now;
3416 	}
3417 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3418 		ipst->ips_icmp_pkt_err_sent++;
3419 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3420 		    ipst->ips_icmp_pkt_err_sent));
3421 		return (B_FALSE);
3422 	}
3423 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3424 	return (B_TRUE);
3425 }
3426 
3427 /*
3428  * Check if it is ok to send an IPv4 ICMP error packet in
3429  * response to the IPv4 packet in mp.
3430  * Free the message and return null if no
3431  * ICMP error packet should be sent.
3432  */
3433 static mblk_t *
3434 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3435 {
3436 	icmph_t	*icmph;
3437 	ipha_t	*ipha;
3438 	uint_t	len_needed;
3439 	ire_t	*src_ire;
3440 	ire_t	*dst_ire;
3441 
3442 	if (!mp)
3443 		return (NULL);
3444 	ipha = (ipha_t *)mp->b_rptr;
3445 	if (ip_csum_hdr(ipha)) {
3446 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3447 		freemsg(mp);
3448 		return (NULL);
3449 	}
3450 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3451 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3452 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3453 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3454 	if (src_ire != NULL || dst_ire != NULL ||
3455 	    CLASSD(ipha->ipha_dst) ||
3456 	    CLASSD(ipha->ipha_src) ||
3457 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3458 		/* Note: only errors to the fragment with offset 0 */
3459 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3460 		freemsg(mp);
3461 		if (src_ire != NULL)
3462 			ire_refrele(src_ire);
3463 		if (dst_ire != NULL)
3464 			ire_refrele(dst_ire);
3465 		return (NULL);
3466 	}
3467 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3468 		/*
3469 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3470 		 * errors in response to any ICMP errors.
3471 		 */
3472 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3473 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3474 			if (!pullupmsg(mp, len_needed)) {
3475 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3476 				freemsg(mp);
3477 				return (NULL);
3478 			}
3479 			ipha = (ipha_t *)mp->b_rptr;
3480 		}
3481 		icmph = (icmph_t *)
3482 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3483 		switch (icmph->icmph_type) {
3484 		case ICMP_DEST_UNREACHABLE:
3485 		case ICMP_SOURCE_QUENCH:
3486 		case ICMP_TIME_EXCEEDED:
3487 		case ICMP_PARAM_PROBLEM:
3488 		case ICMP_REDIRECT:
3489 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3490 			freemsg(mp);
3491 			return (NULL);
3492 		default:
3493 			break;
3494 		}
3495 	}
3496 	/*
3497 	 * If this is a labeled system, then check to see if we're allowed to
3498 	 * send a response to this particular sender.  If not, then just drop.
3499 	 */
3500 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3501 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3502 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3503 		freemsg(mp);
3504 		return (NULL);
3505 	}
3506 	if (icmp_err_rate_limit(ipst)) {
3507 		/*
3508 		 * Only send ICMP error packets every so often.
3509 		 * This should be done on a per port/source basis,
3510 		 * but for now this will suffice.
3511 		 */
3512 		freemsg(mp);
3513 		return (NULL);
3514 	}
3515 	return (mp);
3516 }
3517 
3518 /*
3519  * Generate an ICMP redirect message.
3520  */
3521 static void
3522 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3523 {
3524 	icmph_t	icmph;
3525 
3526 	/*
3527 	 * We are called from ip_rput where we could
3528 	 * not have attached an IPSEC_IN.
3529 	 */
3530 	ASSERT(mp->b_datap->db_type == M_DATA);
3531 
3532 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3533 		return;
3534 	}
3535 
3536 	bzero(&icmph, sizeof (icmph_t));
3537 	icmph.icmph_type = ICMP_REDIRECT;
3538 	icmph.icmph_code = 1;
3539 	icmph.icmph_rd_gateway = gateway;
3540 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3541 	/* Redirects sent by router, and router is global zone */
3542 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3543 }
3544 
3545 /*
3546  * Generate an ICMP time exceeded message.
3547  */
3548 void
3549 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3550     ip_stack_t *ipst)
3551 {
3552 	icmph_t	icmph;
3553 	boolean_t mctl_present;
3554 	mblk_t *first_mp;
3555 
3556 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3557 
3558 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3559 		if (mctl_present)
3560 			freeb(first_mp);
3561 		return;
3562 	}
3563 
3564 	bzero(&icmph, sizeof (icmph_t));
3565 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3566 	icmph.icmph_code = code;
3567 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3568 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3569 	    ipst);
3570 }
3571 
3572 /*
3573  * Generate an ICMP unreachable message.
3574  */
3575 void
3576 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3577     ip_stack_t *ipst)
3578 {
3579 	icmph_t	icmph;
3580 	mblk_t *first_mp;
3581 	boolean_t mctl_present;
3582 
3583 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3584 
3585 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3586 		if (mctl_present)
3587 			freeb(first_mp);
3588 		return;
3589 	}
3590 
3591 	bzero(&icmph, sizeof (icmph_t));
3592 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3593 	icmph.icmph_code = code;
3594 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3595 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3596 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3597 	    zoneid, ipst);
3598 }
3599 
3600 /*
3601  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3602  * duplicate.  As long as someone else holds the address, the interface will
3603  * stay down.  When that conflict goes away, the interface is brought back up.
3604  * This is done so that accidental shutdowns of addresses aren't made
3605  * permanent.  Your server will recover from a failure.
3606  *
3607  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3608  * user space process (dhcpagent).
3609  *
3610  * Recovery completes if ARP reports that the address is now ours (via
3611  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3612  *
3613  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3614  */
3615 static void
3616 ipif_dup_recovery(void *arg)
3617 {
3618 	ipif_t *ipif = arg;
3619 	ill_t *ill = ipif->ipif_ill;
3620 	mblk_t *arp_add_mp;
3621 	mblk_t *arp_del_mp;
3622 	ip_stack_t *ipst = ill->ill_ipst;
3623 
3624 	ipif->ipif_recovery_id = 0;
3625 
3626 	/*
3627 	 * No lock needed for moving or condemned check, as this is just an
3628 	 * optimization.
3629 	 */
3630 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3631 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3632 	    (ipif->ipif_state_flags & (IPIF_CONDEMNED))) {
3633 		/* No reason to try to bring this address back. */
3634 		return;
3635 	}
3636 
3637 	/* ACE_F_UNVERIFIED restarts DAD */
3638 	if ((arp_add_mp = ipif_area_alloc(ipif, ACE_F_UNVERIFIED)) == NULL)
3639 		goto alloc_fail;
3640 
3641 	if (ipif->ipif_arp_del_mp == NULL) {
3642 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3643 			goto alloc_fail;
3644 		ipif->ipif_arp_del_mp = arp_del_mp;
3645 	}
3646 
3647 	putnext(ill->ill_rq, arp_add_mp);
3648 	return;
3649 
3650 alloc_fail:
3651 	/*
3652 	 * On allocation failure, just restart the timer.  Note that the ipif
3653 	 * is down here, so no other thread could be trying to start a recovery
3654 	 * timer.  The ill_lock protects the condemned flag and the recovery
3655 	 * timer ID.
3656 	 */
3657 	freemsg(arp_add_mp);
3658 	mutex_enter(&ill->ill_lock);
3659 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3660 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3661 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3662 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3663 	}
3664 	mutex_exit(&ill->ill_lock);
3665 }
3666 
3667 /*
3668  * This is for exclusive changes due to ARP.  Either tear down an interface due
3669  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3670  */
3671 /* ARGSUSED */
3672 static void
3673 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3674 {
3675 	ill_t	*ill = rq->q_ptr;
3676 	arh_t *arh;
3677 	ipaddr_t src;
3678 	ipif_t	*ipif;
3679 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3680 	char hbuf[MAC_STR_LEN];
3681 	char sbuf[INET_ADDRSTRLEN];
3682 	const char *failtype;
3683 	boolean_t bring_up;
3684 	ip_stack_t *ipst = ill->ill_ipst;
3685 
3686 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3687 	case AR_CN_READY:
3688 		failtype = NULL;
3689 		bring_up = B_TRUE;
3690 		break;
3691 	case AR_CN_FAILED:
3692 		failtype = "in use";
3693 		bring_up = B_FALSE;
3694 		break;
3695 	default:
3696 		failtype = "claimed";
3697 		bring_up = B_FALSE;
3698 		break;
3699 	}
3700 
3701 	arh = (arh_t *)mp->b_cont->b_rptr;
3702 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3703 
3704 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3705 	    sizeof (hbuf));
3706 	(void) ip_dot_addr(src, sbuf);
3707 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3708 
3709 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3710 		    ipif->ipif_lcl_addr != src) {
3711 			continue;
3712 		}
3713 
3714 		/*
3715 		 * If we failed on a recovery probe, then restart the timer to
3716 		 * try again later.
3717 		 */
3718 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3719 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3720 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3721 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3722 		    ipst->ips_ip_dup_recovery > 0 &&
3723 		    ipif->ipif_recovery_id == 0) {
3724 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3725 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3726 			continue;
3727 		}
3728 
3729 		/*
3730 		 * If what we're trying to do has already been done, then do
3731 		 * nothing.
3732 		 */
3733 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3734 			continue;
3735 
3736 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3737 
3738 		if (failtype == NULL) {
3739 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3740 			    ibuf);
3741 		} else {
3742 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3743 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3744 		}
3745 
3746 		if (bring_up) {
3747 			ASSERT(ill->ill_dl_up);
3748 			/*
3749 			 * Free up the ARP delete message so we can allocate
3750 			 * a fresh one through the normal path.
3751 			 */
3752 			freemsg(ipif->ipif_arp_del_mp);
3753 			ipif->ipif_arp_del_mp = NULL;
3754 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3755 			    EINPROGRESS) {
3756 				ipif->ipif_addr_ready = 1;
3757 				(void) ipif_up_done(ipif);
3758 				ASSERT(ill->ill_move_ipif == NULL);
3759 			}
3760 			continue;
3761 		}
3762 
3763 		mutex_enter(&ill->ill_lock);
3764 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3765 		ipif->ipif_flags |= IPIF_DUPLICATE;
3766 		ill->ill_ipif_dup_count++;
3767 		mutex_exit(&ill->ill_lock);
3768 		/*
3769 		 * Already exclusive on the ill; no need to handle deferred
3770 		 * processing here.
3771 		 */
3772 		(void) ipif_down(ipif, NULL, NULL);
3773 		ipif_down_tail(ipif);
3774 		mutex_enter(&ill->ill_lock);
3775 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3776 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3777 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3778 		    ipst->ips_ip_dup_recovery > 0) {
3779 			ASSERT(ipif->ipif_recovery_id == 0);
3780 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3781 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3782 		}
3783 		mutex_exit(&ill->ill_lock);
3784 	}
3785 	freemsg(mp);
3786 }
3787 
3788 /* ARGSUSED */
3789 static void
3790 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3791 {
3792 	ill_t	*ill = rq->q_ptr;
3793 	arh_t *arh;
3794 	ipaddr_t src;
3795 	ipif_t	*ipif;
3796 
3797 	arh = (arh_t *)mp->b_cont->b_rptr;
3798 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3799 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3800 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3801 			(void) ipif_resolver_up(ipif, Res_act_defend);
3802 	}
3803 	freemsg(mp);
3804 }
3805 
3806 /*
3807  * News from ARP.  ARP sends notification of interesting events down
3808  * to its clients using M_CTL messages with the interesting ARP packet
3809  * attached via b_cont.
3810  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3811  * queue as opposed to ARP sending the message to all the clients, i.e. all
3812  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3813  * table if a cache IRE is found to delete all the entries for the address in
3814  * the packet.
3815  */
3816 static void
3817 ip_arp_news(queue_t *q, mblk_t *mp)
3818 {
3819 	arcn_t		*arcn;
3820 	arh_t		*arh;
3821 	ire_t		*ire = NULL;
3822 	char		hbuf[MAC_STR_LEN];
3823 	char		sbuf[INET_ADDRSTRLEN];
3824 	ipaddr_t	src;
3825 	in6_addr_t	v6src;
3826 	boolean_t	isv6 = B_FALSE;
3827 	ipif_t		*ipif;
3828 	ill_t		*ill;
3829 	ip_stack_t	*ipst;
3830 
3831 	if (CONN_Q(q)) {
3832 		conn_t *connp = Q_TO_CONN(q);
3833 
3834 		ipst = connp->conn_netstack->netstack_ip;
3835 	} else {
3836 		ill_t *ill = (ill_t *)q->q_ptr;
3837 
3838 		ipst = ill->ill_ipst;
3839 	}
3840 
3841 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3842 		if (q->q_next) {
3843 			putnext(q, mp);
3844 		} else
3845 			freemsg(mp);
3846 		return;
3847 	}
3848 	arh = (arh_t *)mp->b_cont->b_rptr;
3849 	/* Is it one we are interested in? */
3850 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3851 		isv6 = B_TRUE;
3852 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3853 		    IPV6_ADDR_LEN);
3854 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3855 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3856 		    IP_ADDR_LEN);
3857 	} else {
3858 		freemsg(mp);
3859 		return;
3860 	}
3861 
3862 	ill = q->q_ptr;
3863 
3864 	arcn = (arcn_t *)mp->b_rptr;
3865 	switch (arcn->arcn_code) {
3866 	case AR_CN_BOGON:
3867 		/*
3868 		 * Someone is sending ARP packets with a source protocol
3869 		 * address that we have published and for which we believe our
3870 		 * entry is authoritative and (when ill_arp_extend is set)
3871 		 * verified to be unique on the network.
3872 		 *
3873 		 * The ARP module internally handles the cases where the sender
3874 		 * is just probing (for DAD) and where the hardware address of
3875 		 * a non-authoritative entry has changed.  Thus, these are the
3876 		 * real conflicts, and we have to do resolution.
3877 		 *
3878 		 * We back away quickly from the address if it's from DHCP or
3879 		 * otherwise temporary and hasn't been used recently (or at
3880 		 * all).  We'd like to include "deprecated" addresses here as
3881 		 * well (as there's no real reason to defend something we're
3882 		 * discarding), but IPMP "reuses" this flag to mean something
3883 		 * other than the standard meaning.
3884 		 *
3885 		 * If the ARP module above is not extended (meaning that it
3886 		 * doesn't know how to defend the address), then we just log
3887 		 * the problem as we always did and continue on.  It's not
3888 		 * right, but there's little else we can do, and those old ATM
3889 		 * users are going away anyway.
3890 		 */
3891 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3892 		    hbuf, sizeof (hbuf));
3893 		(void) ip_dot_addr(src, sbuf);
3894 		if (isv6) {
3895 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3896 			    ipst);
3897 		} else {
3898 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3899 		}
3900 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3901 			uint32_t now;
3902 			uint32_t maxage;
3903 			clock_t lused;
3904 			uint_t maxdefense;
3905 			uint_t defs;
3906 
3907 			/*
3908 			 * First, figure out if this address hasn't been used
3909 			 * in a while.  If it hasn't, then it's a better
3910 			 * candidate for abandoning.
3911 			 */
3912 			ipif = ire->ire_ipif;
3913 			ASSERT(ipif != NULL);
3914 			now = gethrestime_sec();
3915 			maxage = now - ire->ire_create_time;
3916 			if (maxage > ipst->ips_ip_max_temp_idle)
3917 				maxage = ipst->ips_ip_max_temp_idle;
3918 			lused = drv_hztousec(ddi_get_lbolt() -
3919 			    ire->ire_last_used_time) / MICROSEC + 1;
3920 			if (lused >= maxage && (ipif->ipif_flags &
3921 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
3922 				maxdefense = ipst->ips_ip_max_temp_defend;
3923 			else
3924 				maxdefense = ipst->ips_ip_max_defend;
3925 
3926 			/*
3927 			 * Now figure out how many times we've defended
3928 			 * ourselves.  Ignore defenses that happened long in
3929 			 * the past.
3930 			 */
3931 			mutex_enter(&ire->ire_lock);
3932 			if ((defs = ire->ire_defense_count) > 0 &&
3933 			    now - ire->ire_defense_time >
3934 			    ipst->ips_ip_defend_interval) {
3935 				ire->ire_defense_count = defs = 0;
3936 			}
3937 			ire->ire_defense_count++;
3938 			ire->ire_defense_time = now;
3939 			mutex_exit(&ire->ire_lock);
3940 			ill_refhold(ill);
3941 			ire_refrele(ire);
3942 
3943 			/*
3944 			 * If we've defended ourselves too many times already,
3945 			 * then give up and tear down the interface(s) using
3946 			 * this address.  Otherwise, defend by sending out a
3947 			 * gratuitous ARP.
3948 			 */
3949 			if (defs >= maxdefense && ill->ill_arp_extend) {
3950 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
3951 				    B_FALSE);
3952 			} else {
3953 				cmn_err(CE_WARN,
3954 				    "node %s is using our IP address %s on %s",
3955 				    hbuf, sbuf, ill->ill_name);
3956 				/*
3957 				 * If this is an old (ATM) ARP module, then
3958 				 * don't try to defend the address.  Remain
3959 				 * compatible with the old behavior.  Defend
3960 				 * only with new ARP.
3961 				 */
3962 				if (ill->ill_arp_extend) {
3963 					qwriter_ip(ill, q, mp, ip_arp_defend,
3964 					    NEW_OP, B_FALSE);
3965 				} else {
3966 					ill_refrele(ill);
3967 				}
3968 			}
3969 			return;
3970 		}
3971 		cmn_err(CE_WARN,
3972 		    "proxy ARP problem?  Node '%s' is using %s on %s",
3973 		    hbuf, sbuf, ill->ill_name);
3974 		if (ire != NULL)
3975 			ire_refrele(ire);
3976 		break;
3977 	case AR_CN_ANNOUNCE:
3978 		if (isv6) {
3979 			/*
3980 			 * For XRESOLV interfaces.
3981 			 * Delete the IRE cache entry and NCE for this
3982 			 * v6 address
3983 			 */
3984 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
3985 			/*
3986 			 * If v6src is a non-zero, it's a router address
3987 			 * as below. Do the same sort of thing to clean
3988 			 * out off-net IRE_CACHE entries that go through
3989 			 * the router.
3990 			 */
3991 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
3992 				ire_walk_v6(ire_delete_cache_gw_v6,
3993 				    (char *)&v6src, ALL_ZONES, ipst);
3994 			}
3995 		} else {
3996 			nce_hw_map_t hwm;
3997 
3998 			/*
3999 			 * ARP gives us a copy of any packet where it thinks
4000 			 * the address has changed, so that we can update our
4001 			 * caches.  We're responsible for caching known answers
4002 			 * in the current design.  We check whether the
4003 			 * hardware address really has changed in all of our
4004 			 * entries that have cached this mapping, and if so, we
4005 			 * blow them away.  This way we will immediately pick
4006 			 * up the rare case of a host changing hardware
4007 			 * address.
4008 			 */
4009 			if (src == 0)
4010 				break;
4011 			hwm.hwm_addr = src;
4012 			hwm.hwm_hwlen = arh->arh_hlen;
4013 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4014 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4015 			ndp_walk_common(ipst->ips_ndp4, NULL,
4016 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4017 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4018 		}
4019 		break;
4020 	case AR_CN_READY:
4021 		/* No external v6 resolver has a contract to use this */
4022 		if (isv6)
4023 			break;
4024 		/* If the link is down, we'll retry this later */
4025 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4026 			break;
4027 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4028 		    NULL, NULL, ipst);
4029 		if (ipif != NULL) {
4030 			/*
4031 			 * If this is a duplicate recovery, then we now need to
4032 			 * go exclusive to bring this thing back up.
4033 			 */
4034 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4035 			    IPIF_DUPLICATE) {
4036 				ipif_refrele(ipif);
4037 				ill_refhold(ill);
4038 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4039 				    B_FALSE);
4040 				return;
4041 			}
4042 			/*
4043 			 * If this is the first notice that this address is
4044 			 * ready, then let the user know now.
4045 			 */
4046 			if ((ipif->ipif_flags & IPIF_UP) &&
4047 			    !ipif->ipif_addr_ready) {
4048 				ipif_mask_reply(ipif);
4049 				ipif_up_notify(ipif);
4050 			}
4051 			ipif->ipif_addr_ready = 1;
4052 			ipif_refrele(ipif);
4053 		}
4054 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4055 		if (ire != NULL) {
4056 			ire->ire_defense_count = 0;
4057 			ire_refrele(ire);
4058 		}
4059 		break;
4060 	case AR_CN_FAILED:
4061 		/* No external v6 resolver has a contract to use this */
4062 		if (isv6)
4063 			break;
4064 		ill_refhold(ill);
4065 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4066 		return;
4067 	}
4068 	freemsg(mp);
4069 }
4070 
4071 /*
4072  * Create a mblk suitable for carrying the interface index and/or source link
4073  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4074  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4075  * application.
4076  */
4077 mblk_t *
4078 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4079     ip_stack_t *ipst)
4080 {
4081 	mblk_t		*mp;
4082 	ip_pktinfo_t	*pinfo;
4083 	ipha_t 		*ipha;
4084 	struct ether_header *pether;
4085 	boolean_t	ipmp_ill_held = B_FALSE;
4086 
4087 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4088 	if (mp == NULL) {
4089 		ip1dbg(("ip_add_info: allocation failure.\n"));
4090 		return (data_mp);
4091 	}
4092 
4093 	ipha = (ipha_t *)data_mp->b_rptr;
4094 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4095 	bzero(pinfo, sizeof (ip_pktinfo_t));
4096 	pinfo->ip_pkt_flags = (uchar_t)flags;
4097 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4098 
4099 	pether = (struct ether_header *)((char *)ipha
4100 	    - sizeof (struct ether_header));
4101 
4102 	/*
4103 	 * Make sure the interface is an ethernet type, since this option
4104 	 * is currently supported only on this type of interface. Also make
4105 	 * sure we are pointing correctly above db_base.
4106 	 */
4107 	if ((flags & IPF_RECVSLLA) &&
4108 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4109 	    (ill->ill_type == IFT_ETHER) &&
4110 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4111 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4112 		bcopy(pether->ether_shost.ether_addr_octet,
4113 		    pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4114 	} else {
4115 		/*
4116 		 * Clear the bit. Indicate to upper layer that IP is not
4117 		 * sending this ancillary info.
4118 		 */
4119 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4120 	}
4121 
4122 	/*
4123 	 * If `ill' is in an IPMP group, use the IPMP ill to determine
4124 	 * IPF_RECVIF and IPF_RECVADDR.  (This currently assumes that
4125 	 * IPF_RECVADDR support on test addresses is not needed.)
4126 	 *
4127 	 * Note that `ill' may already be an IPMP ill if e.g. we're
4128 	 * processing a packet looped back to an IPMP data address
4129 	 * (since those IRE_LOCALs are tied to IPMP ills).
4130 	 */
4131 	if (IS_UNDER_IPMP(ill)) {
4132 		if ((ill = ipmp_ill_hold_ipmp_ill(ill)) == NULL) {
4133 			ip1dbg(("ip_add_info: cannot hold IPMP ill.\n"));
4134 			freemsg(mp);
4135 			return (data_mp);
4136 		}
4137 		ipmp_ill_held = B_TRUE;
4138 	}
4139 
4140 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4141 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4142 	if (flags & IPF_RECVADDR) {
4143 		ipif_t	*ipif;
4144 		ire_t	*ire;
4145 
4146 		/*
4147 		 * Only valid for V4
4148 		 */
4149 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4150 		    (IPV4_VERSION << 4));
4151 
4152 		ipif = ipif_get_next_ipif(NULL, ill);
4153 		if (ipif != NULL) {
4154 			/*
4155 			 * Since a decision has already been made to deliver the
4156 			 * packet, there is no need to test for SECATTR and
4157 			 * ZONEONLY.
4158 			 * When a multicast packet is transmitted
4159 			 * a cache entry is created for the multicast address.
4160 			 * When delivering a copy of the packet or when new
4161 			 * packets are received we do not want to match on the
4162 			 * cached entry so explicitly match on
4163 			 * IRE_LOCAL and IRE_LOOPBACK
4164 			 */
4165 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4166 			    IRE_LOCAL | IRE_LOOPBACK,
4167 			    ipif, zoneid, NULL,
4168 			    MATCH_IRE_TYPE | MATCH_IRE_ILL, ipst);
4169 			if (ire == NULL) {
4170 				/*
4171 				 * packet must have come on a different
4172 				 * interface.
4173 				 * Since a decision has already been made to
4174 				 * deliver the packet, there is no need to test
4175 				 * for SECATTR and ZONEONLY.
4176 				 * Only match on local and broadcast ire's.
4177 				 * See detailed comment above.
4178 				 */
4179 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4180 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4181 				    NULL, MATCH_IRE_TYPE, ipst);
4182 			}
4183 
4184 			if (ire == NULL) {
4185 				/*
4186 				 * This is either a multicast packet or
4187 				 * the address has been removed since
4188 				 * the packet was received.
4189 				 * Return INADDR_ANY so that normal source
4190 				 * selection occurs for the response.
4191 				 */
4192 
4193 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4194 			} else {
4195 				pinfo->ip_pkt_match_addr.s_addr =
4196 				    ire->ire_src_addr;
4197 				ire_refrele(ire);
4198 			}
4199 			ipif_refrele(ipif);
4200 		} else {
4201 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4202 		}
4203 	}
4204 
4205 	if (ipmp_ill_held)
4206 		ill_refrele(ill);
4207 
4208 	mp->b_datap->db_type = M_CTL;
4209 	mp->b_wptr += sizeof (ip_pktinfo_t);
4210 	mp->b_cont = data_mp;
4211 
4212 	return (mp);
4213 }
4214 
4215 /*
4216  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4217  * part of the bind request.
4218  */
4219 
4220 boolean_t
4221 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4222 {
4223 	ipsec_in_t *ii;
4224 
4225 	ASSERT(policy_mp != NULL);
4226 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4227 
4228 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4229 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4230 
4231 	connp->conn_policy = ii->ipsec_in_policy;
4232 	ii->ipsec_in_policy = NULL;
4233 
4234 	if (ii->ipsec_in_action != NULL) {
4235 		if (connp->conn_latch == NULL) {
4236 			connp->conn_latch = iplatch_create();
4237 			if (connp->conn_latch == NULL)
4238 				return (B_FALSE);
4239 		}
4240 		ipsec_latch_inbound(connp->conn_latch, ii);
4241 	}
4242 	return (B_TRUE);
4243 }
4244 
4245 static void
4246 ip_bind_post_handling(conn_t *connp, mblk_t *mp, boolean_t ire_requested)
4247 {
4248 	/*
4249 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4250 	 * We can't do this in ip_bind_get_ire because the policy
4251 	 * may not have been inherited at that point in time and hence
4252 	 * conn_out_enforce_policy may not be set.
4253 	 */
4254 	if (ire_requested && connp->conn_out_enforce_policy &&
4255 	    mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE) {
4256 		ire_t *ire = (ire_t *)mp->b_rptr;
4257 		ASSERT(MBLKL(mp) >= sizeof (ire_t));
4258 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4259 	}
4260 }
4261 
4262 /*
4263  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4264  * and to arrange for power-fanout assist.  The ULP is identified by
4265  * adding a single byte at the end of the original bind message.
4266  * A ULP other than UDP or TCP that wishes to be recognized passes
4267  * down a bind with a zero length address.
4268  *
4269  * The binding works as follows:
4270  * - A zero byte address means just bind to the protocol.
4271  * - A four byte address is treated as a request to validate
4272  *   that the address is a valid local address, appropriate for
4273  *   an application to bind to. This does not affect any fanout
4274  *   information in IP.
4275  * - A sizeof sin_t byte address is used to bind to only the local address
4276  *   and port.
4277  * - A sizeof ipa_conn_t byte address contains complete fanout information
4278  *   consisting of local and remote addresses and ports.  In
4279  *   this case, the addresses are both validated as appropriate
4280  *   for this operation, and, if so, the information is retained
4281  *   for use in the inbound fanout.
4282  *
4283  * The ULP (except in the zero-length bind) can append an
4284  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4285  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4286  * a copy of the source or destination IRE (source for local bind;
4287  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4288  * policy information contained should be copied on to the conn.
4289  *
4290  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4291  */
4292 mblk_t *
4293 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4294 {
4295 	ssize_t		len;
4296 	struct T_bind_req	*tbr;
4297 	sin_t		*sin;
4298 	ipa_conn_t	*ac;
4299 	uchar_t		*ucp;
4300 	mblk_t		*mp1;
4301 	boolean_t	ire_requested;
4302 	int		error = 0;
4303 	int		protocol;
4304 	ipa_conn_x_t	*acx;
4305 
4306 	ASSERT(!connp->conn_af_isv6);
4307 	connp->conn_pkt_isv6 = B_FALSE;
4308 
4309 	len = MBLKL(mp);
4310 	if (len < (sizeof (*tbr) + 1)) {
4311 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4312 		    "ip_bind: bogus msg, len %ld", len);
4313 		/* XXX: Need to return something better */
4314 		goto bad_addr;
4315 	}
4316 	/* Back up and extract the protocol identifier. */
4317 	mp->b_wptr--;
4318 	protocol = *mp->b_wptr & 0xFF;
4319 	tbr = (struct T_bind_req *)mp->b_rptr;
4320 	/* Reset the message type in preparation for shipping it back. */
4321 	DB_TYPE(mp) = M_PCPROTO;
4322 
4323 	connp->conn_ulp = (uint8_t)protocol;
4324 
4325 	/*
4326 	 * Check for a zero length address.  This is from a protocol that
4327 	 * wants to register to receive all packets of its type.
4328 	 */
4329 	if (tbr->ADDR_length == 0) {
4330 		/*
4331 		 * These protocols are now intercepted in ip_bind_v6().
4332 		 * Reject protocol-level binds here for now.
4333 		 *
4334 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4335 		 * so that the protocol type cannot be SCTP.
4336 		 */
4337 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4338 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4339 			goto bad_addr;
4340 		}
4341 
4342 		/*
4343 		 *
4344 		 * The udp module never sends down a zero-length address,
4345 		 * and allowing this on a labeled system will break MLP
4346 		 * functionality.
4347 		 */
4348 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4349 			goto bad_addr;
4350 
4351 		if (connp->conn_mac_exempt)
4352 			goto bad_addr;
4353 
4354 		/* No hash here really.  The table is big enough. */
4355 		connp->conn_srcv6 = ipv6_all_zeros;
4356 
4357 		ipcl_proto_insert(connp, protocol);
4358 
4359 		tbr->PRIM_type = T_BIND_ACK;
4360 		return (mp);
4361 	}
4362 
4363 	/* Extract the address pointer from the message. */
4364 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4365 	    tbr->ADDR_length);
4366 	if (ucp == NULL) {
4367 		ip1dbg(("ip_bind: no address\n"));
4368 		goto bad_addr;
4369 	}
4370 	if (!OK_32PTR(ucp)) {
4371 		ip1dbg(("ip_bind: unaligned address\n"));
4372 		goto bad_addr;
4373 	}
4374 	/*
4375 	 * Check for trailing mps.
4376 	 */
4377 
4378 	mp1 = mp->b_cont;
4379 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4380 
4381 	switch (tbr->ADDR_length) {
4382 	default:
4383 		ip1dbg(("ip_bind: bad address length %d\n",
4384 		    (int)tbr->ADDR_length));
4385 		goto bad_addr;
4386 
4387 	case IP_ADDR_LEN:
4388 		/* Verification of local address only */
4389 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4390 		    *(ipaddr_t *)ucp, 0, B_FALSE);
4391 		break;
4392 
4393 	case sizeof (sin_t):
4394 		sin = (sin_t *)ucp;
4395 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4396 		    sin->sin_addr.s_addr, sin->sin_port, B_TRUE);
4397 		break;
4398 
4399 	case sizeof (ipa_conn_t):
4400 		ac = (ipa_conn_t *)ucp;
4401 		/* For raw socket, the local port is not set. */
4402 		if (ac->ac_lport == 0)
4403 			ac->ac_lport = connp->conn_lport;
4404 		/* Always verify destination reachability. */
4405 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4406 		    &ac->ac_laddr, ac->ac_lport, ac->ac_faddr, ac->ac_fport,
4407 		    B_TRUE, B_TRUE);
4408 		break;
4409 
4410 	case sizeof (ipa_conn_x_t):
4411 		acx = (ipa_conn_x_t *)ucp;
4412 		/*
4413 		 * Whether or not to verify destination reachability depends
4414 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4415 		 */
4416 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4417 		    &acx->acx_conn.ac_laddr, acx->acx_conn.ac_lport,
4418 		    acx->acx_conn.ac_faddr, acx->acx_conn.ac_fport,
4419 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4420 		break;
4421 	}
4422 	ASSERT(error != EINPROGRESS);
4423 	if (error != 0)
4424 		goto bad_addr;
4425 
4426 	ip_bind_post_handling(connp, mp->b_cont, ire_requested);
4427 
4428 	/* Send it home. */
4429 	mp->b_datap->db_type = M_PCPROTO;
4430 	tbr->PRIM_type = T_BIND_ACK;
4431 	return (mp);
4432 
4433 bad_addr:
4434 	/*
4435 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4436 	 * a unix errno.
4437 	 */
4438 	if (error > 0)
4439 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4440 	else
4441 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4442 	return (mp);
4443 }
4444 
4445 /*
4446  * Here address is verified to be a valid local address.
4447  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4448  * address is also considered a valid local address.
4449  * In the case of a broadcast/multicast address, however, the
4450  * upper protocol is expected to reset the src address
4451  * to 0 if it sees a IRE_BROADCAST type returned so that
4452  * no packets are emitted with broadcast/multicast address as
4453  * source address (that violates hosts requirements RFC 1122)
4454  * The addresses valid for bind are:
4455  *	(1) - INADDR_ANY (0)
4456  *	(2) - IP address of an UP interface
4457  *	(3) - IP address of a DOWN interface
4458  *	(4) - valid local IP broadcast addresses. In this case
4459  *	the conn will only receive packets destined to
4460  *	the specified broadcast address.
4461  *	(5) - a multicast address. In this case
4462  *	the conn will only receive packets destined to
4463  *	the specified multicast address. Note: the
4464  *	application still has to issue an
4465  *	IP_ADD_MEMBERSHIP socket option.
4466  *
4467  * On error, return -1 for TBADADDR otherwise pass the
4468  * errno with TSYSERR reply.
4469  *
4470  * In all the above cases, the bound address must be valid in the current zone.
4471  * When the address is loopback, multicast or broadcast, there might be many
4472  * matching IREs so bind has to look up based on the zone.
4473  *
4474  * Note: lport is in network byte order.
4475  *
4476  */
4477 int
4478 ip_bind_laddr_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4479     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4480 {
4481 	int		error = 0;
4482 	ire_t		*src_ire;
4483 	zoneid_t	zoneid;
4484 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4485 	mblk_t		*mp = NULL;
4486 	boolean_t	ire_requested = B_FALSE;
4487 	boolean_t	ipsec_policy_set = B_FALSE;
4488 
4489 	if (mpp)
4490 		mp = *mpp;
4491 
4492 	if (mp != NULL) {
4493 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4494 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4495 	}
4496 
4497 	/*
4498 	 * If it was previously connected, conn_fully_bound would have
4499 	 * been set.
4500 	 */
4501 	connp->conn_fully_bound = B_FALSE;
4502 
4503 	src_ire = NULL;
4504 
4505 	zoneid = IPCL_ZONEID(connp);
4506 
4507 	if (src_addr) {
4508 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4509 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4510 		/*
4511 		 * If an address other than 0.0.0.0 is requested,
4512 		 * we verify that it is a valid address for bind
4513 		 * Note: Following code is in if-else-if form for
4514 		 * readability compared to a condition check.
4515 		 */
4516 		/* LINTED - statement has no consequence */
4517 		if (IRE_IS_LOCAL(src_ire)) {
4518 			/*
4519 			 * (2) Bind to address of local UP interface
4520 			 */
4521 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4522 			/*
4523 			 * (4) Bind to broadcast address
4524 			 * Note: permitted only from transports that
4525 			 * request IRE
4526 			 */
4527 			if (!ire_requested)
4528 				error = EADDRNOTAVAIL;
4529 		} else {
4530 			/*
4531 			 * (3) Bind to address of local DOWN interface
4532 			 * (ipif_lookup_addr() looks up all interfaces
4533 			 * but we do not get here for UP interfaces
4534 			 * - case (2) above)
4535 			 */
4536 			/* LINTED - statement has no consequent */
4537 			if (ip_addr_exists(src_addr, zoneid, ipst)) {
4538 				/* The address exists */
4539 			} else if (CLASSD(src_addr)) {
4540 				error = 0;
4541 				if (src_ire != NULL)
4542 					ire_refrele(src_ire);
4543 				/*
4544 				 * (5) bind to multicast address.
4545 				 * Fake out the IRE returned to upper
4546 				 * layer to be a broadcast IRE.
4547 				 */
4548 				src_ire = ire_ctable_lookup(
4549 				    INADDR_BROADCAST, INADDR_ANY,
4550 				    IRE_BROADCAST, NULL, zoneid, NULL,
4551 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4552 				    ipst);
4553 				if (src_ire == NULL || !ire_requested)
4554 					error = EADDRNOTAVAIL;
4555 			} else {
4556 				/*
4557 				 * Not a valid address for bind
4558 				 */
4559 				error = EADDRNOTAVAIL;
4560 			}
4561 		}
4562 		if (error) {
4563 			/* Red Alert!  Attempting to be a bogon! */
4564 			ip1dbg(("ip_bind_laddr_v4: bad src address 0x%x\n",
4565 			    ntohl(src_addr)));
4566 			goto bad_addr;
4567 		}
4568 	}
4569 
4570 
4571 	/*
4572 	 * Allow setting new policies. For example, disconnects come
4573 	 * down as ipa_t bind. As we would have set conn_policy_cached
4574 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4575 	 * can change after the disconnect.
4576 	 */
4577 	connp->conn_policy_cached = B_FALSE;
4578 
4579 	/*
4580 	 * If not fanout_insert this was just an address verification
4581 	 */
4582 	if (fanout_insert) {
4583 		/*
4584 		 * The addresses have been verified. Time to insert in
4585 		 * the correct fanout list.
4586 		 */
4587 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4588 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4589 		connp->conn_lport = lport;
4590 		connp->conn_fport = 0;
4591 		/*
4592 		 * Do we need to add a check to reject Multicast packets
4593 		 */
4594 		error = ipcl_bind_insert(connp, protocol, src_addr, lport);
4595 	}
4596 
4597 	if (error == 0) {
4598 		if (ire_requested) {
4599 			if (!ip_bind_get_ire_v4(mpp, src_ire, NULL, ipst)) {
4600 				error = -1;
4601 				/* Falls through to bad_addr */
4602 			}
4603 		} else if (ipsec_policy_set) {
4604 			if (!ip_bind_ipsec_policy_set(connp, mp)) {
4605 				error = -1;
4606 				/* Falls through to bad_addr */
4607 			}
4608 		}
4609 	}
4610 bad_addr:
4611 	if (error != 0) {
4612 		if (connp->conn_anon_port) {
4613 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4614 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4615 			    B_FALSE);
4616 		}
4617 		connp->conn_mlp_type = mlptSingle;
4618 	}
4619 	if (src_ire != NULL)
4620 		IRE_REFRELE(src_ire);
4621 	return (error);
4622 }
4623 
4624 int
4625 ip_proto_bind_laddr_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
4626     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4627 {
4628 	int error;
4629 	mblk_t	*mp = NULL;
4630 	boolean_t ire_requested;
4631 
4632 	if (ire_mpp)
4633 		mp = *ire_mpp;
4634 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4635 
4636 	ASSERT(!connp->conn_af_isv6);
4637 	connp->conn_pkt_isv6 = B_FALSE;
4638 	connp->conn_ulp = protocol;
4639 
4640 	error = ip_bind_laddr_v4(connp, ire_mpp, protocol, src_addr, lport,
4641 	    fanout_insert);
4642 	if (error == 0) {
4643 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
4644 		    ire_requested);
4645 	} else if (error < 0) {
4646 		error = -TBADADDR;
4647 	}
4648 	return (error);
4649 }
4650 
4651 /*
4652  * Verify that both the source and destination addresses
4653  * are valid.  If verify_dst is false, then the destination address may be
4654  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4655  * destination reachability, while tunnels do not.
4656  * Note that we allow connect to broadcast and multicast
4657  * addresses when ire_requested is set. Thus the ULP
4658  * has to check for IRE_BROADCAST and multicast.
4659  *
4660  * Returns zero if ok.
4661  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4662  * (for use with TSYSERR reply).
4663  *
4664  * Note: lport and fport are in network byte order.
4665  */
4666 int
4667 ip_bind_connected_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4668     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4669     boolean_t fanout_insert, boolean_t verify_dst)
4670 {
4671 
4672 	ire_t		*src_ire;
4673 	ire_t		*dst_ire;
4674 	int		error = 0;
4675 	ire_t		*sire = NULL;
4676 	ire_t		*md_dst_ire = NULL;
4677 	ire_t		*lso_dst_ire = NULL;
4678 	ill_t		*ill = NULL;
4679 	zoneid_t	zoneid;
4680 	ipaddr_t	src_addr = *src_addrp;
4681 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4682 	mblk_t		*mp = NULL;
4683 	boolean_t	ire_requested = B_FALSE;
4684 	boolean_t	ipsec_policy_set = B_FALSE;
4685 	ts_label_t	*tsl = NULL;
4686 
4687 	if (mpp)
4688 		mp = *mpp;
4689 
4690 	if (mp != NULL) {
4691 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4692 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4693 		tsl = MBLK_GETLABEL(mp);
4694 	}
4695 
4696 	src_ire = dst_ire = NULL;
4697 
4698 	/*
4699 	 * If we never got a disconnect before, clear it now.
4700 	 */
4701 	connp->conn_fully_bound = B_FALSE;
4702 
4703 	zoneid = IPCL_ZONEID(connp);
4704 
4705 	if (CLASSD(dst_addr)) {
4706 		/* Pick up an IRE_BROADCAST */
4707 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4708 		    NULL, zoneid, tsl,
4709 		    (MATCH_IRE_RECURSIVE |
4710 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4711 		    MATCH_IRE_SECATTR), ipst);
4712 	} else {
4713 		/*
4714 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4715 		 * and onlink ipif is not found set ENETUNREACH error.
4716 		 */
4717 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4718 			ipif_t *ipif;
4719 
4720 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4721 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4722 			if (ipif == NULL) {
4723 				error = ENETUNREACH;
4724 				goto bad_addr;
4725 			}
4726 			ipif_refrele(ipif);
4727 		}
4728 
4729 		if (connp->conn_nexthop_set) {
4730 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4731 			    0, 0, NULL, NULL, zoneid, tsl,
4732 			    MATCH_IRE_SECATTR, ipst);
4733 		} else {
4734 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4735 			    &sire, zoneid, tsl,
4736 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4737 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4738 			    MATCH_IRE_SECATTR), ipst);
4739 		}
4740 	}
4741 	/*
4742 	 * dst_ire can't be a broadcast when not ire_requested.
4743 	 * We also prevent ire's with src address INADDR_ANY to
4744 	 * be used, which are created temporarily for
4745 	 * sending out packets from endpoints that have
4746 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4747 	 * reachable.  If verify_dst is false, the destination needn't be
4748 	 * reachable.
4749 	 *
4750 	 * If we match on a reject or black hole, then we've got a
4751 	 * local failure.  May as well fail out the connect() attempt,
4752 	 * since it's never going to succeed.
4753 	 */
4754 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4755 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4756 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4757 		/*
4758 		 * If we're verifying destination reachability, we always want
4759 		 * to complain here.
4760 		 *
4761 		 * If we're not verifying destination reachability but the
4762 		 * destination has a route, we still want to fail on the
4763 		 * temporary address and broadcast address tests.
4764 		 */
4765 		if (verify_dst || (dst_ire != NULL)) {
4766 			if (ip_debug > 2) {
4767 				pr_addr_dbg("ip_bind_connected_v4:"
4768 				    "bad connected dst %s\n",
4769 				    AF_INET, &dst_addr);
4770 			}
4771 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4772 				error = ENETUNREACH;
4773 			else
4774 				error = EHOSTUNREACH;
4775 			goto bad_addr;
4776 		}
4777 	}
4778 
4779 	/*
4780 	 * We now know that routing will allow us to reach the destination.
4781 	 * Check whether Trusted Solaris policy allows communication with this
4782 	 * host, and pretend that the destination is unreachable if not.
4783 	 *
4784 	 * This is never a problem for TCP, since that transport is known to
4785 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4786 	 * handling.  If the remote is unreachable, it will be detected at that
4787 	 * point, so there's no reason to check it here.
4788 	 *
4789 	 * Note that for sendto (and other datagram-oriented friends), this
4790 	 * check is done as part of the data path label computation instead.
4791 	 * The check here is just to make non-TCP connect() report the right
4792 	 * error.
4793 	 */
4794 	if (dst_ire != NULL && is_system_labeled() &&
4795 	    !IPCL_IS_TCP(connp) &&
4796 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4797 	    connp->conn_mac_exempt, ipst) != 0) {
4798 		error = EHOSTUNREACH;
4799 		if (ip_debug > 2) {
4800 			pr_addr_dbg("ip_bind_connected_v4:"
4801 			    " no label for dst %s\n",
4802 			    AF_INET, &dst_addr);
4803 		}
4804 		goto bad_addr;
4805 	}
4806 
4807 	/*
4808 	 * If the app does a connect(), it means that it will most likely
4809 	 * send more than 1 packet to the destination.  It makes sense
4810 	 * to clear the temporary flag.
4811 	 */
4812 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4813 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4814 		irb_t *irb = dst_ire->ire_bucket;
4815 
4816 		rw_enter(&irb->irb_lock, RW_WRITER);
4817 		/*
4818 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4819 		 * the lock to guarantee irb_tmp_ire_cnt.
4820 		 */
4821 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4822 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4823 			irb->irb_tmp_ire_cnt--;
4824 		}
4825 		rw_exit(&irb->irb_lock);
4826 	}
4827 
4828 	/*
4829 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4830 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4831 	 * eligibility tests for passive connects are handled separately
4832 	 * through tcp_adapt_ire().  We do this before the source address
4833 	 * selection, because dst_ire may change after a call to
4834 	 * ipif_select_source().  This is a best-effort check, as the
4835 	 * packet for this connection may not actually go through
4836 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4837 	 * calling ip_newroute().  This is why we further check on the
4838 	 * IRE during LSO/Multidata packet transmission in
4839 	 * tcp_lsosend()/tcp_multisend().
4840 	 */
4841 	if (!ipsec_policy_set && dst_ire != NULL &&
4842 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4843 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4844 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4845 			lso_dst_ire = dst_ire;
4846 			IRE_REFHOLD(lso_dst_ire);
4847 		} else if (ipst->ips_ip_multidata_outbound &&
4848 		    ILL_MDT_CAPABLE(ill)) {
4849 			md_dst_ire = dst_ire;
4850 			IRE_REFHOLD(md_dst_ire);
4851 		}
4852 	}
4853 
4854 	if (dst_ire != NULL && dst_ire->ire_type == IRE_LOCAL &&
4855 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4856 		/*
4857 		 * If the IRE belongs to a different zone, look for a matching
4858 		 * route in the forwarding table and use the source address from
4859 		 * that route.
4860 		 */
4861 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4862 		    zoneid, 0, NULL,
4863 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4864 		    MATCH_IRE_RJ_BHOLE, ipst);
4865 		if (src_ire == NULL) {
4866 			error = EHOSTUNREACH;
4867 			goto bad_addr;
4868 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4869 			if (!(src_ire->ire_type & IRE_HOST))
4870 				error = ENETUNREACH;
4871 			else
4872 				error = EHOSTUNREACH;
4873 			goto bad_addr;
4874 		}
4875 		if (src_addr == INADDR_ANY)
4876 			src_addr = src_ire->ire_src_addr;
4877 		ire_refrele(src_ire);
4878 		src_ire = NULL;
4879 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4880 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4881 			src_addr = sire->ire_src_addr;
4882 			ire_refrele(dst_ire);
4883 			dst_ire = sire;
4884 			sire = NULL;
4885 		} else {
4886 			/*
4887 			 * Pick a source address so that a proper inbound
4888 			 * load spreading would happen.
4889 			 */
4890 			ill_t *ire_ill = dst_ire->ire_ipif->ipif_ill;
4891 			ipif_t *src_ipif = NULL;
4892 			ire_t *ipif_ire;
4893 
4894 			/*
4895 			 * Supply a local source address such that inbound
4896 			 * load spreading happens.
4897 			 *
4898 			 * Determine the best source address on this ill for
4899 			 * the destination.
4900 			 *
4901 			 * 1) For broadcast, we should return a broadcast ire
4902 			 *    found above so that upper layers know that the
4903 			 *    destination address is a broadcast address.
4904 			 *
4905 			 * 2) If the ipif is DEPRECATED, select a better
4906 			 *    source address.  Similarly, if the ipif is on
4907 			 *    the IPMP meta-interface, pick a source address
4908 			 *    at random to improve inbound load spreading.
4909 			 *
4910 			 * 3) If the outgoing interface is part of a usesrc
4911 			 *    group, then try selecting a source address from
4912 			 *    the usesrc ILL.
4913 			 */
4914 			if ((dst_ire->ire_zoneid != zoneid &&
4915 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4916 			    (!(dst_ire->ire_flags & RTF_SETSRC)) &&
4917 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4918 			    (IS_IPMP(ire_ill) ||
4919 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4920 			    (ire_ill->ill_usesrc_ifindex != 0)))) {
4921 				/*
4922 				 * If the destination is reachable via a
4923 				 * given gateway, the selected source address
4924 				 * should be in the same subnet as the gateway.
4925 				 * Otherwise, the destination is not reachable.
4926 				 *
4927 				 * If there are no interfaces on the same subnet
4928 				 * as the destination, ipif_select_source gives
4929 				 * first non-deprecated interface which might be
4930 				 * on a different subnet than the gateway.
4931 				 * This is not desirable. Hence pass the dst_ire
4932 				 * source address to ipif_select_source.
4933 				 * It is sure that the destination is reachable
4934 				 * with the dst_ire source address subnet.
4935 				 * So passing dst_ire source address to
4936 				 * ipif_select_source will make sure that the
4937 				 * selected source will be on the same subnet
4938 				 * as dst_ire source address.
4939 				 */
4940 				ipaddr_t saddr =
4941 				    dst_ire->ire_ipif->ipif_src_addr;
4942 				src_ipif = ipif_select_source(ire_ill,
4943 				    saddr, zoneid);
4944 				if (src_ipif != NULL) {
4945 					if (IS_VNI(src_ipif->ipif_ill)) {
4946 						/*
4947 						 * For VNI there is no
4948 						 * interface route
4949 						 */
4950 						src_addr =
4951 						    src_ipif->ipif_src_addr;
4952 					} else {
4953 						ipif_ire =
4954 						    ipif_to_ire(src_ipif);
4955 						if (ipif_ire != NULL) {
4956 							IRE_REFRELE(dst_ire);
4957 							dst_ire = ipif_ire;
4958 						}
4959 						src_addr =
4960 						    dst_ire->ire_src_addr;
4961 					}
4962 					ipif_refrele(src_ipif);
4963 				} else {
4964 					src_addr = dst_ire->ire_src_addr;
4965 				}
4966 			} else {
4967 				src_addr = dst_ire->ire_src_addr;
4968 			}
4969 		}
4970 	}
4971 
4972 	/*
4973 	 * We do ire_route_lookup() here (and not
4974 	 * interface lookup as we assert that
4975 	 * src_addr should only come from an
4976 	 * UP interface for hard binding.
4977 	 */
4978 	ASSERT(src_ire == NULL);
4979 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
4980 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4981 	/* src_ire must be a local|loopback */
4982 	if (!IRE_IS_LOCAL(src_ire)) {
4983 		if (ip_debug > 2) {
4984 			pr_addr_dbg("ip_bind_connected_v4: bad connected "
4985 			    "src %s\n", AF_INET, &src_addr);
4986 		}
4987 		error = EADDRNOTAVAIL;
4988 		goto bad_addr;
4989 	}
4990 
4991 	/*
4992 	 * If the source address is a loopback address, the
4993 	 * destination had best be local or multicast.
4994 	 * The transports that can't handle multicast will reject
4995 	 * those addresses.
4996 	 */
4997 	if (src_ire->ire_type == IRE_LOOPBACK &&
4998 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
4999 		ip1dbg(("ip_bind_connected_v4: bad connected loopback\n"));
5000 		error = -1;
5001 		goto bad_addr;
5002 	}
5003 
5004 	/*
5005 	 * Allow setting new policies. For example, disconnects come
5006 	 * down as ipa_t bind. As we would have set conn_policy_cached
5007 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5008 	 * can change after the disconnect.
5009 	 */
5010 	connp->conn_policy_cached = B_FALSE;
5011 
5012 	/*
5013 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5014 	 * can handle their passed-in conn's.
5015 	 */
5016 
5017 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5018 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5019 	connp->conn_lport = lport;
5020 	connp->conn_fport = fport;
5021 	*src_addrp = src_addr;
5022 
5023 	ASSERT(!(ipsec_policy_set && ire_requested));
5024 	if (ire_requested) {
5025 		iulp_t *ulp_info = NULL;
5026 
5027 		/*
5028 		 * Note that sire will not be NULL if this is an off-link
5029 		 * connection and there is not cache for that dest yet.
5030 		 *
5031 		 * XXX Because of an existing bug, if there are multiple
5032 		 * default routes, the IRE returned now may not be the actual
5033 		 * default route used (default routes are chosen in a
5034 		 * round robin fashion).  So if the metrics for different
5035 		 * default routes are different, we may return the wrong
5036 		 * metrics.  This will not be a problem if the existing
5037 		 * bug is fixed.
5038 		 */
5039 		if (sire != NULL) {
5040 			ulp_info = &(sire->ire_uinfo);
5041 		}
5042 		if (!ip_bind_get_ire_v4(mpp, dst_ire, ulp_info, ipst)) {
5043 			error = -1;
5044 			goto bad_addr;
5045 		}
5046 		mp = *mpp;
5047 	} else if (ipsec_policy_set) {
5048 		if (!ip_bind_ipsec_policy_set(connp, mp)) {
5049 			error = -1;
5050 			goto bad_addr;
5051 		}
5052 	}
5053 
5054 	/*
5055 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5056 	 * we'll cache that.  If we don't, we'll inherit global policy.
5057 	 *
5058 	 * We can't insert until the conn reflects the policy. Note that
5059 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5060 	 * connections where we don't have a policy. This is to prevent
5061 	 * global policy lookups in the inbound path.
5062 	 *
5063 	 * If we insert before we set conn_policy_cached,
5064 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5065 	 * because global policy cound be non-empty. We normally call
5066 	 * ipsec_check_policy() for conn_policy_cached connections only if
5067 	 * ipc_in_enforce_policy is set. But in this case,
5068 	 * conn_policy_cached can get set anytime since we made the
5069 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5070 	 * called, which will make the above assumption false.  Thus, we
5071 	 * need to insert after we set conn_policy_cached.
5072 	 */
5073 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5074 		goto bad_addr;
5075 
5076 	if (fanout_insert) {
5077 		/*
5078 		 * The addresses have been verified. Time to insert in
5079 		 * the correct fanout list.
5080 		 */
5081 		error = ipcl_conn_insert(connp, protocol, src_addr,
5082 		    dst_addr, connp->conn_ports);
5083 	}
5084 
5085 	if (error == 0) {
5086 		connp->conn_fully_bound = B_TRUE;
5087 		/*
5088 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5089 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5090 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5091 		 * ip_xxinfo_return(), which performs further checks
5092 		 * against them and upon success, returns the LSO/MDT info
5093 		 * mblk which we will attach to the bind acknowledgment.
5094 		 */
5095 		if (lso_dst_ire != NULL) {
5096 			mblk_t *lsoinfo_mp;
5097 
5098 			ASSERT(ill->ill_lso_capab != NULL);
5099 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5100 			    ill->ill_name, ill->ill_lso_capab)) != NULL) {
5101 				if (mp == NULL) {
5102 					*mpp = lsoinfo_mp;
5103 				} else {
5104 					linkb(mp, lsoinfo_mp);
5105 				}
5106 			}
5107 		} else if (md_dst_ire != NULL) {
5108 			mblk_t *mdinfo_mp;
5109 
5110 			ASSERT(ill->ill_mdt_capab != NULL);
5111 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5112 			    ill->ill_name, ill->ill_mdt_capab)) != NULL) {
5113 				if (mp == NULL) {
5114 					*mpp = mdinfo_mp;
5115 				} else {
5116 					linkb(mp, mdinfo_mp);
5117 				}
5118 			}
5119 		}
5120 	}
5121 bad_addr:
5122 	if (ipsec_policy_set) {
5123 		ASSERT(mp != NULL);
5124 		freeb(mp);
5125 		/*
5126 		 * As of now assume that nothing else accompanies
5127 		 * IPSEC_POLICY_SET.
5128 		 */
5129 		*mpp = NULL;
5130 	}
5131 	if (src_ire != NULL)
5132 		IRE_REFRELE(src_ire);
5133 	if (dst_ire != NULL)
5134 		IRE_REFRELE(dst_ire);
5135 	if (sire != NULL)
5136 		IRE_REFRELE(sire);
5137 	if (md_dst_ire != NULL)
5138 		IRE_REFRELE(md_dst_ire);
5139 	if (lso_dst_ire != NULL)
5140 		IRE_REFRELE(lso_dst_ire);
5141 	return (error);
5142 }
5143 
5144 int
5145 ip_proto_bind_connected_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
5146     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
5147     boolean_t fanout_insert, boolean_t verify_dst)
5148 {
5149 	int error;
5150 	mblk_t	*mp = NULL;
5151 	boolean_t ire_requested;
5152 
5153 	if (ire_mpp)
5154 		mp = *ire_mpp;
5155 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
5156 
5157 	ASSERT(!connp->conn_af_isv6);
5158 	connp->conn_pkt_isv6 = B_FALSE;
5159 	connp->conn_ulp = protocol;
5160 
5161 	/* For raw socket, the local port is not set. */
5162 	if (lport == 0)
5163 		lport = connp->conn_lport;
5164 	error = ip_bind_connected_v4(connp, ire_mpp, protocol,
5165 	    src_addrp, lport, dst_addr, fport, fanout_insert, verify_dst);
5166 	if (error == 0) {
5167 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
5168 		    ire_requested);
5169 	} else if (error < 0) {
5170 		error = -TBADADDR;
5171 	}
5172 	return (error);
5173 }
5174 
5175 /*
5176  * Get the ire in *mpp. Returns false if it fails (due to lack of space).
5177  * Prefers dst_ire over src_ire.
5178  */
5179 static boolean_t
5180 ip_bind_get_ire_v4(mblk_t **mpp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5181 {
5182 	mblk_t	*mp = *mpp;
5183 	ire_t	*ret_ire;
5184 
5185 	ASSERT(mp != NULL);
5186 
5187 	if (ire != NULL) {
5188 		/*
5189 		 * mp initialized above to IRE_DB_REQ_TYPE
5190 		 * appended mblk. Its <upper protocol>'s
5191 		 * job to make sure there is room.
5192 		 */
5193 		if ((mp->b_datap->db_lim - mp->b_rptr) < sizeof (ire_t))
5194 			return (B_FALSE);
5195 
5196 		mp->b_datap->db_type = IRE_DB_TYPE;
5197 		mp->b_wptr = mp->b_rptr + sizeof (ire_t);
5198 		bcopy(ire, mp->b_rptr, sizeof (ire_t));
5199 		ret_ire = (ire_t *)mp->b_rptr;
5200 		/*
5201 		 * Pass the latest setting of the ip_path_mtu_discovery and
5202 		 * copy the ulp info if any.
5203 		 */
5204 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5205 		    IPH_DF : 0;
5206 		if (ulp_info != NULL) {
5207 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5208 			    sizeof (iulp_t));
5209 		}
5210 		ret_ire->ire_mp = mp;
5211 	} else {
5212 		/*
5213 		 * No IRE was found. Remove IRE mblk.
5214 		 */
5215 		*mpp = mp->b_cont;
5216 		freeb(mp);
5217 	}
5218 	return (B_TRUE);
5219 }
5220 
5221 /*
5222  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5223  * the final piece where we don't.  Return a pointer to the first mblk in the
5224  * result, and update the pointer to the next mblk to chew on.  If anything
5225  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5226  * NULL pointer.
5227  */
5228 mblk_t *
5229 ip_carve_mp(mblk_t **mpp, ssize_t len)
5230 {
5231 	mblk_t	*mp0;
5232 	mblk_t	*mp1;
5233 	mblk_t	*mp2;
5234 
5235 	if (!len || !mpp || !(mp0 = *mpp))
5236 		return (NULL);
5237 	/* If we aren't going to consume the first mblk, we need a dup. */
5238 	if (mp0->b_wptr - mp0->b_rptr > len) {
5239 		mp1 = dupb(mp0);
5240 		if (mp1) {
5241 			/* Partition the data between the two mblks. */
5242 			mp1->b_wptr = mp1->b_rptr + len;
5243 			mp0->b_rptr = mp1->b_wptr;
5244 			/*
5245 			 * after adjustments if mblk not consumed is now
5246 			 * unaligned, try to align it. If this fails free
5247 			 * all messages and let upper layer recover.
5248 			 */
5249 			if (!OK_32PTR(mp0->b_rptr)) {
5250 				if (!pullupmsg(mp0, -1)) {
5251 					freemsg(mp0);
5252 					freemsg(mp1);
5253 					*mpp = NULL;
5254 					return (NULL);
5255 				}
5256 			}
5257 		}
5258 		return (mp1);
5259 	}
5260 	/* Eat through as many mblks as we need to get len bytes. */
5261 	len -= mp0->b_wptr - mp0->b_rptr;
5262 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5263 		if (mp2->b_wptr - mp2->b_rptr > len) {
5264 			/*
5265 			 * We won't consume the entire last mblk.  Like
5266 			 * above, dup and partition it.
5267 			 */
5268 			mp1->b_cont = dupb(mp2);
5269 			mp1 = mp1->b_cont;
5270 			if (!mp1) {
5271 				/*
5272 				 * Trouble.  Rather than go to a lot of
5273 				 * trouble to clean up, we free the messages.
5274 				 * This won't be any worse than losing it on
5275 				 * the wire.
5276 				 */
5277 				freemsg(mp0);
5278 				freemsg(mp2);
5279 				*mpp = NULL;
5280 				return (NULL);
5281 			}
5282 			mp1->b_wptr = mp1->b_rptr + len;
5283 			mp2->b_rptr = mp1->b_wptr;
5284 			/*
5285 			 * after adjustments if mblk not consumed is now
5286 			 * unaligned, try to align it. If this fails free
5287 			 * all messages and let upper layer recover.
5288 			 */
5289 			if (!OK_32PTR(mp2->b_rptr)) {
5290 				if (!pullupmsg(mp2, -1)) {
5291 					freemsg(mp0);
5292 					freemsg(mp2);
5293 					*mpp = NULL;
5294 					return (NULL);
5295 				}
5296 			}
5297 			*mpp = mp2;
5298 			return (mp0);
5299 		}
5300 		/* Decrement len by the amount we just got. */
5301 		len -= mp2->b_wptr - mp2->b_rptr;
5302 	}
5303 	/*
5304 	 * len should be reduced to zero now.  If not our caller has
5305 	 * screwed up.
5306 	 */
5307 	if (len) {
5308 		/* Shouldn't happen! */
5309 		freemsg(mp0);
5310 		*mpp = NULL;
5311 		return (NULL);
5312 	}
5313 	/*
5314 	 * We consumed up to exactly the end of an mblk.  Detach the part
5315 	 * we are returning from the rest of the chain.
5316 	 */
5317 	mp1->b_cont = NULL;
5318 	*mpp = mp2;
5319 	return (mp0);
5320 }
5321 
5322 /* The ill stream is being unplumbed. Called from ip_close */
5323 int
5324 ip_modclose(ill_t *ill)
5325 {
5326 	boolean_t success;
5327 	ipsq_t	*ipsq;
5328 	ipif_t	*ipif;
5329 	queue_t	*q = ill->ill_rq;
5330 	ip_stack_t	*ipst = ill->ill_ipst;
5331 
5332 	/*
5333 	 * The punlink prior to this may have initiated a capability
5334 	 * negotiation. But ipsq_enter will block until that finishes or
5335 	 * times out.
5336 	 */
5337 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
5338 
5339 	/*
5340 	 * Open/close/push/pop is guaranteed to be single threaded
5341 	 * per stream by STREAMS. FS guarantees that all references
5342 	 * from top are gone before close is called. So there can't
5343 	 * be another close thread that has set CONDEMNED on this ill.
5344 	 * and cause ipsq_enter to return failure.
5345 	 */
5346 	ASSERT(success);
5347 	ipsq = ill->ill_phyint->phyint_ipsq;
5348 
5349 	/*
5350 	 * Mark it condemned. No new reference will be made to this ill.
5351 	 * Lookup functions will return an error. Threads that try to
5352 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5353 	 * that the refcnt will drop down to zero.
5354 	 */
5355 	mutex_enter(&ill->ill_lock);
5356 	ill->ill_state_flags |= ILL_CONDEMNED;
5357 	for (ipif = ill->ill_ipif; ipif != NULL;
5358 	    ipif = ipif->ipif_next) {
5359 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5360 	}
5361 	/*
5362 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5363 	 * returns  error if ILL_CONDEMNED is set
5364 	 */
5365 	cv_broadcast(&ill->ill_cv);
5366 	mutex_exit(&ill->ill_lock);
5367 
5368 	/*
5369 	 * Send all the deferred DLPI messages downstream which came in
5370 	 * during the small window right before ipsq_enter(). We do this
5371 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5372 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5373 	 */
5374 	ill_dlpi_send_deferred(ill);
5375 
5376 	/*
5377 	 * Shut down fragmentation reassembly.
5378 	 * ill_frag_timer won't start a timer again.
5379 	 * Now cancel any existing timer
5380 	 */
5381 	(void) untimeout(ill->ill_frag_timer_id);
5382 	(void) ill_frag_timeout(ill, 0);
5383 
5384 	/*
5385 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5386 	 * this ill. Then wait for the refcnts to drop to zero.
5387 	 * ill_is_freeable checks whether the ill is really quiescent.
5388 	 * Then make sure that threads that are waiting to enter the
5389 	 * ipsq have seen the error returned by ipsq_enter and have
5390 	 * gone away. Then we call ill_delete_tail which does the
5391 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5392 	 */
5393 	ill_delete(ill);
5394 	mutex_enter(&ill->ill_lock);
5395 	while (!ill_is_freeable(ill))
5396 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5397 	while (ill->ill_waiters)
5398 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5399 
5400 	mutex_exit(&ill->ill_lock);
5401 
5402 	/*
5403 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5404 	 * it held until the end of the function since the cleanup
5405 	 * below needs to be able to use the ip_stack_t.
5406 	 */
5407 	netstack_hold(ipst->ips_netstack);
5408 
5409 	/* qprocsoff is done via ill_delete_tail */
5410 	ill_delete_tail(ill);
5411 	ASSERT(ill->ill_ipst == NULL);
5412 
5413 	/*
5414 	 * Walk through all upper (conn) streams and qenable
5415 	 * those that have queued data.
5416 	 * close synchronization needs this to
5417 	 * be done to ensure that all upper layers blocked
5418 	 * due to flow control to the closing device
5419 	 * get unblocked.
5420 	 */
5421 	ip1dbg(("ip_wsrv: walking\n"));
5422 	conn_walk_drain(ipst);
5423 
5424 	mutex_enter(&ipst->ips_ip_mi_lock);
5425 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5426 	mutex_exit(&ipst->ips_ip_mi_lock);
5427 
5428 	/*
5429 	 * credp could be null if the open didn't succeed and ip_modopen
5430 	 * itself calls ip_close.
5431 	 */
5432 	if (ill->ill_credp != NULL)
5433 		crfree(ill->ill_credp);
5434 
5435 	/*
5436 	 * Now we are done with the module close pieces that
5437 	 * need the netstack_t.
5438 	 */
5439 	netstack_rele(ipst->ips_netstack);
5440 
5441 	mi_close_free((IDP)ill);
5442 	q->q_ptr = WR(q)->q_ptr = NULL;
5443 
5444 	ipsq_exit(ipsq);
5445 
5446 	return (0);
5447 }
5448 
5449 /*
5450  * This is called as part of close() for IP, UDP, ICMP, and RTS
5451  * in order to quiesce the conn.
5452  */
5453 void
5454 ip_quiesce_conn(conn_t *connp)
5455 {
5456 	boolean_t	drain_cleanup_reqd = B_FALSE;
5457 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5458 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5459 	ip_stack_t	*ipst;
5460 
5461 	ASSERT(!IPCL_IS_TCP(connp));
5462 	ipst = connp->conn_netstack->netstack_ip;
5463 
5464 	/*
5465 	 * Mark the conn as closing, and this conn must not be
5466 	 * inserted in future into any list. Eg. conn_drain_insert(),
5467 	 * won't insert this conn into the conn_drain_list.
5468 	 * Similarly ill_pending_mp_add() will not add any mp to
5469 	 * the pending mp list, after this conn has started closing.
5470 	 *
5471 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5472 	 * cannot get set henceforth.
5473 	 */
5474 	mutex_enter(&connp->conn_lock);
5475 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5476 	connp->conn_state_flags |= CONN_CLOSING;
5477 	if (connp->conn_idl != NULL)
5478 		drain_cleanup_reqd = B_TRUE;
5479 	if (connp->conn_oper_pending_ill != NULL)
5480 		conn_ioctl_cleanup_reqd = B_TRUE;
5481 	if (connp->conn_dhcpinit_ill != NULL) {
5482 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5483 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5484 		connp->conn_dhcpinit_ill = NULL;
5485 	}
5486 	if (connp->conn_ilg_inuse != 0)
5487 		ilg_cleanup_reqd = B_TRUE;
5488 	mutex_exit(&connp->conn_lock);
5489 
5490 	if (conn_ioctl_cleanup_reqd)
5491 		conn_ioctl_cleanup(connp);
5492 
5493 	if (is_system_labeled() && connp->conn_anon_port) {
5494 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5495 		    connp->conn_mlp_type, connp->conn_ulp,
5496 		    ntohs(connp->conn_lport), B_FALSE);
5497 		connp->conn_anon_port = 0;
5498 	}
5499 	connp->conn_mlp_type = mlptSingle;
5500 
5501 	/*
5502 	 * Remove this conn from any fanout list it is on.
5503 	 * and then wait for any threads currently operating
5504 	 * on this endpoint to finish
5505 	 */
5506 	ipcl_hash_remove(connp);
5507 
5508 	/*
5509 	 * Remove this conn from the drain list, and do
5510 	 * any other cleanup that may be required.
5511 	 * (Only non-tcp streams may have a non-null conn_idl.
5512 	 * TCP streams are never flow controlled, and
5513 	 * conn_idl will be null)
5514 	 */
5515 	if (drain_cleanup_reqd)
5516 		conn_drain_tail(connp, B_TRUE);
5517 
5518 	if (connp == ipst->ips_ip_g_mrouter)
5519 		(void) ip_mrouter_done(NULL, ipst);
5520 
5521 	if (ilg_cleanup_reqd)
5522 		ilg_delete_all(connp);
5523 
5524 	conn_delete_ire(connp, NULL);
5525 
5526 	/*
5527 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5528 	 * callers from write side can't be there now because close
5529 	 * is in progress. The only other caller is ipcl_walk
5530 	 * which checks for the condemned flag.
5531 	 */
5532 	mutex_enter(&connp->conn_lock);
5533 	connp->conn_state_flags |= CONN_CONDEMNED;
5534 	while (connp->conn_ref != 1)
5535 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5536 	connp->conn_state_flags |= CONN_QUIESCED;
5537 	mutex_exit(&connp->conn_lock);
5538 }
5539 
5540 /* ARGSUSED */
5541 int
5542 ip_close(queue_t *q, int flags)
5543 {
5544 	conn_t		*connp;
5545 
5546 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5547 
5548 	/*
5549 	 * Call the appropriate delete routine depending on whether this is
5550 	 * a module or device.
5551 	 */
5552 	if (WR(q)->q_next != NULL) {
5553 		/* This is a module close */
5554 		return (ip_modclose((ill_t *)q->q_ptr));
5555 	}
5556 
5557 	connp = q->q_ptr;
5558 	ip_quiesce_conn(connp);
5559 
5560 	qprocsoff(q);
5561 
5562 	/*
5563 	 * Now we are truly single threaded on this stream, and can
5564 	 * delete the things hanging off the connp, and finally the connp.
5565 	 * We removed this connp from the fanout list, it cannot be
5566 	 * accessed thru the fanouts, and we already waited for the
5567 	 * conn_ref to drop to 0. We are already in close, so
5568 	 * there cannot be any other thread from the top. qprocsoff
5569 	 * has completed, and service has completed or won't run in
5570 	 * future.
5571 	 */
5572 	ASSERT(connp->conn_ref == 1);
5573 
5574 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5575 
5576 	connp->conn_ref--;
5577 	ipcl_conn_destroy(connp);
5578 
5579 	q->q_ptr = WR(q)->q_ptr = NULL;
5580 	return (0);
5581 }
5582 
5583 /*
5584  * Wapper around putnext() so that ip_rts_request can merely use
5585  * conn_recv.
5586  */
5587 /*ARGSUSED2*/
5588 static void
5589 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5590 {
5591 	conn_t *connp = (conn_t *)arg1;
5592 
5593 	putnext(connp->conn_rq, mp);
5594 }
5595 
5596 /*
5597  * Called when the module is about to be unloaded
5598  */
5599 void
5600 ip_ddi_destroy(void)
5601 {
5602 	tnet_fini();
5603 
5604 	icmp_ddi_g_destroy();
5605 	rts_ddi_g_destroy();
5606 	udp_ddi_g_destroy();
5607 	sctp_ddi_g_destroy();
5608 	tcp_ddi_g_destroy();
5609 	ipsec_policy_g_destroy();
5610 	ipcl_g_destroy();
5611 	ip_net_g_destroy();
5612 	ip_ire_g_fini();
5613 	inet_minor_destroy(ip_minor_arena_sa);
5614 #if defined(_LP64)
5615 	inet_minor_destroy(ip_minor_arena_la);
5616 #endif
5617 
5618 #ifdef DEBUG
5619 	list_destroy(&ip_thread_list);
5620 	rw_destroy(&ip_thread_rwlock);
5621 	tsd_destroy(&ip_thread_data);
5622 #endif
5623 
5624 	netstack_unregister(NS_IP);
5625 }
5626 
5627 /*
5628  * First step in cleanup.
5629  */
5630 /* ARGSUSED */
5631 static void
5632 ip_stack_shutdown(netstackid_t stackid, void *arg)
5633 {
5634 	ip_stack_t *ipst = (ip_stack_t *)arg;
5635 
5636 #ifdef NS_DEBUG
5637 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5638 #endif
5639 
5640 	/* Get rid of loopback interfaces and their IREs */
5641 	ip_loopback_cleanup(ipst);
5642 
5643 	/*
5644 	 * The *_hook_shutdown()s start the process of notifying any
5645 	 * consumers that things are going away.... nothing is destroyed.
5646 	 */
5647 	ipv4_hook_shutdown(ipst);
5648 	ipv6_hook_shutdown(ipst);
5649 
5650 	mutex_enter(&ipst->ips_capab_taskq_lock);
5651 	ipst->ips_capab_taskq_quit = B_TRUE;
5652 	cv_signal(&ipst->ips_capab_taskq_cv);
5653 	mutex_exit(&ipst->ips_capab_taskq_lock);
5654 
5655 	mutex_enter(&ipst->ips_mrt_lock);
5656 	ipst->ips_mrt_flags |= IP_MRT_STOP;
5657 	cv_signal(&ipst->ips_mrt_cv);
5658 	mutex_exit(&ipst->ips_mrt_lock);
5659 }
5660 
5661 /*
5662  * Free the IP stack instance.
5663  */
5664 static void
5665 ip_stack_fini(netstackid_t stackid, void *arg)
5666 {
5667 	ip_stack_t *ipst = (ip_stack_t *)arg;
5668 	int ret;
5669 
5670 #ifdef NS_DEBUG
5671 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5672 #endif
5673 	/*
5674 	 * At this point, all of the notifications that the events and
5675 	 * protocols are going away have been run, meaning that we can
5676 	 * now set about starting to clean things up.
5677 	 */
5678 	ipv4_hook_destroy(ipst);
5679 	ipv6_hook_destroy(ipst);
5680 	ip_net_destroy(ipst);
5681 
5682 	mutex_destroy(&ipst->ips_capab_taskq_lock);
5683 	cv_destroy(&ipst->ips_capab_taskq_cv);
5684 	list_destroy(&ipst->ips_capab_taskq_list);
5685 
5686 	mutex_enter(&ipst->ips_mrt_lock);
5687 	while (!(ipst->ips_mrt_flags & IP_MRT_DONE))
5688 		cv_wait(&ipst->ips_mrt_done_cv, &ipst->ips_mrt_lock);
5689 	mutex_destroy(&ipst->ips_mrt_lock);
5690 	cv_destroy(&ipst->ips_mrt_cv);
5691 	cv_destroy(&ipst->ips_mrt_done_cv);
5692 
5693 	ipmp_destroy(ipst);
5694 	rw_destroy(&ipst->ips_srcid_lock);
5695 
5696 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5697 	ipst->ips_ip_mibkp = NULL;
5698 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5699 	ipst->ips_icmp_mibkp = NULL;
5700 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5701 	ipst->ips_ip_kstat = NULL;
5702 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5703 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5704 	ipst->ips_ip6_kstat = NULL;
5705 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5706 
5707 	nd_free(&ipst->ips_ip_g_nd);
5708 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5709 	ipst->ips_param_arr = NULL;
5710 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5711 	ipst->ips_ndp_arr = NULL;
5712 
5713 	ip_mrouter_stack_destroy(ipst);
5714 
5715 	mutex_destroy(&ipst->ips_ip_mi_lock);
5716 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5717 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5718 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5719 
5720 	ret = untimeout(ipst->ips_igmp_timeout_id);
5721 	if (ret == -1) {
5722 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5723 	} else {
5724 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5725 		ipst->ips_igmp_timeout_id = 0;
5726 	}
5727 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5728 	if (ret == -1) {
5729 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5730 	} else {
5731 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5732 		ipst->ips_igmp_slowtimeout_id = 0;
5733 	}
5734 	ret = untimeout(ipst->ips_mld_timeout_id);
5735 	if (ret == -1) {
5736 		ASSERT(ipst->ips_mld_timeout_id == 0);
5737 	} else {
5738 		ASSERT(ipst->ips_mld_timeout_id != 0);
5739 		ipst->ips_mld_timeout_id = 0;
5740 	}
5741 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5742 	if (ret == -1) {
5743 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5744 	} else {
5745 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5746 		ipst->ips_mld_slowtimeout_id = 0;
5747 	}
5748 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5749 	if (ret == -1) {
5750 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5751 	} else {
5752 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5753 		ipst->ips_ip_ire_expire_id = 0;
5754 	}
5755 
5756 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5757 	mutex_destroy(&ipst->ips_mld_timer_lock);
5758 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5759 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5760 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5761 	rw_destroy(&ipst->ips_ill_g_lock);
5762 
5763 	ipobs_fini(ipst);
5764 	ip_ire_fini(ipst);
5765 	ip6_asp_free(ipst);
5766 	conn_drain_fini(ipst);
5767 	ipcl_destroy(ipst);
5768 
5769 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5770 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5771 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5772 	ipst->ips_ndp4 = NULL;
5773 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5774 	ipst->ips_ndp6 = NULL;
5775 
5776 	if (ipst->ips_loopback_ksp != NULL) {
5777 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5778 		ipst->ips_loopback_ksp = NULL;
5779 	}
5780 
5781 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5782 	ipst->ips_phyint_g_list = NULL;
5783 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5784 	ipst->ips_ill_g_heads = NULL;
5785 
5786 	ldi_ident_release(ipst->ips_ldi_ident);
5787 	kmem_free(ipst, sizeof (*ipst));
5788 }
5789 
5790 /*
5791  * This function is called from the TSD destructor, and is used to debug
5792  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5793  * details.
5794  */
5795 static void
5796 ip_thread_exit(void *phash)
5797 {
5798 	th_hash_t *thh = phash;
5799 
5800 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5801 	list_remove(&ip_thread_list, thh);
5802 	rw_exit(&ip_thread_rwlock);
5803 	mod_hash_destroy_hash(thh->thh_hash);
5804 	kmem_free(thh, sizeof (*thh));
5805 }
5806 
5807 /*
5808  * Called when the IP kernel module is loaded into the kernel
5809  */
5810 void
5811 ip_ddi_init(void)
5812 {
5813 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
5814 
5815 	/*
5816 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5817 	 * initial devices: ip, ip6, tcp, tcp6.
5818 	 */
5819 	/*
5820 	 * If this is a 64-bit kernel, then create two separate arenas -
5821 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5822 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5823 	 */
5824 	ip_minor_arena_la = NULL;
5825 	ip_minor_arena_sa = NULL;
5826 #if defined(_LP64)
5827 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5828 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5829 		cmn_err(CE_PANIC,
5830 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5831 	}
5832 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5833 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5834 		cmn_err(CE_PANIC,
5835 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5836 	}
5837 #else
5838 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5839 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5840 		cmn_err(CE_PANIC,
5841 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5842 	}
5843 #endif
5844 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5845 
5846 	ipcl_g_init();
5847 	ip_ire_g_init();
5848 	ip_net_g_init();
5849 
5850 #ifdef DEBUG
5851 	tsd_create(&ip_thread_data, ip_thread_exit);
5852 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5853 	list_create(&ip_thread_list, sizeof (th_hash_t),
5854 	    offsetof(th_hash_t, thh_link));
5855 #endif
5856 
5857 	/*
5858 	 * We want to be informed each time a stack is created or
5859 	 * destroyed in the kernel, so we can maintain the
5860 	 * set of udp_stack_t's.
5861 	 */
5862 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5863 	    ip_stack_fini);
5864 
5865 	ipsec_policy_g_init();
5866 	tcp_ddi_g_init();
5867 	sctp_ddi_g_init();
5868 
5869 	tnet_init();
5870 
5871 	udp_ddi_g_init();
5872 	rts_ddi_g_init();
5873 	icmp_ddi_g_init();
5874 }
5875 
5876 /*
5877  * Initialize the IP stack instance.
5878  */
5879 static void *
5880 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5881 {
5882 	ip_stack_t	*ipst;
5883 	ipparam_t	*pa;
5884 	ipndp_t		*na;
5885 	major_t		major;
5886 
5887 #ifdef NS_DEBUG
5888 	printf("ip_stack_init(stack %d)\n", stackid);
5889 #endif
5890 
5891 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5892 	ipst->ips_netstack = ns;
5893 
5894 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5895 	    KM_SLEEP);
5896 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5897 	    KM_SLEEP);
5898 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5899 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5900 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5901 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5902 
5903 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5904 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5905 	ipst->ips_igmp_deferred_next = INFINITY;
5906 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5907 	ipst->ips_mld_deferred_next = INFINITY;
5908 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5909 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5910 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5911 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5912 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5913 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5914 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5915 
5916 	ipcl_init(ipst);
5917 	ip_ire_init(ipst);
5918 	ip6_asp_init(ipst);
5919 	ipif_init(ipst);
5920 	conn_drain_init(ipst);
5921 	ip_mrouter_stack_init(ipst);
5922 
5923 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
5924 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
5925 
5926 	ipst->ips_ip_multirt_log_interval = 1000;
5927 
5928 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
5929 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
5930 	ipst->ips_ill_index = 1;
5931 
5932 	ipst->ips_saved_ip_g_forward = -1;
5933 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
5934 
5935 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
5936 	ipst->ips_param_arr = pa;
5937 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
5938 
5939 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
5940 	ipst->ips_ndp_arr = na;
5941 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5942 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
5943 	    (caddr_t)&ipst->ips_ip_g_forward;
5944 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
5945 	    (caddr_t)&ipst->ips_ipv6_forward;
5946 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
5947 	    "ip_cgtp_filter") == 0);
5948 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
5949 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
5950 
5951 	(void) ip_param_register(&ipst->ips_ip_g_nd,
5952 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
5953 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
5954 
5955 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
5956 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
5957 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
5958 	ipst->ips_ip6_kstat =
5959 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
5960 
5961 	ipst->ips_ip_src_id = 1;
5962 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
5963 
5964 	ipobs_init(ipst);
5965 	ip_net_init(ipst, ns);
5966 	ipv4_hook_init(ipst);
5967 	ipv6_hook_init(ipst);
5968 	ipmp_init(ipst);
5969 
5970 	/*
5971 	 * Create the taskq dispatcher thread and initialize related stuff.
5972 	 */
5973 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
5974 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
5975 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
5976 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
5977 	list_create(&ipst->ips_capab_taskq_list, sizeof (mblk_t),
5978 	    offsetof(mblk_t, b_next));
5979 
5980 	/*
5981 	 * Create the mcast_restart_timers_thread() worker thread.
5982 	 */
5983 	mutex_init(&ipst->ips_mrt_lock, NULL, MUTEX_DEFAULT, NULL);
5984 	cv_init(&ipst->ips_mrt_cv, NULL, CV_DEFAULT, NULL);
5985 	cv_init(&ipst->ips_mrt_done_cv, NULL, CV_DEFAULT, NULL);
5986 	ipst->ips_mrt_thread = thread_create(NULL, 0,
5987 	    mcast_restart_timers_thread, ipst, 0, &p0, TS_RUN, minclsyspri);
5988 
5989 	major = mod_name_to_major(INET_NAME);
5990 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
5991 	return (ipst);
5992 }
5993 
5994 /*
5995  * Allocate and initialize a DLPI template of the specified length.  (May be
5996  * called as writer.)
5997  */
5998 mblk_t *
5999 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6000 {
6001 	mblk_t	*mp;
6002 
6003 	mp = allocb(len, BPRI_MED);
6004 	if (!mp)
6005 		return (NULL);
6006 
6007 	/*
6008 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6009 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6010 	 * that other DLPI are M_PROTO.
6011 	 */
6012 	if (prim == DL_INFO_REQ) {
6013 		mp->b_datap->db_type = M_PCPROTO;
6014 	} else {
6015 		mp->b_datap->db_type = M_PROTO;
6016 	}
6017 
6018 	mp->b_wptr = mp->b_rptr + len;
6019 	bzero(mp->b_rptr, len);
6020 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6021 	return (mp);
6022 }
6023 
6024 /*
6025  * Allocate and initialize a DLPI notification.  (May be called as writer.)
6026  */
6027 mblk_t *
6028 ip_dlnotify_alloc(uint_t notification, uint_t data)
6029 {
6030 	dl_notify_ind_t	*notifyp;
6031 	mblk_t		*mp;
6032 
6033 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
6034 		return (NULL);
6035 
6036 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
6037 	notifyp->dl_notification = notification;
6038 	notifyp->dl_data = data;
6039 	return (mp);
6040 }
6041 
6042 /*
6043  * Debug formatting routine.  Returns a character string representation of the
6044  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6045  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6046  *
6047  * Once the ndd table-printing interfaces are removed, this can be changed to
6048  * standard dotted-decimal form.
6049  */
6050 char *
6051 ip_dot_addr(ipaddr_t addr, char *buf)
6052 {
6053 	uint8_t *ap = (uint8_t *)&addr;
6054 
6055 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6056 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6057 	return (buf);
6058 }
6059 
6060 /*
6061  * Write the given MAC address as a printable string in the usual colon-
6062  * separated format.
6063  */
6064 const char *
6065 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6066 {
6067 	char *bp;
6068 
6069 	if (alen == 0 || buflen < 4)
6070 		return ("?");
6071 	bp = buf;
6072 	for (;;) {
6073 		/*
6074 		 * If there are more MAC address bytes available, but we won't
6075 		 * have any room to print them, then add "..." to the string
6076 		 * instead.  See below for the 'magic number' explanation.
6077 		 */
6078 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6079 			(void) strcpy(bp, "...");
6080 			break;
6081 		}
6082 		(void) sprintf(bp, "%02x", *addr++);
6083 		bp += 2;
6084 		if (--alen == 0)
6085 			break;
6086 		*bp++ = ':';
6087 		buflen -= 3;
6088 		/*
6089 		 * At this point, based on the first 'if' statement above,
6090 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6091 		 * buflen >= 4.  The first case leaves room for the final "xx"
6092 		 * number and trailing NUL byte.  The second leaves room for at
6093 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6094 		 * that statement.
6095 		 */
6096 	}
6097 	return (buf);
6098 }
6099 
6100 /*
6101  * Send an ICMP error after patching up the packet appropriately.  Returns
6102  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6103  */
6104 static boolean_t
6105 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6106     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6107     zoneid_t zoneid, ip_stack_t *ipst)
6108 {
6109 	ipha_t *ipha;
6110 	mblk_t *first_mp;
6111 	boolean_t secure;
6112 	unsigned char db_type;
6113 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6114 
6115 	first_mp = mp;
6116 	if (mctl_present) {
6117 		mp = mp->b_cont;
6118 		secure = ipsec_in_is_secure(first_mp);
6119 		ASSERT(mp != NULL);
6120 	} else {
6121 		/*
6122 		 * If this is an ICMP error being reported - which goes
6123 		 * up as M_CTLs, we need to convert them to M_DATA till
6124 		 * we finish checking with global policy because
6125 		 * ipsec_check_global_policy() assumes M_DATA as clear
6126 		 * and M_CTL as secure.
6127 		 */
6128 		db_type = DB_TYPE(mp);
6129 		DB_TYPE(mp) = M_DATA;
6130 		secure = B_FALSE;
6131 	}
6132 	/*
6133 	 * We are generating an icmp error for some inbound packet.
6134 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6135 	 * Before we generate an error, check with global policy
6136 	 * to see whether this is allowed to enter the system. As
6137 	 * there is no "conn", we are checking with global policy.
6138 	 */
6139 	ipha = (ipha_t *)mp->b_rptr;
6140 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6141 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6142 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6143 		if (first_mp == NULL)
6144 			return (B_FALSE);
6145 	}
6146 
6147 	if (!mctl_present)
6148 		DB_TYPE(mp) = db_type;
6149 
6150 	if (flags & IP_FF_SEND_ICMP) {
6151 		if (flags & IP_FF_HDR_COMPLETE) {
6152 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6153 				freemsg(first_mp);
6154 				return (B_TRUE);
6155 			}
6156 		}
6157 		if (flags & IP_FF_CKSUM) {
6158 			/*
6159 			 * Have to correct checksum since
6160 			 * the packet might have been
6161 			 * fragmented and the reassembly code in ip_rput
6162 			 * does not restore the IP checksum.
6163 			 */
6164 			ipha->ipha_hdr_checksum = 0;
6165 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6166 		}
6167 		switch (icmp_type) {
6168 		case ICMP_DEST_UNREACHABLE:
6169 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6170 			    ipst);
6171 			break;
6172 		default:
6173 			freemsg(first_mp);
6174 			break;
6175 		}
6176 	} else {
6177 		freemsg(first_mp);
6178 		return (B_FALSE);
6179 	}
6180 
6181 	return (B_TRUE);
6182 }
6183 
6184 /*
6185  * Used to send an ICMP error message when a packet is received for
6186  * a protocol that is not supported. The mblk passed as argument
6187  * is consumed by this function.
6188  */
6189 void
6190 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6191     ip_stack_t *ipst)
6192 {
6193 	mblk_t *mp;
6194 	ipha_t *ipha;
6195 	ill_t *ill;
6196 	ipsec_in_t *ii;
6197 
6198 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6199 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6200 
6201 	mp = ipsec_mp->b_cont;
6202 	ipsec_mp->b_cont = NULL;
6203 	ipha = (ipha_t *)mp->b_rptr;
6204 	/* Get ill from index in ipsec_in_t. */
6205 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6206 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6207 	    ipst);
6208 	if (ill != NULL) {
6209 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6210 			if (ip_fanout_send_icmp(q, mp, flags,
6211 			    ICMP_DEST_UNREACHABLE,
6212 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6213 				BUMP_MIB(ill->ill_ip_mib,
6214 				    ipIfStatsInUnknownProtos);
6215 			}
6216 		} else {
6217 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6218 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6219 			    0, B_FALSE, zoneid, ipst)) {
6220 				BUMP_MIB(ill->ill_ip_mib,
6221 				    ipIfStatsInUnknownProtos);
6222 			}
6223 		}
6224 		ill_refrele(ill);
6225 	} else { /* re-link for the freemsg() below. */
6226 		ipsec_mp->b_cont = mp;
6227 	}
6228 
6229 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6230 	freemsg(ipsec_mp);
6231 }
6232 
6233 /*
6234  * See if the inbound datagram has had IPsec processing applied to it.
6235  */
6236 boolean_t
6237 ipsec_in_is_secure(mblk_t *ipsec_mp)
6238 {
6239 	ipsec_in_t *ii;
6240 
6241 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6242 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6243 
6244 	if (ii->ipsec_in_loopback) {
6245 		return (ii->ipsec_in_secure);
6246 	} else {
6247 		return (ii->ipsec_in_ah_sa != NULL ||
6248 		    ii->ipsec_in_esp_sa != NULL ||
6249 		    ii->ipsec_in_decaps);
6250 	}
6251 }
6252 
6253 /*
6254  * Handle protocols with which IP is less intimate.  There
6255  * can be more than one stream bound to a particular
6256  * protocol.  When this is the case, normally each one gets a copy
6257  * of any incoming packets.
6258  *
6259  * IPsec NOTE :
6260  *
6261  * Don't allow a secure packet going up a non-secure connection.
6262  * We don't allow this because
6263  *
6264  * 1) Reply might go out in clear which will be dropped at
6265  *    the sending side.
6266  * 2) If the reply goes out in clear it will give the
6267  *    adversary enough information for getting the key in
6268  *    most of the cases.
6269  *
6270  * Moreover getting a secure packet when we expect clear
6271  * implies that SA's were added without checking for
6272  * policy on both ends. This should not happen once ISAKMP
6273  * is used to negotiate SAs as SAs will be added only after
6274  * verifying the policy.
6275  *
6276  * NOTE : If the packet was tunneled and not multicast we only send
6277  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6278  * back to delivering packets to AF_INET6 raw sockets.
6279  *
6280  * IPQoS Notes:
6281  * Once we have determined the client, invoke IPPF processing.
6282  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6283  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6284  * ip_policy will be false.
6285  *
6286  * Zones notes:
6287  * Currently only applications in the global zone can create raw sockets for
6288  * protocols other than ICMP. So unlike the broadcast / multicast case of
6289  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6290  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6291  */
6292 static void
6293 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6294     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6295     zoneid_t zoneid)
6296 {
6297 	queue_t	*rq;
6298 	mblk_t	*mp1, *first_mp1;
6299 	uint_t	protocol = ipha->ipha_protocol;
6300 	ipaddr_t dst;
6301 	boolean_t one_only;
6302 	mblk_t *first_mp = mp;
6303 	boolean_t secure;
6304 	uint32_t ill_index;
6305 	conn_t	*connp, *first_connp, *next_connp;
6306 	connf_t	*connfp;
6307 	boolean_t shared_addr;
6308 	mib2_ipIfStatsEntry_t *mibptr;
6309 	ip_stack_t *ipst = recv_ill->ill_ipst;
6310 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6311 
6312 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6313 	if (mctl_present) {
6314 		mp = first_mp->b_cont;
6315 		secure = ipsec_in_is_secure(first_mp);
6316 		ASSERT(mp != NULL);
6317 	} else {
6318 		secure = B_FALSE;
6319 	}
6320 	dst = ipha->ipha_dst;
6321 	/*
6322 	 * If the packet was tunneled and not multicast we only send to it
6323 	 * the first match.
6324 	 */
6325 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6326 	    !CLASSD(dst));
6327 
6328 	shared_addr = (zoneid == ALL_ZONES);
6329 	if (shared_addr) {
6330 		/*
6331 		 * We don't allow multilevel ports for raw IP, so no need to
6332 		 * check for that here.
6333 		 */
6334 		zoneid = tsol_packet_to_zoneid(mp);
6335 	}
6336 
6337 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6338 	mutex_enter(&connfp->connf_lock);
6339 	connp = connfp->connf_head;
6340 	for (connp = connfp->connf_head; connp != NULL;
6341 	    connp = connp->conn_next) {
6342 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6343 		    zoneid) &&
6344 		    (!is_system_labeled() ||
6345 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6346 		    connp))) {
6347 			break;
6348 		}
6349 	}
6350 
6351 	if (connp == NULL) {
6352 		/*
6353 		 * No one bound to these addresses.  Is
6354 		 * there a client that wants all
6355 		 * unclaimed datagrams?
6356 		 */
6357 		mutex_exit(&connfp->connf_lock);
6358 		/*
6359 		 * Check for IPPROTO_ENCAP...
6360 		 */
6361 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6362 			/*
6363 			 * If an IPsec mblk is here on a multicast
6364 			 * tunnel (using ip_mroute stuff), check policy here,
6365 			 * THEN ship off to ip_mroute_decap().
6366 			 *
6367 			 * BTW,  If I match a configured IP-in-IP
6368 			 * tunnel, this path will not be reached, and
6369 			 * ip_mroute_decap will never be called.
6370 			 */
6371 			first_mp = ipsec_check_global_policy(first_mp, connp,
6372 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6373 			if (first_mp != NULL) {
6374 				if (mctl_present)
6375 					freeb(first_mp);
6376 				ip_mroute_decap(q, mp, ill);
6377 			} /* Else we already freed everything! */
6378 		} else {
6379 			/*
6380 			 * Otherwise send an ICMP protocol unreachable.
6381 			 */
6382 			if (ip_fanout_send_icmp(q, first_mp, flags,
6383 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6384 			    mctl_present, zoneid, ipst)) {
6385 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6386 			}
6387 		}
6388 		return;
6389 	}
6390 
6391 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
6392 
6393 	CONN_INC_REF(connp);
6394 	first_connp = connp;
6395 
6396 	/*
6397 	 * Only send message to one tunnel driver by immediately
6398 	 * terminating the loop.
6399 	 */
6400 	connp = one_only ? NULL : connp->conn_next;
6401 
6402 	for (;;) {
6403 		while (connp != NULL) {
6404 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6405 			    flags, zoneid) &&
6406 			    (!is_system_labeled() ||
6407 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6408 			    shared_addr, connp)))
6409 				break;
6410 			connp = connp->conn_next;
6411 		}
6412 
6413 		/*
6414 		 * Copy the packet.
6415 		 */
6416 		if (connp == NULL ||
6417 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6418 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6419 			/*
6420 			 * No more interested clients or memory
6421 			 * allocation failed
6422 			 */
6423 			connp = first_connp;
6424 			break;
6425 		}
6426 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
6427 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6428 		CONN_INC_REF(connp);
6429 		mutex_exit(&connfp->connf_lock);
6430 		rq = connp->conn_rq;
6431 
6432 		/*
6433 		 * Check flow control
6434 		 */
6435 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6436 		    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6437 			if (flags & IP_FF_RAWIP) {
6438 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6439 			} else {
6440 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6441 			}
6442 
6443 			freemsg(first_mp1);
6444 		} else {
6445 			/*
6446 			 * Don't enforce here if we're an actual tunnel -
6447 			 * let "tun" do it instead.
6448 			 */
6449 			if (!IPCL_IS_IPTUN(connp) &&
6450 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6451 			    secure)) {
6452 				first_mp1 = ipsec_check_inbound_policy
6453 				    (first_mp1, connp, ipha, NULL,
6454 				    mctl_present);
6455 			}
6456 			if (first_mp1 != NULL) {
6457 				int in_flags = 0;
6458 				/*
6459 				 * ip_fanout_proto also gets called from
6460 				 * icmp_inbound_error_fanout, in which case
6461 				 * the msg type is M_CTL.  Don't add info
6462 				 * in this case for the time being. In future
6463 				 * when there is a need for knowing the
6464 				 * inbound iface index for ICMP error msgs,
6465 				 * then this can be changed.
6466 				 */
6467 				if (connp->conn_recvif)
6468 					in_flags = IPF_RECVIF;
6469 				/*
6470 				 * The ULP may support IP_RECVPKTINFO for both
6471 				 * IP v4 and v6 so pass the appropriate argument
6472 				 * based on conn IP version.
6473 				 */
6474 				if (connp->conn_ip_recvpktinfo) {
6475 					if (connp->conn_af_isv6) {
6476 						/*
6477 						 * V6 only needs index
6478 						 */
6479 						in_flags |= IPF_RECVIF;
6480 					} else {
6481 						/*
6482 						 * V4 needs index +
6483 						 * matching address.
6484 						 */
6485 						in_flags |= IPF_RECVADDR;
6486 					}
6487 				}
6488 				if ((in_flags != 0) &&
6489 				    (mp->b_datap->db_type != M_CTL)) {
6490 					/*
6491 					 * the actual data will be
6492 					 * contained in b_cont upon
6493 					 * successful return of the
6494 					 * following call else
6495 					 * original mblk is returned
6496 					 */
6497 					ASSERT(recv_ill != NULL);
6498 					mp1 = ip_add_info(mp1, recv_ill,
6499 					    in_flags, IPCL_ZONEID(connp), ipst);
6500 				}
6501 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6502 				if (mctl_present)
6503 					freeb(first_mp1);
6504 				(connp->conn_recv)(connp, mp1, NULL);
6505 			}
6506 		}
6507 		mutex_enter(&connfp->connf_lock);
6508 		/* Follow the next pointer before releasing the conn. */
6509 		next_connp = connp->conn_next;
6510 		CONN_DEC_REF(connp);
6511 		connp = next_connp;
6512 	}
6513 
6514 	/* Last one.  Send it upstream. */
6515 	mutex_exit(&connfp->connf_lock);
6516 
6517 	/*
6518 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6519 	 * will be set to false.
6520 	 */
6521 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6522 		ill_index = ill->ill_phyint->phyint_ifindex;
6523 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6524 		if (mp == NULL) {
6525 			CONN_DEC_REF(connp);
6526 			if (mctl_present) {
6527 				freeb(first_mp);
6528 			}
6529 			return;
6530 		}
6531 	}
6532 
6533 	rq = connp->conn_rq;
6534 	/*
6535 	 * Check flow control
6536 	 */
6537 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6538 	    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6539 		if (flags & IP_FF_RAWIP) {
6540 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6541 		} else {
6542 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6543 		}
6544 
6545 		freemsg(first_mp);
6546 	} else {
6547 		if (IPCL_IS_IPTUN(connp)) {
6548 			/*
6549 			 * Tunneled packet.  We enforce policy in the tunnel
6550 			 * module itself.
6551 			 *
6552 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6553 			 * a policy check.
6554 			 * FIXME to use conn_recv for tun later.
6555 			 */
6556 			putnext(rq, first_mp);
6557 			CONN_DEC_REF(connp);
6558 			return;
6559 		}
6560 
6561 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6562 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6563 			    ipha, NULL, mctl_present);
6564 		}
6565 
6566 		if (first_mp != NULL) {
6567 			int in_flags = 0;
6568 
6569 			/*
6570 			 * ip_fanout_proto also gets called
6571 			 * from icmp_inbound_error_fanout, in
6572 			 * which case the msg type is M_CTL.
6573 			 * Don't add info in this case for time
6574 			 * being. In future when there is a
6575 			 * need for knowing the inbound iface
6576 			 * index for ICMP error msgs, then this
6577 			 * can be changed
6578 			 */
6579 			if (connp->conn_recvif)
6580 				in_flags = IPF_RECVIF;
6581 			if (connp->conn_ip_recvpktinfo) {
6582 				if (connp->conn_af_isv6) {
6583 					/*
6584 					 * V6 only needs index
6585 					 */
6586 					in_flags |= IPF_RECVIF;
6587 				} else {
6588 					/*
6589 					 * V4 needs index +
6590 					 * matching address.
6591 					 */
6592 					in_flags |= IPF_RECVADDR;
6593 				}
6594 			}
6595 			if ((in_flags != 0) &&
6596 			    (mp->b_datap->db_type != M_CTL)) {
6597 
6598 				/*
6599 				 * the actual data will be contained in
6600 				 * b_cont upon successful return
6601 				 * of the following call else original
6602 				 * mblk is returned
6603 				 */
6604 				ASSERT(recv_ill != NULL);
6605 				mp = ip_add_info(mp, recv_ill,
6606 				    in_flags, IPCL_ZONEID(connp), ipst);
6607 			}
6608 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6609 			(connp->conn_recv)(connp, mp, NULL);
6610 			if (mctl_present)
6611 				freeb(first_mp);
6612 		}
6613 	}
6614 	CONN_DEC_REF(connp);
6615 }
6616 
6617 /*
6618  * Fanout for TCP packets
6619  * The caller puts <fport, lport> in the ports parameter.
6620  *
6621  * IPQoS Notes
6622  * Before sending it to the client, invoke IPPF processing.
6623  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6624  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6625  * ip_policy is false.
6626  */
6627 static void
6628 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6629     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6630 {
6631 	mblk_t  *first_mp;
6632 	boolean_t secure;
6633 	uint32_t ill_index;
6634 	int	ip_hdr_len;
6635 	tcph_t	*tcph;
6636 	boolean_t syn_present = B_FALSE;
6637 	conn_t	*connp;
6638 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6639 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6640 
6641 	ASSERT(recv_ill != NULL);
6642 
6643 	first_mp = mp;
6644 	if (mctl_present) {
6645 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6646 		mp = first_mp->b_cont;
6647 		secure = ipsec_in_is_secure(first_mp);
6648 		ASSERT(mp != NULL);
6649 	} else {
6650 		secure = B_FALSE;
6651 	}
6652 
6653 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6654 
6655 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6656 	    zoneid, ipst)) == NULL) {
6657 		/*
6658 		 * No connected connection or listener. Send a
6659 		 * TH_RST via tcp_xmit_listeners_reset.
6660 		 */
6661 
6662 		/* Initiate IPPf processing, if needed. */
6663 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6664 			uint32_t ill_index;
6665 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6666 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6667 			if (first_mp == NULL)
6668 				return;
6669 		}
6670 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6671 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6672 		    zoneid));
6673 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6674 		    ipst->ips_netstack->netstack_tcp, NULL);
6675 		return;
6676 	}
6677 
6678 	/*
6679 	 * Allocate the SYN for the TCP connection here itself
6680 	 */
6681 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6682 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6683 		if (IPCL_IS_TCP(connp)) {
6684 			squeue_t *sqp;
6685 
6686 			/*
6687 			 * For fused tcp loopback, assign the eager's
6688 			 * squeue to be that of the active connect's.
6689 			 * Note that we don't check for IP_FF_LOOPBACK
6690 			 * here since this routine gets called only
6691 			 * for loopback (unlike the IPv6 counterpart).
6692 			 */
6693 			ASSERT(Q_TO_CONN(q) != NULL);
6694 			if (do_tcp_fusion &&
6695 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6696 			    !secure &&
6697 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6698 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6699 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6700 				sqp = Q_TO_CONN(q)->conn_sqp;
6701 			} else {
6702 				sqp = IP_SQUEUE_GET(lbolt);
6703 			}
6704 
6705 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6706 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6707 			syn_present = B_TRUE;
6708 		}
6709 	}
6710 
6711 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6712 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6713 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6714 		if ((flags & TH_RST) || (flags & TH_URG)) {
6715 			CONN_DEC_REF(connp);
6716 			freemsg(first_mp);
6717 			return;
6718 		}
6719 		if (flags & TH_ACK) {
6720 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6721 			    ipst->ips_netstack->netstack_tcp, connp);
6722 			CONN_DEC_REF(connp);
6723 			return;
6724 		}
6725 
6726 		CONN_DEC_REF(connp);
6727 		freemsg(first_mp);
6728 		return;
6729 	}
6730 
6731 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6732 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6733 		    NULL, mctl_present);
6734 		if (first_mp == NULL) {
6735 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6736 			CONN_DEC_REF(connp);
6737 			return;
6738 		}
6739 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6740 			ASSERT(syn_present);
6741 			if (mctl_present) {
6742 				ASSERT(first_mp != mp);
6743 				first_mp->b_datap->db_struioflag |=
6744 				    STRUIO_POLICY;
6745 			} else {
6746 				ASSERT(first_mp == mp);
6747 				mp->b_datap->db_struioflag &=
6748 				    ~STRUIO_EAGER;
6749 				mp->b_datap->db_struioflag |=
6750 				    STRUIO_POLICY;
6751 			}
6752 		} else {
6753 			/*
6754 			 * Discard first_mp early since we're dealing with a
6755 			 * fully-connected conn_t and tcp doesn't do policy in
6756 			 * this case.
6757 			 */
6758 			if (mctl_present) {
6759 				freeb(first_mp);
6760 				mctl_present = B_FALSE;
6761 			}
6762 			first_mp = mp;
6763 		}
6764 	}
6765 
6766 	/*
6767 	 * Initiate policy processing here if needed. If we get here from
6768 	 * icmp_inbound_error_fanout, ip_policy is false.
6769 	 */
6770 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6771 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6772 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6773 		if (mp == NULL) {
6774 			CONN_DEC_REF(connp);
6775 			if (mctl_present)
6776 				freeb(first_mp);
6777 			return;
6778 		} else if (mctl_present) {
6779 			ASSERT(first_mp != mp);
6780 			first_mp->b_cont = mp;
6781 		} else {
6782 			first_mp = mp;
6783 		}
6784 	}
6785 
6786 
6787 
6788 	/* Handle socket options. */
6789 	if (!syn_present &&
6790 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6791 		/* Add header */
6792 		ASSERT(recv_ill != NULL);
6793 		/*
6794 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6795 		 * IPF_RECVIF.
6796 		 */
6797 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6798 		    ipst);
6799 		if (mp == NULL) {
6800 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6801 			CONN_DEC_REF(connp);
6802 			if (mctl_present)
6803 				freeb(first_mp);
6804 			return;
6805 		} else if (mctl_present) {
6806 			/*
6807 			 * ip_add_info might return a new mp.
6808 			 */
6809 			ASSERT(first_mp != mp);
6810 			first_mp->b_cont = mp;
6811 		} else {
6812 			first_mp = mp;
6813 		}
6814 	}
6815 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6816 	if (IPCL_IS_TCP(connp)) {
6817 		/* do not drain, certain use cases can blow the stack */
6818 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, connp->conn_recv,
6819 		    connp, ip_squeue_flag, SQTAG_IP_FANOUT_TCP);
6820 	} else {
6821 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6822 		(connp->conn_recv)(connp, first_mp, NULL);
6823 		CONN_DEC_REF(connp);
6824 	}
6825 }
6826 
6827 /*
6828  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6829  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6830  * is not consumed.
6831  *
6832  * One of four things can happen, all of which affect the passed-in mblk:
6833  *
6834  * 1.) ICMP messages that go through here just get returned TRUE.
6835  *
6836  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6837  *
6838  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6839  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6840  *
6841  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6842  */
6843 static boolean_t
6844 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6845     ipsec_stack_t *ipss)
6846 {
6847 	int shift, plen, iph_len;
6848 	ipha_t *ipha;
6849 	udpha_t *udpha;
6850 	uint32_t *spi;
6851 	uint32_t esp_ports;
6852 	uint8_t *orptr;
6853 	boolean_t free_ire;
6854 
6855 	if (DB_TYPE(mp) == M_CTL) {
6856 		/*
6857 		 * ICMP message with UDP inside.  Don't bother stripping, just
6858 		 * send it up.
6859 		 *
6860 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6861 		 * to ignore errors set by ICMP anyway ('cause they might be
6862 		 * forged), but that's the app's decision, not ours.
6863 		 */
6864 
6865 		/* Bunch of reality checks for DEBUG kernels... */
6866 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6867 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6868 
6869 		return (B_TRUE);
6870 	}
6871 
6872 	ipha = (ipha_t *)mp->b_rptr;
6873 	iph_len = IPH_HDR_LENGTH(ipha);
6874 	plen = ntohs(ipha->ipha_length);
6875 
6876 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6877 		/*
6878 		 * Most likely a keepalive for the benefit of an intervening
6879 		 * NAT.  These aren't for us, per se, so drop it.
6880 		 *
6881 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6882 		 * byte packets (keepalives are 1-byte), but we'll drop them
6883 		 * also.
6884 		 */
6885 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6886 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6887 		return (B_FALSE);
6888 	}
6889 
6890 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6891 		/* might as well pull it all up - it might be ESP. */
6892 		if (!pullupmsg(mp, -1)) {
6893 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6894 			    DROPPER(ipss, ipds_esp_nomem),
6895 			    &ipss->ipsec_dropper);
6896 			return (B_FALSE);
6897 		}
6898 
6899 		ipha = (ipha_t *)mp->b_rptr;
6900 	}
6901 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6902 	if (*spi == 0) {
6903 		/* UDP packet - remove 0-spi. */
6904 		shift = sizeof (uint32_t);
6905 	} else {
6906 		/* ESP-in-UDP packet - reduce to ESP. */
6907 		ipha->ipha_protocol = IPPROTO_ESP;
6908 		shift = sizeof (udpha_t);
6909 	}
6910 
6911 	/* Fix IP header */
6912 	ipha->ipha_length = htons(plen - shift);
6913 	ipha->ipha_hdr_checksum = 0;
6914 
6915 	orptr = mp->b_rptr;
6916 	mp->b_rptr += shift;
6917 
6918 	udpha = (udpha_t *)(orptr + iph_len);
6919 	if (*spi == 0) {
6920 		ASSERT((uint8_t *)ipha == orptr);
6921 		udpha->uha_length = htons(plen - shift - iph_len);
6922 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
6923 		esp_ports = 0;
6924 	} else {
6925 		esp_ports = *((uint32_t *)udpha);
6926 		ASSERT(esp_ports != 0);
6927 	}
6928 	ovbcopy(orptr, orptr + shift, iph_len);
6929 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
6930 		ipha = (ipha_t *)(orptr + shift);
6931 
6932 		free_ire = (ire == NULL);
6933 		if (free_ire) {
6934 			/* Re-acquire ire. */
6935 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
6936 			    ipss->ipsec_netstack->netstack_ip);
6937 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
6938 				if (ire != NULL)
6939 					ire_refrele(ire);
6940 				/*
6941 				 * Do a regular freemsg(), as this is an IP
6942 				 * error (no local route) not an IPsec one.
6943 				 */
6944 				freemsg(mp);
6945 			}
6946 		}
6947 
6948 		ip_proto_input(q, mp, ipha, ire, recv_ill, esp_ports);
6949 		if (free_ire)
6950 			ire_refrele(ire);
6951 	}
6952 
6953 	return (esp_ports == 0);
6954 }
6955 
6956 /*
6957  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6958  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6959  * Caller is responsible for dropping references to the conn, and freeing
6960  * first_mp.
6961  *
6962  * IPQoS Notes
6963  * Before sending it to the client, invoke IPPF processing. Policy processing
6964  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6965  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6966  * ip_wput_local, ip_policy is false.
6967  */
6968 static void
6969 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6970     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6971     boolean_t ip_policy)
6972 {
6973 	boolean_t	mctl_present = (first_mp != NULL);
6974 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6975 	uint32_t	ill_index;
6976 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6977 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6978 
6979 	ASSERT(ill != NULL);
6980 
6981 	if (mctl_present)
6982 		first_mp->b_cont = mp;
6983 	else
6984 		first_mp = mp;
6985 
6986 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6987 	    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
6988 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
6989 		freemsg(first_mp);
6990 		return;
6991 	}
6992 
6993 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6994 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6995 		    NULL, mctl_present);
6996 		/* Freed by ipsec_check_inbound_policy(). */
6997 		if (first_mp == NULL) {
6998 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
6999 			return;
7000 		}
7001 	}
7002 	if (mctl_present)
7003 		freeb(first_mp);
7004 
7005 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7006 	if (connp->conn_udp->udp_nat_t_endpoint) {
7007 		if (mctl_present) {
7008 			/* mctl_present *shouldn't* happen. */
7009 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7010 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7011 			    &ipss->ipsec_dropper);
7012 			return;
7013 		}
7014 
7015 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7016 			return;
7017 	}
7018 
7019 	/* Handle options. */
7020 	if (connp->conn_recvif)
7021 		in_flags = IPF_RECVIF;
7022 	/*
7023 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7024 	 * passed to ip_add_info is based on IP version of connp.
7025 	 */
7026 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7027 		if (connp->conn_af_isv6) {
7028 			/*
7029 			 * V6 only needs index
7030 			 */
7031 			in_flags |= IPF_RECVIF;
7032 		} else {
7033 			/*
7034 			 * V4 needs index + matching address.
7035 			 */
7036 			in_flags |= IPF_RECVADDR;
7037 		}
7038 	}
7039 
7040 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7041 		in_flags |= IPF_RECVSLLA;
7042 
7043 	/*
7044 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7045 	 * freed if the packet is dropped. The caller will do so.
7046 	 */
7047 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7048 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7049 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7050 		if (mp == NULL) {
7051 			return;
7052 		}
7053 	}
7054 	if ((in_flags != 0) &&
7055 	    (mp->b_datap->db_type != M_CTL)) {
7056 		/*
7057 		 * The actual data will be contained in b_cont
7058 		 * upon successful return of the following call
7059 		 * else original mblk is returned
7060 		 */
7061 		ASSERT(recv_ill != NULL);
7062 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7063 		    ipst);
7064 	}
7065 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7066 	/* Send it upstream */
7067 	(connp->conn_recv)(connp, mp, NULL);
7068 }
7069 
7070 /*
7071  * Fanout for UDP packets.
7072  * The caller puts <fport, lport> in the ports parameter.
7073  *
7074  * If SO_REUSEADDR is set all multicast and broadcast packets
7075  * will be delivered to all streams bound to the same port.
7076  *
7077  * Zones notes:
7078  * Multicast and broadcast packets will be distributed to streams in all zones.
7079  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7080  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7081  * packets. To maintain this behavior with multiple zones, the conns are grouped
7082  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7083  * each zone. If unset, all the following conns in the same zone are skipped.
7084  */
7085 static void
7086 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7087     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7088     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7089 {
7090 	uint32_t	dstport, srcport;
7091 	ipaddr_t	dst;
7092 	mblk_t		*first_mp;
7093 	boolean_t	secure;
7094 	in6_addr_t	v6src;
7095 	conn_t		*connp;
7096 	connf_t		*connfp;
7097 	conn_t		*first_connp;
7098 	conn_t		*next_connp;
7099 	mblk_t		*mp1, *first_mp1;
7100 	ipaddr_t	src;
7101 	zoneid_t	last_zoneid;
7102 	boolean_t	reuseaddr;
7103 	boolean_t	shared_addr;
7104 	boolean_t	unlabeled;
7105 	ip_stack_t	*ipst;
7106 
7107 	ASSERT(recv_ill != NULL);
7108 	ipst = recv_ill->ill_ipst;
7109 
7110 	first_mp = mp;
7111 	if (mctl_present) {
7112 		mp = first_mp->b_cont;
7113 		first_mp->b_cont = NULL;
7114 		secure = ipsec_in_is_secure(first_mp);
7115 		ASSERT(mp != NULL);
7116 	} else {
7117 		first_mp = NULL;
7118 		secure = B_FALSE;
7119 	}
7120 
7121 	/* Extract ports in net byte order */
7122 	dstport = htons(ntohl(ports) & 0xFFFF);
7123 	srcport = htons(ntohl(ports) >> 16);
7124 	dst = ipha->ipha_dst;
7125 	src = ipha->ipha_src;
7126 
7127 	unlabeled = B_FALSE;
7128 	if (is_system_labeled())
7129 		/* Cred cannot be null on IPv4 */
7130 		unlabeled = (crgetlabel(DB_CRED(mp))->tsl_flags &
7131 		    TSLF_UNLABELED) != 0;
7132 	shared_addr = (zoneid == ALL_ZONES);
7133 	if (shared_addr) {
7134 		/*
7135 		 * No need to handle exclusive-stack zones since ALL_ZONES
7136 		 * only applies to the shared stack.
7137 		 */
7138 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7139 		/*
7140 		 * If no shared MLP is found, tsol_mlp_findzone returns
7141 		 * ALL_ZONES.  In that case, we assume it's SLP, and
7142 		 * search for the zone based on the packet label.
7143 		 *
7144 		 * If there is such a zone, we prefer to find a
7145 		 * connection in it.  Otherwise, we look for a
7146 		 * MAC-exempt connection in any zone whose label
7147 		 * dominates the default label on the packet.
7148 		 */
7149 		if (zoneid == ALL_ZONES)
7150 			zoneid = tsol_packet_to_zoneid(mp);
7151 		else
7152 			unlabeled = B_FALSE;
7153 	}
7154 
7155 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7156 	mutex_enter(&connfp->connf_lock);
7157 	connp = connfp->connf_head;
7158 	if (!broadcast && !CLASSD(dst)) {
7159 		/*
7160 		 * Not broadcast or multicast. Send to the one (first)
7161 		 * client we find. No need to check conn_wantpacket()
7162 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7163 		 * IPv4 unicast packets.
7164 		 */
7165 		while ((connp != NULL) &&
7166 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7167 		    (!IPCL_ZONE_MATCH(connp, zoneid) &&
7168 		    !(unlabeled && connp->conn_mac_exempt)))) {
7169 			/*
7170 			 * We keep searching since the conn did not match,
7171 			 * or its zone did not match and it is not either
7172 			 * an allzones conn or a mac exempt conn (if the
7173 			 * sender is unlabeled.)
7174 			 */
7175 			connp = connp->conn_next;
7176 		}
7177 
7178 		if (connp == NULL ||
7179 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7180 			goto notfound;
7181 
7182 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7183 
7184 		if (is_system_labeled() &&
7185 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7186 		    connp))
7187 			goto notfound;
7188 
7189 		CONN_INC_REF(connp);
7190 		mutex_exit(&connfp->connf_lock);
7191 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7192 		    flags, recv_ill, ip_policy);
7193 		IP_STAT(ipst, ip_udp_fannorm);
7194 		CONN_DEC_REF(connp);
7195 		return;
7196 	}
7197 
7198 	/*
7199 	 * Broadcast and multicast case
7200 	 *
7201 	 * Need to check conn_wantpacket().
7202 	 * If SO_REUSEADDR has been set on the first we send the
7203 	 * packet to all clients that have joined the group and
7204 	 * match the port.
7205 	 */
7206 
7207 	while (connp != NULL) {
7208 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7209 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7210 		    (!is_system_labeled() ||
7211 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7212 		    connp)))
7213 			break;
7214 		connp = connp->conn_next;
7215 	}
7216 
7217 	if (connp == NULL ||
7218 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7219 		goto notfound;
7220 
7221 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7222 
7223 	first_connp = connp;
7224 	/*
7225 	 * When SO_REUSEADDR is not set, send the packet only to the first
7226 	 * matching connection in its zone by keeping track of the zoneid.
7227 	 */
7228 	reuseaddr = first_connp->conn_reuseaddr;
7229 	last_zoneid = first_connp->conn_zoneid;
7230 
7231 	CONN_INC_REF(connp);
7232 	connp = connp->conn_next;
7233 	for (;;) {
7234 		while (connp != NULL) {
7235 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7236 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7237 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7238 			    (!is_system_labeled() ||
7239 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7240 			    shared_addr, connp)))
7241 				break;
7242 			connp = connp->conn_next;
7243 		}
7244 		/*
7245 		 * Just copy the data part alone. The mctl part is
7246 		 * needed just for verifying policy and it is never
7247 		 * sent up.
7248 		 */
7249 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7250 		    ((mp1 = copymsg(mp)) == NULL))) {
7251 			/*
7252 			 * No more interested clients or memory
7253 			 * allocation failed
7254 			 */
7255 			connp = first_connp;
7256 			break;
7257 		}
7258 		if (connp->conn_zoneid != last_zoneid) {
7259 			/*
7260 			 * Update the zoneid so that the packet isn't sent to
7261 			 * any more conns in the same zone unless SO_REUSEADDR
7262 			 * is set.
7263 			 */
7264 			reuseaddr = connp->conn_reuseaddr;
7265 			last_zoneid = connp->conn_zoneid;
7266 		}
7267 		if (first_mp != NULL) {
7268 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7269 			    ipsec_info_type == IPSEC_IN);
7270 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7271 			    ipst->ips_netstack);
7272 			if (first_mp1 == NULL) {
7273 				freemsg(mp1);
7274 				connp = first_connp;
7275 				break;
7276 			}
7277 		} else {
7278 			first_mp1 = NULL;
7279 		}
7280 		CONN_INC_REF(connp);
7281 		mutex_exit(&connfp->connf_lock);
7282 		/*
7283 		 * IPQoS notes: We don't send the packet for policy
7284 		 * processing here, will do it for the last one (below).
7285 		 * i.e. we do it per-packet now, but if we do policy
7286 		 * processing per-conn, then we would need to do it
7287 		 * here too.
7288 		 */
7289 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7290 		    ipha, flags, recv_ill, B_FALSE);
7291 		mutex_enter(&connfp->connf_lock);
7292 		/* Follow the next pointer before releasing the conn. */
7293 		next_connp = connp->conn_next;
7294 		IP_STAT(ipst, ip_udp_fanmb);
7295 		CONN_DEC_REF(connp);
7296 		connp = next_connp;
7297 	}
7298 
7299 	/* Last one.  Send it upstream. */
7300 	mutex_exit(&connfp->connf_lock);
7301 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7302 	    recv_ill, ip_policy);
7303 	IP_STAT(ipst, ip_udp_fanmb);
7304 	CONN_DEC_REF(connp);
7305 	return;
7306 
7307 notfound:
7308 
7309 	mutex_exit(&connfp->connf_lock);
7310 	IP_STAT(ipst, ip_udp_fanothers);
7311 	/*
7312 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7313 	 * have already been matched above, since they live in the IPv4
7314 	 * fanout tables. This implies we only need to
7315 	 * check for IPv6 in6addr_any endpoints here.
7316 	 * Thus we compare using ipv6_all_zeros instead of the destination
7317 	 * address, except for the multicast group membership lookup which
7318 	 * uses the IPv4 destination.
7319 	 */
7320 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7321 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7322 	mutex_enter(&connfp->connf_lock);
7323 	connp = connfp->connf_head;
7324 	if (!broadcast && !CLASSD(dst)) {
7325 		while (connp != NULL) {
7326 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7327 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7328 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7329 			    !connp->conn_ipv6_v6only)
7330 				break;
7331 			connp = connp->conn_next;
7332 		}
7333 
7334 		if (connp != NULL && is_system_labeled() &&
7335 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7336 		    connp))
7337 			connp = NULL;
7338 
7339 		if (connp == NULL ||
7340 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7341 			/*
7342 			 * No one bound to this port.  Is
7343 			 * there a client that wants all
7344 			 * unclaimed datagrams?
7345 			 */
7346 			mutex_exit(&connfp->connf_lock);
7347 
7348 			if (mctl_present)
7349 				first_mp->b_cont = mp;
7350 			else
7351 				first_mp = mp;
7352 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7353 			    connf_head != NULL) {
7354 				ip_fanout_proto(q, first_mp, ill, ipha,
7355 				    flags | IP_FF_RAWIP, mctl_present,
7356 				    ip_policy, recv_ill, zoneid);
7357 			} else {
7358 				if (ip_fanout_send_icmp(q, first_mp, flags,
7359 				    ICMP_DEST_UNREACHABLE,
7360 				    ICMP_PORT_UNREACHABLE,
7361 				    mctl_present, zoneid, ipst)) {
7362 					BUMP_MIB(ill->ill_ip_mib,
7363 					    udpIfStatsNoPorts);
7364 				}
7365 			}
7366 			return;
7367 		}
7368 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7369 
7370 		CONN_INC_REF(connp);
7371 		mutex_exit(&connfp->connf_lock);
7372 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7373 		    flags, recv_ill, ip_policy);
7374 		CONN_DEC_REF(connp);
7375 		return;
7376 	}
7377 	/*
7378 	 * IPv4 multicast packet being delivered to an AF_INET6
7379 	 * in6addr_any endpoint.
7380 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7381 	 * and not conn_wantpacket_v6() since any multicast membership is
7382 	 * for an IPv4-mapped multicast address.
7383 	 * The packet is sent to all clients in all zones that have joined the
7384 	 * group and match the port.
7385 	 */
7386 	while (connp != NULL) {
7387 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7388 		    srcport, v6src) &&
7389 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7390 		    (!is_system_labeled() ||
7391 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7392 		    connp)))
7393 			break;
7394 		connp = connp->conn_next;
7395 	}
7396 
7397 	if (connp == NULL ||
7398 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7399 		/*
7400 		 * No one bound to this port.  Is
7401 		 * there a client that wants all
7402 		 * unclaimed datagrams?
7403 		 */
7404 		mutex_exit(&connfp->connf_lock);
7405 
7406 		if (mctl_present)
7407 			first_mp->b_cont = mp;
7408 		else
7409 			first_mp = mp;
7410 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7411 		    NULL) {
7412 			ip_fanout_proto(q, first_mp, ill, ipha,
7413 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7414 			    recv_ill, zoneid);
7415 		} else {
7416 			/*
7417 			 * We used to attempt to send an icmp error here, but
7418 			 * since this is known to be a multicast packet
7419 			 * and we don't send icmp errors in response to
7420 			 * multicast, just drop the packet and give up sooner.
7421 			 */
7422 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7423 			freemsg(first_mp);
7424 		}
7425 		return;
7426 	}
7427 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7428 
7429 	first_connp = connp;
7430 
7431 	CONN_INC_REF(connp);
7432 	connp = connp->conn_next;
7433 	for (;;) {
7434 		while (connp != NULL) {
7435 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7436 			    ipv6_all_zeros, srcport, v6src) &&
7437 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7438 			    (!is_system_labeled() ||
7439 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7440 			    shared_addr, connp)))
7441 				break;
7442 			connp = connp->conn_next;
7443 		}
7444 		/*
7445 		 * Just copy the data part alone. The mctl part is
7446 		 * needed just for verifying policy and it is never
7447 		 * sent up.
7448 		 */
7449 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7450 		    ((mp1 = copymsg(mp)) == NULL))) {
7451 			/*
7452 			 * No more intested clients or memory
7453 			 * allocation failed
7454 			 */
7455 			connp = first_connp;
7456 			break;
7457 		}
7458 		if (first_mp != NULL) {
7459 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7460 			    ipsec_info_type == IPSEC_IN);
7461 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7462 			    ipst->ips_netstack);
7463 			if (first_mp1 == NULL) {
7464 				freemsg(mp1);
7465 				connp = first_connp;
7466 				break;
7467 			}
7468 		} else {
7469 			first_mp1 = NULL;
7470 		}
7471 		CONN_INC_REF(connp);
7472 		mutex_exit(&connfp->connf_lock);
7473 		/*
7474 		 * IPQoS notes: We don't send the packet for policy
7475 		 * processing here, will do it for the last one (below).
7476 		 * i.e. we do it per-packet now, but if we do policy
7477 		 * processing per-conn, then we would need to do it
7478 		 * here too.
7479 		 */
7480 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7481 		    ipha, flags, recv_ill, B_FALSE);
7482 		mutex_enter(&connfp->connf_lock);
7483 		/* Follow the next pointer before releasing the conn. */
7484 		next_connp = connp->conn_next;
7485 		CONN_DEC_REF(connp);
7486 		connp = next_connp;
7487 	}
7488 
7489 	/* Last one.  Send it upstream. */
7490 	mutex_exit(&connfp->connf_lock);
7491 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7492 	    recv_ill, ip_policy);
7493 	CONN_DEC_REF(connp);
7494 }
7495 
7496 /*
7497  * Complete the ip_wput header so that it
7498  * is possible to generate ICMP
7499  * errors.
7500  */
7501 int
7502 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7503 {
7504 	ire_t *ire;
7505 
7506 	if (ipha->ipha_src == INADDR_ANY) {
7507 		ire = ire_lookup_local(zoneid, ipst);
7508 		if (ire == NULL) {
7509 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7510 			return (1);
7511 		}
7512 		ipha->ipha_src = ire->ire_addr;
7513 		ire_refrele(ire);
7514 	}
7515 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7516 	ipha->ipha_hdr_checksum = 0;
7517 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7518 	return (0);
7519 }
7520 
7521 /*
7522  * Nobody should be sending
7523  * packets up this stream
7524  */
7525 static void
7526 ip_lrput(queue_t *q, mblk_t *mp)
7527 {
7528 	mblk_t *mp1;
7529 
7530 	switch (mp->b_datap->db_type) {
7531 	case M_FLUSH:
7532 		/* Turn around */
7533 		if (*mp->b_rptr & FLUSHW) {
7534 			*mp->b_rptr &= ~FLUSHR;
7535 			qreply(q, mp);
7536 			return;
7537 		}
7538 		break;
7539 	}
7540 	/* Could receive messages that passed through ar_rput */
7541 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7542 		mp1->b_prev = mp1->b_next = NULL;
7543 	freemsg(mp);
7544 }
7545 
7546 /* Nobody should be sending packets down this stream */
7547 /* ARGSUSED */
7548 void
7549 ip_lwput(queue_t *q, mblk_t *mp)
7550 {
7551 	freemsg(mp);
7552 }
7553 
7554 /*
7555  * Move the first hop in any source route to ipha_dst and remove that part of
7556  * the source route.  Called by other protocols.  Errors in option formatting
7557  * are ignored - will be handled by ip_wput_options Return the final
7558  * destination (either ipha_dst or the last entry in a source route.)
7559  */
7560 ipaddr_t
7561 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7562 {
7563 	ipoptp_t	opts;
7564 	uchar_t		*opt;
7565 	uint8_t		optval;
7566 	uint8_t		optlen;
7567 	ipaddr_t	dst;
7568 	int		i;
7569 	ire_t		*ire;
7570 	ip_stack_t	*ipst = ns->netstack_ip;
7571 
7572 	ip2dbg(("ip_massage_options\n"));
7573 	dst = ipha->ipha_dst;
7574 	for (optval = ipoptp_first(&opts, ipha);
7575 	    optval != IPOPT_EOL;
7576 	    optval = ipoptp_next(&opts)) {
7577 		opt = opts.ipoptp_cur;
7578 		switch (optval) {
7579 			uint8_t off;
7580 		case IPOPT_SSRR:
7581 		case IPOPT_LSRR:
7582 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7583 				ip1dbg(("ip_massage_options: bad src route\n"));
7584 				break;
7585 			}
7586 			optlen = opts.ipoptp_len;
7587 			off = opt[IPOPT_OFFSET];
7588 			off--;
7589 		redo_srr:
7590 			if (optlen < IP_ADDR_LEN ||
7591 			    off > optlen - IP_ADDR_LEN) {
7592 				/* End of source route */
7593 				ip1dbg(("ip_massage_options: end of SR\n"));
7594 				break;
7595 			}
7596 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7597 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7598 			    ntohl(dst)));
7599 			/*
7600 			 * Check if our address is present more than
7601 			 * once as consecutive hops in source route.
7602 			 * XXX verify per-interface ip_forwarding
7603 			 * for source route?
7604 			 */
7605 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7606 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7607 			if (ire != NULL) {
7608 				ire_refrele(ire);
7609 				off += IP_ADDR_LEN;
7610 				goto redo_srr;
7611 			}
7612 			if (dst == htonl(INADDR_LOOPBACK)) {
7613 				ip1dbg(("ip_massage_options: loopback addr in "
7614 				    "source route!\n"));
7615 				break;
7616 			}
7617 			/*
7618 			 * Update ipha_dst to be the first hop and remove the
7619 			 * first hop from the source route (by overwriting
7620 			 * part of the option with NOP options).
7621 			 */
7622 			ipha->ipha_dst = dst;
7623 			/* Put the last entry in dst */
7624 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7625 			    3;
7626 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7627 
7628 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7629 			    ntohl(dst)));
7630 			/* Move down and overwrite */
7631 			opt[IP_ADDR_LEN] = opt[0];
7632 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7633 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7634 			for (i = 0; i < IP_ADDR_LEN; i++)
7635 				opt[i] = IPOPT_NOP;
7636 			break;
7637 		}
7638 	}
7639 	return (dst);
7640 }
7641 
7642 /*
7643  * Return the network mask
7644  * associated with the specified address.
7645  */
7646 ipaddr_t
7647 ip_net_mask(ipaddr_t addr)
7648 {
7649 	uchar_t	*up = (uchar_t *)&addr;
7650 	ipaddr_t mask = 0;
7651 	uchar_t	*maskp = (uchar_t *)&mask;
7652 
7653 #if defined(__i386) || defined(__amd64)
7654 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7655 #endif
7656 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7657 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7658 #endif
7659 	if (CLASSD(addr)) {
7660 		maskp[0] = 0xF0;
7661 		return (mask);
7662 	}
7663 
7664 	/* We assume Class E default netmask to be 32 */
7665 	if (CLASSE(addr))
7666 		return (0xffffffffU);
7667 
7668 	if (addr == 0)
7669 		return (0);
7670 	maskp[0] = 0xFF;
7671 	if ((up[0] & 0x80) == 0)
7672 		return (mask);
7673 
7674 	maskp[1] = 0xFF;
7675 	if ((up[0] & 0xC0) == 0x80)
7676 		return (mask);
7677 
7678 	maskp[2] = 0xFF;
7679 	if ((up[0] & 0xE0) == 0xC0)
7680 		return (mask);
7681 
7682 	/* Otherwise return no mask */
7683 	return ((ipaddr_t)0);
7684 }
7685 
7686 /*
7687  * Helper ill lookup function used by IPsec.
7688  */
7689 ill_t *
7690 ip_grab_ill(mblk_t *first_mp, int ifindex, boolean_t isv6, ip_stack_t *ipst)
7691 {
7692 	ill_t *ret_ill;
7693 
7694 	ASSERT(ifindex != 0);
7695 
7696 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7697 	    ipst);
7698 	if (ret_ill == NULL) {
7699 		if (isv6) {
7700 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
7701 			ip1dbg(("ip_grab_ill (IPv6): bad ifindex %d.\n",
7702 			    ifindex));
7703 		} else {
7704 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
7705 			ip1dbg(("ip_grab_ill (IPv4): bad ifindex %d.\n",
7706 			    ifindex));
7707 		}
7708 		freemsg(first_mp);
7709 		return (NULL);
7710 	}
7711 	return (ret_ill);
7712 }
7713 
7714 /*
7715  * IPv4 -
7716  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7717  * out a packet to a destination address for which we do not have specific
7718  * (or sufficient) routing information.
7719  *
7720  * NOTE : These are the scopes of some of the variables that point at IRE,
7721  *	  which needs to be followed while making any future modifications
7722  *	  to avoid memory leaks.
7723  *
7724  *	- ire and sire are the entries looked up initially by
7725  *	  ire_ftable_lookup.
7726  *	- ipif_ire is used to hold the interface ire associated with
7727  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7728  *	  it before branching out to error paths.
7729  *	- save_ire is initialized before ire_create, so that ire returned
7730  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7731  *	  before breaking out of the switch.
7732  *
7733  *	Thus on failures, we have to REFRELE only ire and sire, if they
7734  *	are not NULL.
7735  */
7736 void
7737 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7738     zoneid_t zoneid, ip_stack_t *ipst)
7739 {
7740 	areq_t	*areq;
7741 	ipaddr_t gw = 0;
7742 	ire_t	*ire = NULL;
7743 	mblk_t	*res_mp;
7744 	ipaddr_t *addrp;
7745 	ipaddr_t nexthop_addr;
7746 	ipif_t  *src_ipif = NULL;
7747 	ill_t	*dst_ill = NULL;
7748 	ipha_t  *ipha;
7749 	ire_t	*sire = NULL;
7750 	mblk_t	*first_mp;
7751 	ire_t	*save_ire;
7752 	ushort_t ire_marks = 0;
7753 	boolean_t mctl_present;
7754 	ipsec_out_t *io;
7755 	mblk_t	*saved_mp;
7756 	ire_t	*first_sire = NULL;
7757 	mblk_t	*copy_mp = NULL;
7758 	mblk_t	*xmit_mp = NULL;
7759 	ipaddr_t save_dst;
7760 	uint32_t multirt_flags =
7761 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7762 	boolean_t multirt_is_resolvable;
7763 	boolean_t multirt_resolve_next;
7764 	boolean_t unspec_src;
7765 	boolean_t ip_nexthop = B_FALSE;
7766 	tsol_ire_gw_secattr_t *attrp = NULL;
7767 	tsol_gcgrp_t *gcgrp = NULL;
7768 	tsol_gcgrp_addr_t ga;
7769 
7770 	if (ip_debug > 2) {
7771 		/* ip1dbg */
7772 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7773 	}
7774 
7775 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7776 	if (mctl_present) {
7777 		io = (ipsec_out_t *)first_mp->b_rptr;
7778 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7779 		ASSERT(zoneid == io->ipsec_out_zoneid);
7780 		ASSERT(zoneid != ALL_ZONES);
7781 	}
7782 
7783 	ipha = (ipha_t *)mp->b_rptr;
7784 
7785 	/* All multicast lookups come through ip_newroute_ipif() */
7786 	if (CLASSD(dst)) {
7787 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7788 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7789 		freemsg(first_mp);
7790 		return;
7791 	}
7792 
7793 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7794 		ip_nexthop = B_TRUE;
7795 		nexthop_addr = io->ipsec_out_nexthop_addr;
7796 	}
7797 	/*
7798 	 * If this IRE is created for forwarding or it is not for
7799 	 * traffic for congestion controlled protocols, mark it as temporary.
7800 	 */
7801 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7802 		ire_marks |= IRE_MARK_TEMPORARY;
7803 
7804 	/*
7805 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7806 	 * chain until it gets the most specific information available.
7807 	 * For example, we know that there is no IRE_CACHE for this dest,
7808 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7809 	 * ire_ftable_lookup will look up the gateway, etc.
7810 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7811 	 * to the destination, of equal netmask length in the forward table,
7812 	 * will be recursively explored. If no information is available
7813 	 * for the final gateway of that route, we force the returned ire
7814 	 * to be equal to sire using MATCH_IRE_PARENT.
7815 	 * At least, in this case we have a starting point (in the buckets)
7816 	 * to look for other routes to the destination in the forward table.
7817 	 * This is actually used only for multirouting, where a list
7818 	 * of routes has to be processed in sequence.
7819 	 *
7820 	 * In the process of coming up with the most specific information,
7821 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7822 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7823 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7824 	 * Two caveats when handling incomplete ire's in ip_newroute:
7825 	 * - we should be careful when accessing its ire_nce (specifically
7826 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7827 	 * - not all legacy code path callers are prepared to handle
7828 	 *   incomplete ire's, so we should not create/add incomplete
7829 	 *   ire_cache entries here. (See discussion about temporary solution
7830 	 *   further below).
7831 	 *
7832 	 * In order to minimize packet dropping, and to preserve existing
7833 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7834 	 * gateway, and instead use the IF_RESOLVER ire to send out
7835 	 * another request to ARP (this is achieved by passing the
7836 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7837 	 * arp response comes back in ip_wput_nondata, we will create
7838 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7839 	 *
7840 	 * Note that this is a temporary solution; the correct solution is
7841 	 * to create an incomplete  per-dst ire_cache entry, and send the
7842 	 * packet out when the gw's nce is resolved. In order to achieve this,
7843 	 * all packet processing must have been completed prior to calling
7844 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7845 	 * to be modified to accomodate this solution.
7846 	 */
7847 	if (ip_nexthop) {
7848 		/*
7849 		 * The first time we come here, we look for an IRE_INTERFACE
7850 		 * entry for the specified nexthop, set the dst to be the
7851 		 * nexthop address and create an IRE_CACHE entry for the
7852 		 * nexthop. The next time around, we are able to find an
7853 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7854 		 * nexthop address and create an IRE_CACHE entry for the
7855 		 * destination address via the specified nexthop.
7856 		 */
7857 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7858 		    MBLK_GETLABEL(mp), ipst);
7859 		if (ire != NULL) {
7860 			gw = nexthop_addr;
7861 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7862 		} else {
7863 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7864 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7865 			    MBLK_GETLABEL(mp),
7866 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7867 			    ipst);
7868 			if (ire != NULL) {
7869 				dst = nexthop_addr;
7870 			}
7871 		}
7872 	} else {
7873 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7874 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7875 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7876 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7877 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7878 		    ipst);
7879 	}
7880 
7881 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7882 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7883 
7884 	/*
7885 	 * This loop is run only once in most cases.
7886 	 * We loop to resolve further routes only when the destination
7887 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7888 	 */
7889 	do {
7890 		/* Clear the previous iteration's values */
7891 		if (src_ipif != NULL) {
7892 			ipif_refrele(src_ipif);
7893 			src_ipif = NULL;
7894 		}
7895 		if (dst_ill != NULL) {
7896 			ill_refrele(dst_ill);
7897 			dst_ill = NULL;
7898 		}
7899 
7900 		multirt_resolve_next = B_FALSE;
7901 		/*
7902 		 * We check if packets have to be multirouted.
7903 		 * In this case, given the current <ire, sire> couple,
7904 		 * we look for the next suitable <ire, sire>.
7905 		 * This check is done in ire_multirt_lookup(),
7906 		 * which applies various criteria to find the next route
7907 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7908 		 * unchanged if it detects it has not been tried yet.
7909 		 */
7910 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7911 			ip3dbg(("ip_newroute: starting next_resolution "
7912 			    "with first_mp %p, tag %d\n",
7913 			    (void *)first_mp,
7914 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7915 
7916 			ASSERT(sire != NULL);
7917 			multirt_is_resolvable =
7918 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7919 			    MBLK_GETLABEL(mp), ipst);
7920 
7921 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7922 			    "ire %p, sire %p\n",
7923 			    multirt_is_resolvable,
7924 			    (void *)ire, (void *)sire));
7925 
7926 			if (!multirt_is_resolvable) {
7927 				/*
7928 				 * No more multirt route to resolve; give up
7929 				 * (all routes resolved or no more
7930 				 * resolvable routes).
7931 				 */
7932 				if (ire != NULL) {
7933 					ire_refrele(ire);
7934 					ire = NULL;
7935 				}
7936 			} else {
7937 				ASSERT(sire != NULL);
7938 				ASSERT(ire != NULL);
7939 				/*
7940 				 * We simply use first_sire as a flag that
7941 				 * indicates if a resolvable multirt route
7942 				 * has already been found.
7943 				 * If it is not the case, we may have to send
7944 				 * an ICMP error to report that the
7945 				 * destination is unreachable.
7946 				 * We do not IRE_REFHOLD first_sire.
7947 				 */
7948 				if (first_sire == NULL) {
7949 					first_sire = sire;
7950 				}
7951 			}
7952 		}
7953 		if (ire == NULL) {
7954 			if (ip_debug > 3) {
7955 				/* ip2dbg */
7956 				pr_addr_dbg("ip_newroute: "
7957 				    "can't resolve %s\n", AF_INET, &dst);
7958 			}
7959 			ip3dbg(("ip_newroute: "
7960 			    "ire %p, sire %p, first_sire %p\n",
7961 			    (void *)ire, (void *)sire, (void *)first_sire));
7962 
7963 			if (sire != NULL) {
7964 				ire_refrele(sire);
7965 				sire = NULL;
7966 			}
7967 
7968 			if (first_sire != NULL) {
7969 				/*
7970 				 * At least one multirt route has been found
7971 				 * in the same call to ip_newroute();
7972 				 * there is no need to report an ICMP error.
7973 				 * first_sire was not IRE_REFHOLDed.
7974 				 */
7975 				MULTIRT_DEBUG_UNTAG(first_mp);
7976 				freemsg(first_mp);
7977 				return;
7978 			}
7979 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
7980 			    RTA_DST, ipst);
7981 			goto icmp_err_ret;
7982 		}
7983 
7984 		/*
7985 		 * Verify that the returned IRE does not have either
7986 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
7987 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
7988 		 */
7989 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
7990 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
7991 			goto icmp_err_ret;
7992 		}
7993 		/*
7994 		 * Increment the ire_ob_pkt_count field for ire if it is an
7995 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
7996 		 * increment the same for the parent IRE, sire, if it is some
7997 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
7998 		 */
7999 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8000 			UPDATE_OB_PKT_COUNT(ire);
8001 			ire->ire_last_used_time = lbolt;
8002 		}
8003 
8004 		if (sire != NULL) {
8005 			gw = sire->ire_gateway_addr;
8006 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8007 			    IRE_INTERFACE)) == 0);
8008 			UPDATE_OB_PKT_COUNT(sire);
8009 			sire->ire_last_used_time = lbolt;
8010 		}
8011 		/*
8012 		 * We have a route to reach the destination.  Find the
8013 		 * appropriate ill, then get a source address using
8014 		 * ipif_select_source().
8015 		 *
8016 		 * If we are here trying to create an IRE_CACHE for an offlink
8017 		 * destination and have an IRE_CACHE entry for VNI, then use
8018 		 * ire_stq instead since VNI's queue is a black hole.
8019 		 */
8020 		if ((ire->ire_type == IRE_CACHE) &&
8021 		    IS_VNI(ire->ire_ipif->ipif_ill)) {
8022 			dst_ill = ire->ire_stq->q_ptr;
8023 			ill_refhold(dst_ill);
8024 		} else {
8025 			ill_t *ill = ire->ire_ipif->ipif_ill;
8026 
8027 			if (IS_IPMP(ill)) {
8028 				dst_ill =
8029 				    ipmp_illgrp_hold_next_ill(ill->ill_grp);
8030 			} else {
8031 				dst_ill = ill;
8032 				ill_refhold(dst_ill);
8033 			}
8034 		}
8035 
8036 		if (dst_ill == NULL) {
8037 			if (ip_debug > 2) {
8038 				pr_addr_dbg("ip_newroute: no dst "
8039 				    "ill for dst %s\n", AF_INET, &dst);
8040 			}
8041 			goto icmp_err_ret;
8042 		}
8043 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8044 
8045 		/*
8046 		 * Pick the best source address from dst_ill.
8047 		 *
8048 		 * 1) Try to pick the source address from the destination
8049 		 *    route. Clustering assumes that when we have multiple
8050 		 *    prefixes hosted on an interface, the prefix of the
8051 		 *    source address matches the prefix of the destination
8052 		 *    route. We do this only if the address is not
8053 		 *    DEPRECATED.
8054 		 *
8055 		 * 2) If the conn is in a different zone than the ire, we
8056 		 *    need to pick a source address from the right zone.
8057 		 */
8058 		ASSERT(src_ipif == NULL);
8059 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8060 			/*
8061 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8062 			 * Check that the ipif matching the requested source
8063 			 * address still exists.
8064 			 */
8065 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8066 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8067 		}
8068 
8069 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8070 
8071 		if (src_ipif == NULL &&
8072 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8073 			ire_marks |= IRE_MARK_USESRC_CHECK;
8074 			if (!IS_UNDER_IPMP(ire->ire_ipif->ipif_ill) &&
8075 			    IS_IPMP(ire->ire_ipif->ipif_ill) ||
8076 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8077 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8078 			    ire->ire_zoneid != ALL_ZONES) ||
8079 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8080 				/*
8081 				 * If the destination is reachable via a
8082 				 * given gateway, the selected source address
8083 				 * should be in the same subnet as the gateway.
8084 				 * Otherwise, the destination is not reachable.
8085 				 *
8086 				 * If there are no interfaces on the same subnet
8087 				 * as the destination, ipif_select_source gives
8088 				 * first non-deprecated interface which might be
8089 				 * on a different subnet than the gateway.
8090 				 * This is not desirable. Hence pass the dst_ire
8091 				 * source address to ipif_select_source.
8092 				 * It is sure that the destination is reachable
8093 				 * with the dst_ire source address subnet.
8094 				 * So passing dst_ire source address to
8095 				 * ipif_select_source will make sure that the
8096 				 * selected source will be on the same subnet
8097 				 * as dst_ire source address.
8098 				 */
8099 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8100 
8101 				src_ipif = ipif_select_source(dst_ill, saddr,
8102 				    zoneid);
8103 				if (src_ipif == NULL) {
8104 					if (ip_debug > 2) {
8105 						pr_addr_dbg("ip_newroute: "
8106 						    "no src for dst %s ",
8107 						    AF_INET, &dst);
8108 						printf("on interface %s\n",
8109 						    dst_ill->ill_name);
8110 					}
8111 					goto icmp_err_ret;
8112 				}
8113 			} else {
8114 				src_ipif = ire->ire_ipif;
8115 				ASSERT(src_ipif != NULL);
8116 				/* hold src_ipif for uniformity */
8117 				ipif_refhold(src_ipif);
8118 			}
8119 		}
8120 
8121 		/*
8122 		 * Assign a source address while we have the conn.
8123 		 * We can't have ip_wput_ire pick a source address when the
8124 		 * packet returns from arp since we need to look at
8125 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8126 		 * going through arp.
8127 		 *
8128 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8129 		 *	  it uses ip6i to store this information.
8130 		 */
8131 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8132 			ipha->ipha_src = src_ipif->ipif_src_addr;
8133 
8134 		if (ip_debug > 3) {
8135 			/* ip2dbg */
8136 			pr_addr_dbg("ip_newroute: first hop %s\n",
8137 			    AF_INET, &gw);
8138 		}
8139 		ip2dbg(("\tire type %s (%d)\n",
8140 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8141 
8142 		/*
8143 		 * The TTL of multirouted packets is bounded by the
8144 		 * ip_multirt_ttl ndd variable.
8145 		 */
8146 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8147 			/* Force TTL of multirouted packets */
8148 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8149 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8150 				ip2dbg(("ip_newroute: forcing multirt TTL "
8151 				    "to %d (was %d), dst 0x%08x\n",
8152 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8153 				    ntohl(sire->ire_addr)));
8154 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8155 			}
8156 		}
8157 		/*
8158 		 * At this point in ip_newroute(), ire is either the
8159 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8160 		 * destination or an IRE_INTERFACE type that should be used
8161 		 * to resolve an on-subnet destination or an on-subnet
8162 		 * next-hop gateway.
8163 		 *
8164 		 * In the IRE_CACHE case, we have the following :
8165 		 *
8166 		 * 1) src_ipif - used for getting a source address.
8167 		 *
8168 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8169 		 *    means packets using this IRE_CACHE will go out on
8170 		 *    dst_ill.
8171 		 *
8172 		 * 3) The IRE sire will point to the prefix that is the
8173 		 *    longest  matching route for the destination. These
8174 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8175 		 *
8176 		 *    The newly created IRE_CACHE entry for the off-subnet
8177 		 *    destination is tied to both the prefix route and the
8178 		 *    interface route used to resolve the next-hop gateway
8179 		 *    via the ire_phandle and ire_ihandle fields,
8180 		 *    respectively.
8181 		 *
8182 		 * In the IRE_INTERFACE case, we have the following :
8183 		 *
8184 		 * 1) src_ipif - used for getting a source address.
8185 		 *
8186 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8187 		 *    means packets using the IRE_CACHE that we will build
8188 		 *    here will go out on dst_ill.
8189 		 *
8190 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8191 		 *    to be created will only be tied to the IRE_INTERFACE
8192 		 *    that was derived from the ire_ihandle field.
8193 		 *
8194 		 *    If sire is non-NULL, it means the destination is
8195 		 *    off-link and we will first create the IRE_CACHE for the
8196 		 *    gateway. Next time through ip_newroute, we will create
8197 		 *    the IRE_CACHE for the final destination as described
8198 		 *    above.
8199 		 *
8200 		 * In both cases, after the current resolution has been
8201 		 * completed (or possibly initialised, in the IRE_INTERFACE
8202 		 * case), the loop may be re-entered to attempt the resolution
8203 		 * of another RTF_MULTIRT route.
8204 		 *
8205 		 * When an IRE_CACHE entry for the off-subnet destination is
8206 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8207 		 * for further processing in emission loops.
8208 		 */
8209 		save_ire = ire;
8210 		switch (ire->ire_type) {
8211 		case IRE_CACHE: {
8212 			ire_t	*ipif_ire;
8213 
8214 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8215 			if (gw == 0)
8216 				gw = ire->ire_gateway_addr;
8217 			/*
8218 			 * We need 3 ire's to create a new cache ire for an
8219 			 * off-link destination from the cache ire of the
8220 			 * gateway.
8221 			 *
8222 			 *	1. The prefix ire 'sire' (Note that this does
8223 			 *	   not apply to the conn_nexthop_set case)
8224 			 *	2. The cache ire of the gateway 'ire'
8225 			 *	3. The interface ire 'ipif_ire'
8226 			 *
8227 			 * We have (1) and (2). We lookup (3) below.
8228 			 *
8229 			 * If there is no interface route to the gateway,
8230 			 * it is a race condition, where we found the cache
8231 			 * but the interface route has been deleted.
8232 			 */
8233 			if (ip_nexthop) {
8234 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8235 			} else {
8236 				ipif_ire =
8237 				    ire_ihandle_lookup_offlink(ire, sire);
8238 			}
8239 			if (ipif_ire == NULL) {
8240 				ip1dbg(("ip_newroute: "
8241 				    "ire_ihandle_lookup_offlink failed\n"));
8242 				goto icmp_err_ret;
8243 			}
8244 
8245 			/*
8246 			 * Check cached gateway IRE for any security
8247 			 * attributes; if found, associate the gateway
8248 			 * credentials group to the destination IRE.
8249 			 */
8250 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8251 				mutex_enter(&attrp->igsa_lock);
8252 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8253 					GCGRP_REFHOLD(gcgrp);
8254 				mutex_exit(&attrp->igsa_lock);
8255 			}
8256 
8257 			/*
8258 			 * XXX For the source of the resolver mp,
8259 			 * we are using the same DL_UNITDATA_REQ
8260 			 * (from save_ire->ire_nce->nce_res_mp)
8261 			 * though the save_ire is not pointing at the same ill.
8262 			 * This is incorrect. We need to send it up to the
8263 			 * resolver to get the right res_mp. For ethernets
8264 			 * this may be okay (ill_type == DL_ETHER).
8265 			 */
8266 
8267 			ire = ire_create(
8268 			    (uchar_t *)&dst,		/* dest address */
8269 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8270 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8271 			    (uchar_t *)&gw,		/* gateway address */
8272 			    &save_ire->ire_max_frag,
8273 			    save_ire->ire_nce,		/* src nce */
8274 			    dst_ill->ill_rq,		/* recv-from queue */
8275 			    dst_ill->ill_wq,		/* send-to queue */
8276 			    IRE_CACHE,			/* IRE type */
8277 			    src_ipif,
8278 			    (sire != NULL) ?
8279 			    sire->ire_mask : 0, 	/* Parent mask */
8280 			    (sire != NULL) ?
8281 			    sire->ire_phandle : 0,	/* Parent handle */
8282 			    ipif_ire->ire_ihandle,	/* Interface handle */
8283 			    (sire != NULL) ? (sire->ire_flags &
8284 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8285 			    (sire != NULL) ?
8286 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8287 			    NULL,
8288 			    gcgrp,
8289 			    ipst);
8290 
8291 			if (ire == NULL) {
8292 				if (gcgrp != NULL) {
8293 					GCGRP_REFRELE(gcgrp);
8294 					gcgrp = NULL;
8295 				}
8296 				ire_refrele(ipif_ire);
8297 				ire_refrele(save_ire);
8298 				break;
8299 			}
8300 
8301 			/* reference now held by IRE */
8302 			gcgrp = NULL;
8303 
8304 			ire->ire_marks |= ire_marks;
8305 
8306 			/*
8307 			 * Prevent sire and ipif_ire from getting deleted.
8308 			 * The newly created ire is tied to both of them via
8309 			 * the phandle and ihandle respectively.
8310 			 */
8311 			if (sire != NULL) {
8312 				IRB_REFHOLD(sire->ire_bucket);
8313 				/* Has it been removed already ? */
8314 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8315 					IRB_REFRELE(sire->ire_bucket);
8316 					ire_refrele(ipif_ire);
8317 					ire_refrele(save_ire);
8318 					break;
8319 				}
8320 			}
8321 
8322 			IRB_REFHOLD(ipif_ire->ire_bucket);
8323 			/* Has it been removed already ? */
8324 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8325 				IRB_REFRELE(ipif_ire->ire_bucket);
8326 				if (sire != NULL)
8327 					IRB_REFRELE(sire->ire_bucket);
8328 				ire_refrele(ipif_ire);
8329 				ire_refrele(save_ire);
8330 				break;
8331 			}
8332 
8333 			xmit_mp = first_mp;
8334 			/*
8335 			 * In the case of multirouting, a copy
8336 			 * of the packet is done before its sending.
8337 			 * The copy is used to attempt another
8338 			 * route resolution, in a next loop.
8339 			 */
8340 			if (ire->ire_flags & RTF_MULTIRT) {
8341 				copy_mp = copymsg(first_mp);
8342 				if (copy_mp != NULL) {
8343 					xmit_mp = copy_mp;
8344 					MULTIRT_DEBUG_TAG(first_mp);
8345 				}
8346 			}
8347 
8348 			ire_add_then_send(q, ire, xmit_mp);
8349 			ire_refrele(save_ire);
8350 
8351 			/* Assert that sire is not deleted yet. */
8352 			if (sire != NULL) {
8353 				ASSERT(sire->ire_ptpn != NULL);
8354 				IRB_REFRELE(sire->ire_bucket);
8355 			}
8356 
8357 			/* Assert that ipif_ire is not deleted yet. */
8358 			ASSERT(ipif_ire->ire_ptpn != NULL);
8359 			IRB_REFRELE(ipif_ire->ire_bucket);
8360 			ire_refrele(ipif_ire);
8361 
8362 			/*
8363 			 * If copy_mp is not NULL, multirouting was
8364 			 * requested. We loop to initiate a next
8365 			 * route resolution attempt, starting from sire.
8366 			 */
8367 			if (copy_mp != NULL) {
8368 				/*
8369 				 * Search for the next unresolved
8370 				 * multirt route.
8371 				 */
8372 				copy_mp = NULL;
8373 				ipif_ire = NULL;
8374 				ire = NULL;
8375 				multirt_resolve_next = B_TRUE;
8376 				continue;
8377 			}
8378 			if (sire != NULL)
8379 				ire_refrele(sire);
8380 			ipif_refrele(src_ipif);
8381 			ill_refrele(dst_ill);
8382 			return;
8383 		}
8384 		case IRE_IF_NORESOLVER: {
8385 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8386 			    dst_ill->ill_resolver_mp == NULL) {
8387 				ip1dbg(("ip_newroute: dst_ill %p "
8388 				    "for IRE_IF_NORESOLVER ire %p has "
8389 				    "no ill_resolver_mp\n",
8390 				    (void *)dst_ill, (void *)ire));
8391 				break;
8392 			}
8393 
8394 			/*
8395 			 * TSol note: We are creating the ire cache for the
8396 			 * destination 'dst'. If 'dst' is offlink, going
8397 			 * through the first hop 'gw', the security attributes
8398 			 * of 'dst' must be set to point to the gateway
8399 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8400 			 * is possible that 'dst' is a potential gateway that is
8401 			 * referenced by some route that has some security
8402 			 * attributes. Thus in the former case, we need to do a
8403 			 * gcgrp_lookup of 'gw' while in the latter case we
8404 			 * need to do gcgrp_lookup of 'dst' itself.
8405 			 */
8406 			ga.ga_af = AF_INET;
8407 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8408 			    &ga.ga_addr);
8409 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8410 
8411 			ire = ire_create(
8412 			    (uchar_t *)&dst,		/* dest address */
8413 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8414 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8415 			    (uchar_t *)&gw,		/* gateway address */
8416 			    &save_ire->ire_max_frag,
8417 			    NULL,			/* no src nce */
8418 			    dst_ill->ill_rq,		/* recv-from queue */
8419 			    dst_ill->ill_wq,		/* send-to queue */
8420 			    IRE_CACHE,
8421 			    src_ipif,
8422 			    save_ire->ire_mask,		/* Parent mask */
8423 			    (sire != NULL) ?		/* Parent handle */
8424 			    sire->ire_phandle : 0,
8425 			    save_ire->ire_ihandle,	/* Interface handle */
8426 			    (sire != NULL) ? sire->ire_flags &
8427 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8428 			    &(save_ire->ire_uinfo),
8429 			    NULL,
8430 			    gcgrp,
8431 			    ipst);
8432 
8433 			if (ire == NULL) {
8434 				if (gcgrp != NULL) {
8435 					GCGRP_REFRELE(gcgrp);
8436 					gcgrp = NULL;
8437 				}
8438 				ire_refrele(save_ire);
8439 				break;
8440 			}
8441 
8442 			/* reference now held by IRE */
8443 			gcgrp = NULL;
8444 
8445 			ire->ire_marks |= ire_marks;
8446 
8447 			/* Prevent save_ire from getting deleted */
8448 			IRB_REFHOLD(save_ire->ire_bucket);
8449 			/* Has it been removed already ? */
8450 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8451 				IRB_REFRELE(save_ire->ire_bucket);
8452 				ire_refrele(save_ire);
8453 				break;
8454 			}
8455 
8456 			/*
8457 			 * In the case of multirouting, a copy
8458 			 * of the packet is made before it is sent.
8459 			 * The copy is used in the next
8460 			 * loop to attempt another resolution.
8461 			 */
8462 			xmit_mp = first_mp;
8463 			if ((sire != NULL) &&
8464 			    (sire->ire_flags & RTF_MULTIRT)) {
8465 				copy_mp = copymsg(first_mp);
8466 				if (copy_mp != NULL) {
8467 					xmit_mp = copy_mp;
8468 					MULTIRT_DEBUG_TAG(first_mp);
8469 				}
8470 			}
8471 			ire_add_then_send(q, ire, xmit_mp);
8472 
8473 			/* Assert that it is not deleted yet. */
8474 			ASSERT(save_ire->ire_ptpn != NULL);
8475 			IRB_REFRELE(save_ire->ire_bucket);
8476 			ire_refrele(save_ire);
8477 
8478 			if (copy_mp != NULL) {
8479 				/*
8480 				 * If we found a (no)resolver, we ignore any
8481 				 * trailing top priority IRE_CACHE in further
8482 				 * loops. This ensures that we do not omit any
8483 				 * (no)resolver.
8484 				 * This IRE_CACHE, if any, will be processed
8485 				 * by another thread entering ip_newroute().
8486 				 * IRE_CACHE entries, if any, will be processed
8487 				 * by another thread entering ip_newroute(),
8488 				 * (upon resolver response, for instance).
8489 				 * This aims to force parallel multirt
8490 				 * resolutions as soon as a packet must be sent.
8491 				 * In the best case, after the tx of only one
8492 				 * packet, all reachable routes are resolved.
8493 				 * Otherwise, the resolution of all RTF_MULTIRT
8494 				 * routes would require several emissions.
8495 				 */
8496 				multirt_flags &= ~MULTIRT_CACHEGW;
8497 
8498 				/*
8499 				 * Search for the next unresolved multirt
8500 				 * route.
8501 				 */
8502 				copy_mp = NULL;
8503 				save_ire = NULL;
8504 				ire = NULL;
8505 				multirt_resolve_next = B_TRUE;
8506 				continue;
8507 			}
8508 
8509 			/*
8510 			 * Don't need sire anymore
8511 			 */
8512 			if (sire != NULL)
8513 				ire_refrele(sire);
8514 
8515 			ipif_refrele(src_ipif);
8516 			ill_refrele(dst_ill);
8517 			return;
8518 		}
8519 		case IRE_IF_RESOLVER:
8520 			/*
8521 			 * We can't build an IRE_CACHE yet, but at least we
8522 			 * found a resolver that can help.
8523 			 */
8524 			res_mp = dst_ill->ill_resolver_mp;
8525 			if (!OK_RESOLVER_MP(res_mp))
8526 				break;
8527 
8528 			/*
8529 			 * To be at this point in the code with a non-zero gw
8530 			 * means that dst is reachable through a gateway that
8531 			 * we have never resolved.  By changing dst to the gw
8532 			 * addr we resolve the gateway first.
8533 			 * When ire_add_then_send() tries to put the IP dg
8534 			 * to dst, it will reenter ip_newroute() at which
8535 			 * time we will find the IRE_CACHE for the gw and
8536 			 * create another IRE_CACHE in case IRE_CACHE above.
8537 			 */
8538 			if (gw != INADDR_ANY) {
8539 				/*
8540 				 * The source ipif that was determined above was
8541 				 * relative to the destination address, not the
8542 				 * gateway's. If src_ipif was not taken out of
8543 				 * the IRE_IF_RESOLVER entry, we'll need to call
8544 				 * ipif_select_source() again.
8545 				 */
8546 				if (src_ipif != ire->ire_ipif) {
8547 					ipif_refrele(src_ipif);
8548 					src_ipif = ipif_select_source(dst_ill,
8549 					    gw, zoneid);
8550 					if (src_ipif == NULL) {
8551 						if (ip_debug > 2) {
8552 							pr_addr_dbg(
8553 							    "ip_newroute: no "
8554 							    "src for gw %s ",
8555 							    AF_INET, &gw);
8556 							printf("on "
8557 							    "interface %s\n",
8558 							    dst_ill->ill_name);
8559 						}
8560 						goto icmp_err_ret;
8561 					}
8562 				}
8563 				save_dst = dst;
8564 				dst = gw;
8565 				gw = INADDR_ANY;
8566 			}
8567 
8568 			/*
8569 			 * We obtain a partial IRE_CACHE which we will pass
8570 			 * along with the resolver query.  When the response
8571 			 * comes back it will be there ready for us to add.
8572 			 * The ire_max_frag is atomically set under the
8573 			 * irebucket lock in ire_add_v[46].
8574 			 */
8575 
8576 			ire = ire_create_mp(
8577 			    (uchar_t *)&dst,		/* dest address */
8578 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8579 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8580 			    (uchar_t *)&gw,		/* gateway address */
8581 			    NULL,			/* ire_max_frag */
8582 			    NULL,			/* no src nce */
8583 			    dst_ill->ill_rq,		/* recv-from queue */
8584 			    dst_ill->ill_wq,		/* send-to queue */
8585 			    IRE_CACHE,
8586 			    src_ipif,			/* Interface ipif */
8587 			    save_ire->ire_mask,		/* Parent mask */
8588 			    0,
8589 			    save_ire->ire_ihandle,	/* Interface handle */
8590 			    0,				/* flags if any */
8591 			    &(save_ire->ire_uinfo),
8592 			    NULL,
8593 			    NULL,
8594 			    ipst);
8595 
8596 			if (ire == NULL) {
8597 				ire_refrele(save_ire);
8598 				break;
8599 			}
8600 
8601 			if ((sire != NULL) &&
8602 			    (sire->ire_flags & RTF_MULTIRT)) {
8603 				copy_mp = copymsg(first_mp);
8604 				if (copy_mp != NULL)
8605 					MULTIRT_DEBUG_TAG(copy_mp);
8606 			}
8607 
8608 			ire->ire_marks |= ire_marks;
8609 
8610 			/*
8611 			 * Construct message chain for the resolver
8612 			 * of the form:
8613 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8614 			 * Packet could contain a IPSEC_OUT mp.
8615 			 *
8616 			 * NOTE : ire will be added later when the response
8617 			 * comes back from ARP. If the response does not
8618 			 * come back, ARP frees the packet. For this reason,
8619 			 * we can't REFHOLD the bucket of save_ire to prevent
8620 			 * deletions. We may not be able to REFRELE the bucket
8621 			 * if the response never comes back. Thus, before
8622 			 * adding the ire, ire_add_v4 will make sure that the
8623 			 * interface route does not get deleted. This is the
8624 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8625 			 * where we can always prevent deletions because of
8626 			 * the synchronous nature of adding IRES i.e
8627 			 * ire_add_then_send is called after creating the IRE.
8628 			 */
8629 			ASSERT(ire->ire_mp != NULL);
8630 			ire->ire_mp->b_cont = first_mp;
8631 			/* Have saved_mp handy, for cleanup if canput fails */
8632 			saved_mp = mp;
8633 			mp = copyb(res_mp);
8634 			if (mp == NULL) {
8635 				/* Prepare for cleanup */
8636 				mp = saved_mp; /* pkt */
8637 				ire_delete(ire); /* ire_mp */
8638 				ire = NULL;
8639 				ire_refrele(save_ire);
8640 				if (copy_mp != NULL) {
8641 					MULTIRT_DEBUG_UNTAG(copy_mp);
8642 					freemsg(copy_mp);
8643 					copy_mp = NULL;
8644 				}
8645 				break;
8646 			}
8647 			linkb(mp, ire->ire_mp);
8648 
8649 			/*
8650 			 * Fill in the source and dest addrs for the resolver.
8651 			 * NOTE: this depends on memory layouts imposed by
8652 			 * ill_init().
8653 			 */
8654 			areq = (areq_t *)mp->b_rptr;
8655 			addrp = (ipaddr_t *)((char *)areq +
8656 			    areq->areq_sender_addr_offset);
8657 			*addrp = save_ire->ire_src_addr;
8658 
8659 			ire_refrele(save_ire);
8660 			addrp = (ipaddr_t *)((char *)areq +
8661 			    areq->areq_target_addr_offset);
8662 			*addrp = dst;
8663 			/* Up to the resolver. */
8664 			if (canputnext(dst_ill->ill_rq) &&
8665 			    !(dst_ill->ill_arp_closing)) {
8666 				putnext(dst_ill->ill_rq, mp);
8667 				ire = NULL;
8668 				if (copy_mp != NULL) {
8669 					/*
8670 					 * If we found a resolver, we ignore
8671 					 * any trailing top priority IRE_CACHE
8672 					 * in the further loops. This ensures
8673 					 * that we do not omit any resolver.
8674 					 * IRE_CACHE entries, if any, will be
8675 					 * processed next time we enter
8676 					 * ip_newroute().
8677 					 */
8678 					multirt_flags &= ~MULTIRT_CACHEGW;
8679 					/*
8680 					 * Search for the next unresolved
8681 					 * multirt route.
8682 					 */
8683 					first_mp = copy_mp;
8684 					copy_mp = NULL;
8685 					/* Prepare the next resolution loop. */
8686 					mp = first_mp;
8687 					EXTRACT_PKT_MP(mp, first_mp,
8688 					    mctl_present);
8689 					if (mctl_present)
8690 						io = (ipsec_out_t *)
8691 						    first_mp->b_rptr;
8692 					ipha = (ipha_t *)mp->b_rptr;
8693 
8694 					ASSERT(sire != NULL);
8695 
8696 					dst = save_dst;
8697 					multirt_resolve_next = B_TRUE;
8698 					continue;
8699 				}
8700 
8701 				if (sire != NULL)
8702 					ire_refrele(sire);
8703 
8704 				/*
8705 				 * The response will come back in ip_wput
8706 				 * with db_type IRE_DB_TYPE.
8707 				 */
8708 				ipif_refrele(src_ipif);
8709 				ill_refrele(dst_ill);
8710 				return;
8711 			} else {
8712 				/* Prepare for cleanup */
8713 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8714 				    mp);
8715 				mp->b_cont = NULL;
8716 				freeb(mp); /* areq */
8717 				/*
8718 				 * this is an ire that is not added to the
8719 				 * cache. ire_freemblk will handle the release
8720 				 * of any resources associated with the ire.
8721 				 */
8722 				ire_delete(ire); /* ire_mp */
8723 				mp = saved_mp; /* pkt */
8724 				ire = NULL;
8725 				if (copy_mp != NULL) {
8726 					MULTIRT_DEBUG_UNTAG(copy_mp);
8727 					freemsg(copy_mp);
8728 					copy_mp = NULL;
8729 				}
8730 				break;
8731 			}
8732 		default:
8733 			break;
8734 		}
8735 	} while (multirt_resolve_next);
8736 
8737 	ip1dbg(("ip_newroute: dropped\n"));
8738 	/* Did this packet originate externally? */
8739 	if (mp->b_prev) {
8740 		mp->b_next = NULL;
8741 		mp->b_prev = NULL;
8742 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8743 	} else {
8744 		if (dst_ill != NULL) {
8745 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8746 		} else {
8747 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8748 		}
8749 	}
8750 	ASSERT(copy_mp == NULL);
8751 	MULTIRT_DEBUG_UNTAG(first_mp);
8752 	freemsg(first_mp);
8753 	if (ire != NULL)
8754 		ire_refrele(ire);
8755 	if (sire != NULL)
8756 		ire_refrele(sire);
8757 	if (src_ipif != NULL)
8758 		ipif_refrele(src_ipif);
8759 	if (dst_ill != NULL)
8760 		ill_refrele(dst_ill);
8761 	return;
8762 
8763 icmp_err_ret:
8764 	ip1dbg(("ip_newroute: no route\n"));
8765 	if (src_ipif != NULL)
8766 		ipif_refrele(src_ipif);
8767 	if (dst_ill != NULL)
8768 		ill_refrele(dst_ill);
8769 	if (sire != NULL)
8770 		ire_refrele(sire);
8771 	/* Did this packet originate externally? */
8772 	if (mp->b_prev) {
8773 		mp->b_next = NULL;
8774 		mp->b_prev = NULL;
8775 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8776 		q = WR(q);
8777 	} else {
8778 		/*
8779 		 * There is no outgoing ill, so just increment the
8780 		 * system MIB.
8781 		 */
8782 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8783 		/*
8784 		 * Since ip_wput() isn't close to finished, we fill
8785 		 * in enough of the header for credible error reporting.
8786 		 */
8787 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8788 			/* Failed */
8789 			MULTIRT_DEBUG_UNTAG(first_mp);
8790 			freemsg(first_mp);
8791 			if (ire != NULL)
8792 				ire_refrele(ire);
8793 			return;
8794 		}
8795 	}
8796 
8797 	/*
8798 	 * At this point we will have ire only if RTF_BLACKHOLE
8799 	 * or RTF_REJECT flags are set on the IRE. It will not
8800 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8801 	 */
8802 	if (ire != NULL) {
8803 		if (ire->ire_flags & RTF_BLACKHOLE) {
8804 			ire_refrele(ire);
8805 			MULTIRT_DEBUG_UNTAG(first_mp);
8806 			freemsg(first_mp);
8807 			return;
8808 		}
8809 		ire_refrele(ire);
8810 	}
8811 	if (ip_source_routed(ipha, ipst)) {
8812 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8813 		    zoneid, ipst);
8814 		return;
8815 	}
8816 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8817 }
8818 
8819 ip_opt_info_t zero_info;
8820 
8821 /*
8822  * IPv4 -
8823  * ip_newroute_ipif is called by ip_wput_multicast and
8824  * ip_rput_forward_multicast whenever we need to send
8825  * out a packet to a destination address for which we do not have specific
8826  * routing information. It is used when the packet will be sent out
8827  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
8828  * socket option is set or icmp error message wants to go out on a particular
8829  * interface for a unicast packet.
8830  *
8831  * In most cases, the destination address is resolved thanks to the ipif
8832  * intrinsic resolver. However, there are some cases where the call to
8833  * ip_newroute_ipif must take into account the potential presence of
8834  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8835  * that uses the interface. This is specified through flags,
8836  * which can be a combination of:
8837  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8838  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8839  *   and flags. Additionally, the packet source address has to be set to
8840  *   the specified address. The caller is thus expected to set this flag
8841  *   if the packet has no specific source address yet.
8842  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8843  *   flag, the resulting ire will inherit the flag. All unresolved routes
8844  *   to the destination must be explored in the same call to
8845  *   ip_newroute_ipif().
8846  */
8847 static void
8848 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8849     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
8850 {
8851 	areq_t	*areq;
8852 	ire_t	*ire = NULL;
8853 	mblk_t	*res_mp;
8854 	ipaddr_t *addrp;
8855 	mblk_t *first_mp;
8856 	ire_t	*save_ire = NULL;
8857 	ipif_t	*src_ipif = NULL;
8858 	ushort_t ire_marks = 0;
8859 	ill_t	*dst_ill = NULL;
8860 	ipha_t *ipha;
8861 	mblk_t	*saved_mp;
8862 	ire_t   *fire = NULL;
8863 	mblk_t  *copy_mp = NULL;
8864 	boolean_t multirt_resolve_next;
8865 	boolean_t unspec_src;
8866 	ipaddr_t ipha_dst;
8867 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
8868 
8869 	/*
8870 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
8871 	 * here for uniformity
8872 	 */
8873 	ipif_refhold(ipif);
8874 
8875 	/*
8876 	 * This loop is run only once in most cases.
8877 	 * We loop to resolve further routes only when the destination
8878 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8879 	 */
8880 	do {
8881 		if (dst_ill != NULL) {
8882 			ill_refrele(dst_ill);
8883 			dst_ill = NULL;
8884 		}
8885 		if (src_ipif != NULL) {
8886 			ipif_refrele(src_ipif);
8887 			src_ipif = NULL;
8888 		}
8889 		multirt_resolve_next = B_FALSE;
8890 
8891 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
8892 		    ipif->ipif_ill->ill_name));
8893 
8894 		first_mp = mp;
8895 		if (DB_TYPE(mp) == M_CTL)
8896 			mp = mp->b_cont;
8897 		ipha = (ipha_t *)mp->b_rptr;
8898 
8899 		/*
8900 		 * Save the packet destination address, we may need it after
8901 		 * the packet has been consumed.
8902 		 */
8903 		ipha_dst = ipha->ipha_dst;
8904 
8905 		/*
8906 		 * If the interface is a pt-pt interface we look for an
8907 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
8908 		 * local_address and the pt-pt destination address. Otherwise
8909 		 * we just match the local address.
8910 		 * NOTE: dst could be different than ipha->ipha_dst in case
8911 		 * of sending igmp multicast packets over a point-to-point
8912 		 * connection.
8913 		 * Thus we must be careful enough to check ipha_dst to be a
8914 		 * multicast address, otherwise it will take xmit_if path for
8915 		 * multicast packets resulting into kernel stack overflow by
8916 		 * repeated calls to ip_newroute_ipif from ire_send().
8917 		 */
8918 		if (CLASSD(ipha_dst) &&
8919 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
8920 			goto err_ret;
8921 		}
8922 
8923 		/*
8924 		 * We check if an IRE_OFFSUBNET for the addr that goes through
8925 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
8926 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
8927 		 * propagate its flags to the new ire.
8928 		 */
8929 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
8930 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
8931 			ip2dbg(("ip_newroute_ipif: "
8932 			    "ipif_lookup_multi_ire("
8933 			    "ipif %p, dst %08x) = fire %p\n",
8934 			    (void *)ipif, ntohl(dst), (void *)fire));
8935 		}
8936 
8937 		/*
8938 		 * Note: While we pick a dst_ill we are really only
8939 		 * interested in the ill for load spreading. The source
8940 		 * ipif is determined by source address selection below.
8941 		 */
8942 		if (IS_IPMP(ipif->ipif_ill)) {
8943 			ipmp_illgrp_t *illg = ipif->ipif_ill->ill_grp;
8944 
8945 			if (CLASSD(ipha_dst))
8946 				dst_ill = ipmp_illgrp_hold_cast_ill(illg);
8947 			else
8948 				dst_ill = ipmp_illgrp_hold_next_ill(illg);
8949 		} else {
8950 			dst_ill = ipif->ipif_ill;
8951 			ill_refhold(dst_ill);
8952 		}
8953 
8954 		if (dst_ill == NULL) {
8955 			if (ip_debug > 2) {
8956 				pr_addr_dbg("ip_newroute_ipif: no dst ill "
8957 				    "for dst %s\n", AF_INET, &dst);
8958 			}
8959 			goto err_ret;
8960 		}
8961 
8962 		/*
8963 		 * Pick a source address preferring non-deprecated ones.
8964 		 * Unlike ip_newroute, we don't do any source address
8965 		 * selection here since for multicast it really does not help
8966 		 * in inbound load spreading as in the unicast case.
8967 		 */
8968 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
8969 		    (fire->ire_flags & RTF_SETSRC)) {
8970 			/*
8971 			 * As requested by flags, an IRE_OFFSUBNET was looked up
8972 			 * on that interface. This ire has RTF_SETSRC flag, so
8973 			 * the source address of the packet must be changed.
8974 			 * Check that the ipif matching the requested source
8975 			 * address still exists.
8976 			 */
8977 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
8978 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8979 		}
8980 
8981 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8982 
8983 		if (!IS_UNDER_IPMP(ipif->ipif_ill) &&
8984 		    (IS_IPMP(ipif->ipif_ill) ||
8985 		    (!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
8986 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
8987 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
8988 		    ipif->ipif_zoneid != ALL_ZONES)) &&
8989 		    (src_ipif == NULL) &&
8990 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8991 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
8992 			if (src_ipif == NULL) {
8993 				if (ip_debug > 2) {
8994 					/* ip1dbg */
8995 					pr_addr_dbg("ip_newroute_ipif: "
8996 					    "no src for dst %s",
8997 					    AF_INET, &dst);
8998 				}
8999 				ip1dbg((" on interface %s\n",
9000 				    dst_ill->ill_name));
9001 				goto err_ret;
9002 			}
9003 			ipif_refrele(ipif);
9004 			ipif = src_ipif;
9005 			ipif_refhold(ipif);
9006 		}
9007 		if (src_ipif == NULL) {
9008 			src_ipif = ipif;
9009 			ipif_refhold(src_ipif);
9010 		}
9011 
9012 		/*
9013 		 * Assign a source address while we have the conn.
9014 		 * We can't have ip_wput_ire pick a source address when the
9015 		 * packet returns from arp since conn_unspec_src might be set
9016 		 * and we lose the conn when going through arp.
9017 		 */
9018 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9019 			ipha->ipha_src = src_ipif->ipif_src_addr;
9020 
9021 		/*
9022 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9023 		 * that the outgoing interface does not have an interface ire.
9024 		 */
9025 		if (CLASSD(ipha_dst) && (connp == NULL ||
9026 		    connp->conn_outgoing_ill == NULL) &&
9027 		    infop->ip_opt_ill_index == 0) {
9028 			/* ipif_to_ire returns an held ire */
9029 			ire = ipif_to_ire(ipif);
9030 			if (ire == NULL)
9031 				goto err_ret;
9032 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9033 				goto err_ret;
9034 			save_ire = ire;
9035 
9036 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9037 			    "flags %04x\n",
9038 			    (void *)ire, (void *)ipif, flags));
9039 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9040 			    (fire->ire_flags & RTF_MULTIRT)) {
9041 				/*
9042 				 * As requested by flags, an IRE_OFFSUBNET was
9043 				 * looked up on that interface. This ire has
9044 				 * RTF_MULTIRT flag, so the resolution loop will
9045 				 * be re-entered to resolve additional routes on
9046 				 * other interfaces. For that purpose, a copy of
9047 				 * the packet is performed at this point.
9048 				 */
9049 				fire->ire_last_used_time = lbolt;
9050 				copy_mp = copymsg(first_mp);
9051 				if (copy_mp) {
9052 					MULTIRT_DEBUG_TAG(copy_mp);
9053 				}
9054 			}
9055 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9056 			    (fire->ire_flags & RTF_SETSRC)) {
9057 				/*
9058 				 * As requested by flags, an IRE_OFFSUBET was
9059 				 * looked up on that interface. This ire has
9060 				 * RTF_SETSRC flag, so the source address of the
9061 				 * packet must be changed.
9062 				 */
9063 				ipha->ipha_src = fire->ire_src_addr;
9064 			}
9065 		} else {
9066 			/*
9067 			 * The only ways we can come here are:
9068 			 * 1) IP_BOUND_IF socket option is set
9069 			 * 2) SO_DONTROUTE socket option is set
9070 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9071 			 * In all cases, the new ire will not be added
9072 			 * into cache table.
9073 			 */
9074 			ASSERT(connp == NULL || connp->conn_dontroute ||
9075 			    connp->conn_outgoing_ill != NULL ||
9076 			    infop->ip_opt_ill_index != 0);
9077 			ire_marks |= IRE_MARK_NOADD;
9078 		}
9079 
9080 		switch (ipif->ipif_net_type) {
9081 		case IRE_IF_NORESOLVER: {
9082 			/* We have what we need to build an IRE_CACHE. */
9083 
9084 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9085 			    (dst_ill->ill_resolver_mp == NULL)) {
9086 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9087 				    "for IRE_IF_NORESOLVER ire %p has "
9088 				    "no ill_resolver_mp\n",
9089 				    (void *)dst_ill, (void *)ire));
9090 				break;
9091 			}
9092 
9093 			/*
9094 			 * The new ire inherits the IRE_OFFSUBNET flags
9095 			 * and source address, if this was requested.
9096 			 */
9097 			ire = ire_create(
9098 			    (uchar_t *)&dst,		/* dest address */
9099 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9100 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9101 			    NULL,			/* gateway address */
9102 			    &ipif->ipif_mtu,
9103 			    NULL,			/* no src nce */
9104 			    dst_ill->ill_rq,		/* recv-from queue */
9105 			    dst_ill->ill_wq,		/* send-to queue */
9106 			    IRE_CACHE,
9107 			    src_ipif,
9108 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9109 			    (fire != NULL) ?		/* Parent handle */
9110 			    fire->ire_phandle : 0,
9111 			    (save_ire != NULL) ?	/* Interface handle */
9112 			    save_ire->ire_ihandle : 0,
9113 			    (fire != NULL) ?
9114 			    (fire->ire_flags &
9115 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9116 			    (save_ire == NULL ? &ire_uinfo_null :
9117 			    &save_ire->ire_uinfo),
9118 			    NULL,
9119 			    NULL,
9120 			    ipst);
9121 
9122 			if (ire == NULL) {
9123 				if (save_ire != NULL)
9124 					ire_refrele(save_ire);
9125 				break;
9126 			}
9127 
9128 			ire->ire_marks |= ire_marks;
9129 
9130 			/*
9131 			 * If IRE_MARK_NOADD is set then we need to convert
9132 			 * the max_fragp to a useable value now. This is
9133 			 * normally done in ire_add_v[46]. We also need to
9134 			 * associate the ire with an nce (normally would be
9135 			 * done in ip_wput_nondata()).
9136 			 *
9137 			 * Note that IRE_MARK_NOADD packets created here
9138 			 * do not have a non-null ire_mp pointer. The null
9139 			 * value of ire_bucket indicates that they were
9140 			 * never added.
9141 			 */
9142 			if (ire->ire_marks & IRE_MARK_NOADD) {
9143 				uint_t  max_frag;
9144 
9145 				max_frag = *ire->ire_max_fragp;
9146 				ire->ire_max_fragp = NULL;
9147 				ire->ire_max_frag = max_frag;
9148 
9149 				if ((ire->ire_nce = ndp_lookup_v4(
9150 				    ire_to_ill(ire),
9151 				    (ire->ire_gateway_addr != INADDR_ANY ?
9152 				    &ire->ire_gateway_addr : &ire->ire_addr),
9153 				    B_FALSE)) == NULL) {
9154 					if (save_ire != NULL)
9155 						ire_refrele(save_ire);
9156 					break;
9157 				}
9158 				ASSERT(ire->ire_nce->nce_state ==
9159 				    ND_REACHABLE);
9160 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9161 			}
9162 
9163 			/* Prevent save_ire from getting deleted */
9164 			if (save_ire != NULL) {
9165 				IRB_REFHOLD(save_ire->ire_bucket);
9166 				/* Has it been removed already ? */
9167 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9168 					IRB_REFRELE(save_ire->ire_bucket);
9169 					ire_refrele(save_ire);
9170 					break;
9171 				}
9172 			}
9173 
9174 			ire_add_then_send(q, ire, first_mp);
9175 
9176 			/* Assert that save_ire is not deleted yet. */
9177 			if (save_ire != NULL) {
9178 				ASSERT(save_ire->ire_ptpn != NULL);
9179 				IRB_REFRELE(save_ire->ire_bucket);
9180 				ire_refrele(save_ire);
9181 				save_ire = NULL;
9182 			}
9183 			if (fire != NULL) {
9184 				ire_refrele(fire);
9185 				fire = NULL;
9186 			}
9187 
9188 			/*
9189 			 * the resolution loop is re-entered if this
9190 			 * was requested through flags and if we
9191 			 * actually are in a multirouting case.
9192 			 */
9193 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9194 				boolean_t need_resolve =
9195 				    ire_multirt_need_resolve(ipha_dst,
9196 				    MBLK_GETLABEL(copy_mp), ipst);
9197 				if (!need_resolve) {
9198 					MULTIRT_DEBUG_UNTAG(copy_mp);
9199 					freemsg(copy_mp);
9200 					copy_mp = NULL;
9201 				} else {
9202 					/*
9203 					 * ipif_lookup_group() calls
9204 					 * ire_lookup_multi() that uses
9205 					 * ire_ftable_lookup() to find
9206 					 * an IRE_INTERFACE for the group.
9207 					 * In the multirt case,
9208 					 * ire_lookup_multi() then invokes
9209 					 * ire_multirt_lookup() to find
9210 					 * the next resolvable ire.
9211 					 * As a result, we obtain an new
9212 					 * interface, derived from the
9213 					 * next ire.
9214 					 */
9215 					ipif_refrele(ipif);
9216 					ipif = ipif_lookup_group(ipha_dst,
9217 					    zoneid, ipst);
9218 					ip2dbg(("ip_newroute_ipif: "
9219 					    "multirt dst %08x, ipif %p\n",
9220 					    htonl(dst), (void *)ipif));
9221 					if (ipif != NULL) {
9222 						mp = copy_mp;
9223 						copy_mp = NULL;
9224 						multirt_resolve_next = B_TRUE;
9225 						continue;
9226 					} else {
9227 						freemsg(copy_mp);
9228 					}
9229 				}
9230 			}
9231 			if (ipif != NULL)
9232 				ipif_refrele(ipif);
9233 			ill_refrele(dst_ill);
9234 			ipif_refrele(src_ipif);
9235 			return;
9236 		}
9237 		case IRE_IF_RESOLVER:
9238 			/*
9239 			 * We can't build an IRE_CACHE yet, but at least
9240 			 * we found a resolver that can help.
9241 			 */
9242 			res_mp = dst_ill->ill_resolver_mp;
9243 			if (!OK_RESOLVER_MP(res_mp))
9244 				break;
9245 
9246 			/*
9247 			 * We obtain a partial IRE_CACHE which we will pass
9248 			 * along with the resolver query.  When the response
9249 			 * comes back it will be there ready for us to add.
9250 			 * The new ire inherits the IRE_OFFSUBNET flags
9251 			 * and source address, if this was requested.
9252 			 * The ire_max_frag is atomically set under the
9253 			 * irebucket lock in ire_add_v[46]. Only in the
9254 			 * case of IRE_MARK_NOADD, we set it here itself.
9255 			 */
9256 			ire = ire_create_mp(
9257 			    (uchar_t *)&dst,		/* dest address */
9258 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9259 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9260 			    NULL,			/* gateway address */
9261 			    (ire_marks & IRE_MARK_NOADD) ?
9262 			    ipif->ipif_mtu : 0,		/* max_frag */
9263 			    NULL,			/* no src nce */
9264 			    dst_ill->ill_rq,		/* recv-from queue */
9265 			    dst_ill->ill_wq,		/* send-to queue */
9266 			    IRE_CACHE,
9267 			    src_ipif,
9268 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9269 			    (fire != NULL) ?		/* Parent handle */
9270 			    fire->ire_phandle : 0,
9271 			    (save_ire != NULL) ?	/* Interface handle */
9272 			    save_ire->ire_ihandle : 0,
9273 			    (fire != NULL) ?		/* flags if any */
9274 			    (fire->ire_flags &
9275 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9276 			    (save_ire == NULL ? &ire_uinfo_null :
9277 			    &save_ire->ire_uinfo),
9278 			    NULL,
9279 			    NULL,
9280 			    ipst);
9281 
9282 			if (save_ire != NULL) {
9283 				ire_refrele(save_ire);
9284 				save_ire = NULL;
9285 			}
9286 			if (ire == NULL)
9287 				break;
9288 
9289 			ire->ire_marks |= ire_marks;
9290 			/*
9291 			 * Construct message chain for the resolver of the
9292 			 * form:
9293 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9294 			 *
9295 			 * NOTE : ire will be added later when the response
9296 			 * comes back from ARP. If the response does not
9297 			 * come back, ARP frees the packet. For this reason,
9298 			 * we can't REFHOLD the bucket of save_ire to prevent
9299 			 * deletions. We may not be able to REFRELE the
9300 			 * bucket if the response never comes back.
9301 			 * Thus, before adding the ire, ire_add_v4 will make
9302 			 * sure that the interface route does not get deleted.
9303 			 * This is the only case unlike ip_newroute_v6,
9304 			 * ip_newroute_ipif_v6 where we can always prevent
9305 			 * deletions because ire_add_then_send is called after
9306 			 * creating the IRE.
9307 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9308 			 * does not add this IRE into the IRE CACHE.
9309 			 */
9310 			ASSERT(ire->ire_mp != NULL);
9311 			ire->ire_mp->b_cont = first_mp;
9312 			/* Have saved_mp handy, for cleanup if canput fails */
9313 			saved_mp = mp;
9314 			mp = copyb(res_mp);
9315 			if (mp == NULL) {
9316 				/* Prepare for cleanup */
9317 				mp = saved_mp; /* pkt */
9318 				ire_delete(ire); /* ire_mp */
9319 				ire = NULL;
9320 				if (copy_mp != NULL) {
9321 					MULTIRT_DEBUG_UNTAG(copy_mp);
9322 					freemsg(copy_mp);
9323 					copy_mp = NULL;
9324 				}
9325 				break;
9326 			}
9327 			linkb(mp, ire->ire_mp);
9328 
9329 			/*
9330 			 * Fill in the source and dest addrs for the resolver.
9331 			 * NOTE: this depends on memory layouts imposed by
9332 			 * ill_init().  There are corner cases above where we
9333 			 * might've created the IRE with an INADDR_ANY source
9334 			 * address (e.g., if the zeroth ipif on an underlying
9335 			 * ill in an IPMP group is 0.0.0.0, but another ipif
9336 			 * on the ill has a usable test address).  If so, tell
9337 			 * ARP to use ipha_src as its sender address.
9338 			 */
9339 			areq = (areq_t *)mp->b_rptr;
9340 			addrp = (ipaddr_t *)((char *)areq +
9341 			    areq->areq_sender_addr_offset);
9342 			if (ire->ire_src_addr != INADDR_ANY)
9343 				*addrp = ire->ire_src_addr;
9344 			else
9345 				*addrp = ipha->ipha_src;
9346 			addrp = (ipaddr_t *)((char *)areq +
9347 			    areq->areq_target_addr_offset);
9348 			*addrp = dst;
9349 			/* Up to the resolver. */
9350 			if (canputnext(dst_ill->ill_rq) &&
9351 			    !(dst_ill->ill_arp_closing)) {
9352 				putnext(dst_ill->ill_rq, mp);
9353 				/*
9354 				 * The response will come back in ip_wput
9355 				 * with db_type IRE_DB_TYPE.
9356 				 */
9357 			} else {
9358 				mp->b_cont = NULL;
9359 				freeb(mp); /* areq */
9360 				ire_delete(ire); /* ire_mp */
9361 				saved_mp->b_next = NULL;
9362 				saved_mp->b_prev = NULL;
9363 				freemsg(first_mp); /* pkt */
9364 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9365 			}
9366 
9367 			if (fire != NULL) {
9368 				ire_refrele(fire);
9369 				fire = NULL;
9370 			}
9371 
9372 
9373 			/*
9374 			 * The resolution loop is re-entered if this was
9375 			 * requested through flags and we actually are
9376 			 * in a multirouting case.
9377 			 */
9378 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9379 				boolean_t need_resolve =
9380 				    ire_multirt_need_resolve(ipha_dst,
9381 				    MBLK_GETLABEL(copy_mp), ipst);
9382 				if (!need_resolve) {
9383 					MULTIRT_DEBUG_UNTAG(copy_mp);
9384 					freemsg(copy_mp);
9385 					copy_mp = NULL;
9386 				} else {
9387 					/*
9388 					 * ipif_lookup_group() calls
9389 					 * ire_lookup_multi() that uses
9390 					 * ire_ftable_lookup() to find
9391 					 * an IRE_INTERFACE for the group.
9392 					 * In the multirt case,
9393 					 * ire_lookup_multi() then invokes
9394 					 * ire_multirt_lookup() to find
9395 					 * the next resolvable ire.
9396 					 * As a result, we obtain an new
9397 					 * interface, derived from the
9398 					 * next ire.
9399 					 */
9400 					ipif_refrele(ipif);
9401 					ipif = ipif_lookup_group(ipha_dst,
9402 					    zoneid, ipst);
9403 					if (ipif != NULL) {
9404 						mp = copy_mp;
9405 						copy_mp = NULL;
9406 						multirt_resolve_next = B_TRUE;
9407 						continue;
9408 					} else {
9409 						freemsg(copy_mp);
9410 					}
9411 				}
9412 			}
9413 			if (ipif != NULL)
9414 				ipif_refrele(ipif);
9415 			ill_refrele(dst_ill);
9416 			ipif_refrele(src_ipif);
9417 			return;
9418 		default:
9419 			break;
9420 		}
9421 	} while (multirt_resolve_next);
9422 
9423 err_ret:
9424 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9425 	if (fire != NULL)
9426 		ire_refrele(fire);
9427 	ipif_refrele(ipif);
9428 	/* Did this packet originate externally? */
9429 	if (dst_ill != NULL)
9430 		ill_refrele(dst_ill);
9431 	if (src_ipif != NULL)
9432 		ipif_refrele(src_ipif);
9433 	if (mp->b_prev || mp->b_next) {
9434 		mp->b_next = NULL;
9435 		mp->b_prev = NULL;
9436 	} else {
9437 		/*
9438 		 * Since ip_wput() isn't close to finished, we fill
9439 		 * in enough of the header for credible error reporting.
9440 		 */
9441 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9442 			/* Failed */
9443 			freemsg(first_mp);
9444 			if (ire != NULL)
9445 				ire_refrele(ire);
9446 			return;
9447 		}
9448 	}
9449 	/*
9450 	 * At this point we will have ire only if RTF_BLACKHOLE
9451 	 * or RTF_REJECT flags are set on the IRE. It will not
9452 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9453 	 */
9454 	if (ire != NULL) {
9455 		if (ire->ire_flags & RTF_BLACKHOLE) {
9456 			ire_refrele(ire);
9457 			freemsg(first_mp);
9458 			return;
9459 		}
9460 		ire_refrele(ire);
9461 	}
9462 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9463 }
9464 
9465 /* Name/Value Table Lookup Routine */
9466 char *
9467 ip_nv_lookup(nv_t *nv, int value)
9468 {
9469 	if (!nv)
9470 		return (NULL);
9471 	for (; nv->nv_name; nv++) {
9472 		if (nv->nv_value == value)
9473 			return (nv->nv_name);
9474 	}
9475 	return ("unknown");
9476 }
9477 
9478 /*
9479  * This is a module open, i.e. this is a control stream for access
9480  * to a DLPI device.  We allocate an ill_t as the instance data in
9481  * this case.
9482  */
9483 int
9484 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9485 {
9486 	ill_t	*ill;
9487 	int	err;
9488 	zoneid_t zoneid;
9489 	netstack_t *ns;
9490 	ip_stack_t *ipst;
9491 
9492 	/*
9493 	 * Prevent unprivileged processes from pushing IP so that
9494 	 * they can't send raw IP.
9495 	 */
9496 	if (secpolicy_net_rawaccess(credp) != 0)
9497 		return (EPERM);
9498 
9499 	ns = netstack_find_by_cred(credp);
9500 	ASSERT(ns != NULL);
9501 	ipst = ns->netstack_ip;
9502 	ASSERT(ipst != NULL);
9503 
9504 	/*
9505 	 * For exclusive stacks we set the zoneid to zero
9506 	 * to make IP operate as if in the global zone.
9507 	 */
9508 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9509 		zoneid = GLOBAL_ZONEID;
9510 	else
9511 		zoneid = crgetzoneid(credp);
9512 
9513 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9514 	q->q_ptr = WR(q)->q_ptr = ill;
9515 	ill->ill_ipst = ipst;
9516 	ill->ill_zoneid = zoneid;
9517 
9518 	/*
9519 	 * ill_init initializes the ill fields and then sends down
9520 	 * down a DL_INFO_REQ after calling qprocson.
9521 	 */
9522 	err = ill_init(q, ill);
9523 	if (err != 0) {
9524 		mi_free(ill);
9525 		netstack_rele(ipst->ips_netstack);
9526 		q->q_ptr = NULL;
9527 		WR(q)->q_ptr = NULL;
9528 		return (err);
9529 	}
9530 
9531 	/* ill_init initializes the ipsq marking this thread as writer */
9532 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
9533 	/* Wait for the DL_INFO_ACK */
9534 	mutex_enter(&ill->ill_lock);
9535 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9536 		/*
9537 		 * Return value of 0 indicates a pending signal.
9538 		 */
9539 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9540 		if (err == 0) {
9541 			mutex_exit(&ill->ill_lock);
9542 			(void) ip_close(q, 0);
9543 			return (EINTR);
9544 		}
9545 	}
9546 	mutex_exit(&ill->ill_lock);
9547 
9548 	/*
9549 	 * ip_rput_other could have set an error  in ill_error on
9550 	 * receipt of M_ERROR.
9551 	 */
9552 
9553 	err = ill->ill_error;
9554 	if (err != 0) {
9555 		(void) ip_close(q, 0);
9556 		return (err);
9557 	}
9558 
9559 	ill->ill_credp = credp;
9560 	crhold(credp);
9561 
9562 	mutex_enter(&ipst->ips_ip_mi_lock);
9563 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9564 	    credp);
9565 	mutex_exit(&ipst->ips_ip_mi_lock);
9566 	if (err) {
9567 		(void) ip_close(q, 0);
9568 		return (err);
9569 	}
9570 	return (0);
9571 }
9572 
9573 /* For /dev/ip aka AF_INET open */
9574 int
9575 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9576 {
9577 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9578 }
9579 
9580 /* For /dev/ip6 aka AF_INET6 open */
9581 int
9582 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9583 {
9584 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9585 }
9586 
9587 /* IP open routine. */
9588 int
9589 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9590     boolean_t isv6)
9591 {
9592 	conn_t 		*connp;
9593 	major_t		maj;
9594 	zoneid_t	zoneid;
9595 	netstack_t	*ns;
9596 	ip_stack_t	*ipst;
9597 
9598 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9599 
9600 	/* Allow reopen. */
9601 	if (q->q_ptr != NULL)
9602 		return (0);
9603 
9604 	if (sflag & MODOPEN) {
9605 		/* This is a module open */
9606 		return (ip_modopen(q, devp, flag, sflag, credp));
9607 	}
9608 
9609 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
9610 		/*
9611 		 * Non streams based socket looking for a stream
9612 		 * to access IP
9613 		 */
9614 		return (ip_helper_stream_setup(q, devp, flag, sflag,
9615 		    credp, isv6));
9616 	}
9617 
9618 	ns = netstack_find_by_cred(credp);
9619 	ASSERT(ns != NULL);
9620 	ipst = ns->netstack_ip;
9621 	ASSERT(ipst != NULL);
9622 
9623 	/*
9624 	 * For exclusive stacks we set the zoneid to zero
9625 	 * to make IP operate as if in the global zone.
9626 	 */
9627 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9628 		zoneid = GLOBAL_ZONEID;
9629 	else
9630 		zoneid = crgetzoneid(credp);
9631 
9632 	/*
9633 	 * We are opening as a device. This is an IP client stream, and we
9634 	 * allocate an conn_t as the instance data.
9635 	 */
9636 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9637 
9638 	/*
9639 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9640 	 * done by netstack_find_by_cred()
9641 	 */
9642 	netstack_rele(ipst->ips_netstack);
9643 
9644 	connp->conn_zoneid = zoneid;
9645 	connp->conn_sqp = NULL;
9646 	connp->conn_initial_sqp = NULL;
9647 	connp->conn_final_sqp = NULL;
9648 
9649 	connp->conn_upq = q;
9650 	q->q_ptr = WR(q)->q_ptr = connp;
9651 
9652 	if (flag & SO_SOCKSTR)
9653 		connp->conn_flags |= IPCL_SOCKET;
9654 
9655 	/* Minor tells us which /dev entry was opened */
9656 	if (isv6) {
9657 		connp->conn_flags |= IPCL_ISV6;
9658 		connp->conn_af_isv6 = B_TRUE;
9659 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9660 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9661 	} else {
9662 		connp->conn_af_isv6 = B_FALSE;
9663 		connp->conn_pkt_isv6 = B_FALSE;
9664 	}
9665 
9666 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9667 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9668 		connp->conn_minor_arena = ip_minor_arena_la;
9669 	} else {
9670 		/*
9671 		 * Either minor numbers in the large arena were exhausted
9672 		 * or a non socket application is doing the open.
9673 		 * Try to allocate from the small arena.
9674 		 */
9675 		if ((connp->conn_dev =
9676 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9677 			/* CONN_DEC_REF takes care of netstack_rele() */
9678 			q->q_ptr = WR(q)->q_ptr = NULL;
9679 			CONN_DEC_REF(connp);
9680 			return (EBUSY);
9681 		}
9682 		connp->conn_minor_arena = ip_minor_arena_sa;
9683 	}
9684 
9685 	maj = getemajor(*devp);
9686 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9687 
9688 	/*
9689 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9690 	 */
9691 	connp->conn_cred = credp;
9692 
9693 	/*
9694 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9695 	 */
9696 	connp->conn_recv = ip_conn_input;
9697 
9698 	crhold(connp->conn_cred);
9699 
9700 	/*
9701 	 * If the caller has the process-wide flag set, then default to MAC
9702 	 * exempt mode.  This allows read-down to unlabeled hosts.
9703 	 */
9704 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9705 		connp->conn_mac_exempt = B_TRUE;
9706 
9707 	connp->conn_rq = q;
9708 	connp->conn_wq = WR(q);
9709 
9710 	/* Non-zero default values */
9711 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9712 
9713 	/*
9714 	 * Make the conn globally visible to walkers
9715 	 */
9716 	ASSERT(connp->conn_ref == 1);
9717 	mutex_enter(&connp->conn_lock);
9718 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9719 	mutex_exit(&connp->conn_lock);
9720 
9721 	qprocson(q);
9722 
9723 	return (0);
9724 }
9725 
9726 /*
9727  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9728  * Note that there is no race since either ip_output function works - it
9729  * is just an optimization to enter the best ip_output routine directly.
9730  */
9731 void
9732 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9733     ip_stack_t *ipst)
9734 {
9735 	if (isv6)  {
9736 		if (bump_mib) {
9737 			BUMP_MIB(&ipst->ips_ip6_mib,
9738 			    ipIfStatsOutSwitchIPVersion);
9739 		}
9740 		connp->conn_send = ip_output_v6;
9741 		connp->conn_pkt_isv6 = B_TRUE;
9742 	} else {
9743 		if (bump_mib) {
9744 			BUMP_MIB(&ipst->ips_ip_mib,
9745 			    ipIfStatsOutSwitchIPVersion);
9746 		}
9747 		connp->conn_send = ip_output;
9748 		connp->conn_pkt_isv6 = B_FALSE;
9749 	}
9750 
9751 }
9752 
9753 /*
9754  * See if IPsec needs loading because of the options in mp.
9755  */
9756 static boolean_t
9757 ipsec_opt_present(mblk_t *mp)
9758 {
9759 	uint8_t *optcp, *next_optcp, *opt_endcp;
9760 	struct opthdr *opt;
9761 	struct T_opthdr *topt;
9762 	int opthdr_len;
9763 	t_uscalar_t optname, optlevel;
9764 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9765 	ipsec_req_t *ipsr;
9766 
9767 	/*
9768 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9769 	 * return TRUE.
9770 	 */
9771 
9772 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9773 	opt_endcp = optcp + tor->OPT_length;
9774 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9775 		opthdr_len = sizeof (struct T_opthdr);
9776 	} else {		/* O_OPTMGMT_REQ */
9777 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9778 		opthdr_len = sizeof (struct opthdr);
9779 	}
9780 	for (; optcp < opt_endcp; optcp = next_optcp) {
9781 		if (optcp + opthdr_len > opt_endcp)
9782 			return (B_FALSE);	/* Not enough option header. */
9783 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9784 			topt = (struct T_opthdr *)optcp;
9785 			optlevel = topt->level;
9786 			optname = topt->name;
9787 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9788 		} else {
9789 			opt = (struct opthdr *)optcp;
9790 			optlevel = opt->level;
9791 			optname = opt->name;
9792 			next_optcp = optcp + opthdr_len +
9793 			    _TPI_ALIGN_OPT(opt->len);
9794 		}
9795 		if ((next_optcp < optcp) || /* wraparound pointer space */
9796 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9797 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9798 			return (B_FALSE); /* bad option buffer */
9799 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9800 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9801 			/*
9802 			 * Check to see if it's an all-bypass or all-zeroes
9803 			 * IPsec request.  Don't bother loading IPsec if
9804 			 * the socket doesn't want to use it.  (A good example
9805 			 * is a bypass request.)
9806 			 *
9807 			 * Basically, if any of the non-NEVER bits are set,
9808 			 * load IPsec.
9809 			 */
9810 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9811 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9812 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9813 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9814 			    != 0)
9815 				return (B_TRUE);
9816 		}
9817 	}
9818 	return (B_FALSE);
9819 }
9820 
9821 /*
9822  * If conn is is waiting for ipsec to finish loading, kick it.
9823  */
9824 /* ARGSUSED */
9825 static void
9826 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9827 {
9828 	t_scalar_t	optreq_prim;
9829 	mblk_t		*mp;
9830 	cred_t		*cr;
9831 	int		err = 0;
9832 
9833 	/*
9834 	 * This function is called, after ipsec loading is complete.
9835 	 * Since IP checks exclusively and atomically (i.e it prevents
9836 	 * ipsec load from completing until ip_optcom_req completes)
9837 	 * whether ipsec load is complete, there cannot be a race with IP
9838 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9839 	 */
9840 	mutex_enter(&connp->conn_lock);
9841 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9842 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9843 		mp = connp->conn_ipsec_opt_mp;
9844 		connp->conn_ipsec_opt_mp = NULL;
9845 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9846 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
9847 		mutex_exit(&connp->conn_lock);
9848 
9849 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9850 
9851 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9852 		if (optreq_prim == T_OPTMGMT_REQ) {
9853 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9854 			    &ip_opt_obj, B_FALSE);
9855 		} else {
9856 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9857 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9858 			    &ip_opt_obj, B_FALSE);
9859 		}
9860 		if (err != EINPROGRESS)
9861 			CONN_OPER_PENDING_DONE(connp);
9862 		return;
9863 	}
9864 	mutex_exit(&connp->conn_lock);
9865 }
9866 
9867 /*
9868  * Called from the ipsec_loader thread, outside any perimeter, to tell
9869  * ip qenable any of the queues waiting for the ipsec loader to
9870  * complete.
9871  */
9872 void
9873 ip_ipsec_load_complete(ipsec_stack_t *ipss)
9874 {
9875 	netstack_t *ns = ipss->ipsec_netstack;
9876 
9877 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
9878 }
9879 
9880 /*
9881  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
9882  * determines the grp on which it has to become exclusive, queues the mp
9883  * and IPSQ draining restarts the optmgmt
9884  */
9885 static boolean_t
9886 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
9887 {
9888 	conn_t *connp = Q_TO_CONN(q);
9889 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
9890 
9891 	/*
9892 	 * Take IPsec requests and treat them special.
9893 	 */
9894 	if (ipsec_opt_present(mp)) {
9895 		/* First check if IPsec is loaded. */
9896 		mutex_enter(&ipss->ipsec_loader_lock);
9897 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
9898 			mutex_exit(&ipss->ipsec_loader_lock);
9899 			return (B_FALSE);
9900 		}
9901 		mutex_enter(&connp->conn_lock);
9902 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
9903 
9904 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
9905 		connp->conn_ipsec_opt_mp = mp;
9906 		mutex_exit(&connp->conn_lock);
9907 		mutex_exit(&ipss->ipsec_loader_lock);
9908 
9909 		ipsec_loader_loadnow(ipss);
9910 		return (B_TRUE);
9911 	}
9912 	return (B_FALSE);
9913 }
9914 
9915 /*
9916  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
9917  * all of them are copied to the conn_t. If the req is "zero", the policy is
9918  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
9919  * fields.
9920  * We keep only the latest setting of the policy and thus policy setting
9921  * is not incremental/cumulative.
9922  *
9923  * Requests to set policies with multiple alternative actions will
9924  * go through a different API.
9925  */
9926 int
9927 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
9928 {
9929 	uint_t ah_req = 0;
9930 	uint_t esp_req = 0;
9931 	uint_t se_req = 0;
9932 	ipsec_selkey_t sel;
9933 	ipsec_act_t *actp = NULL;
9934 	uint_t nact;
9935 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
9936 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
9937 	ipsec_policy_root_t *pr;
9938 	ipsec_policy_head_t *ph;
9939 	int fam;
9940 	boolean_t is_pol_reset;
9941 	int error = 0;
9942 	netstack_t	*ns = connp->conn_netstack;
9943 	ip_stack_t	*ipst = ns->netstack_ip;
9944 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
9945 
9946 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
9947 
9948 	/*
9949 	 * The IP_SEC_OPT option does not allow variable length parameters,
9950 	 * hence a request cannot be NULL.
9951 	 */
9952 	if (req == NULL)
9953 		return (EINVAL);
9954 
9955 	ah_req = req->ipsr_ah_req;
9956 	esp_req = req->ipsr_esp_req;
9957 	se_req = req->ipsr_self_encap_req;
9958 
9959 	/* Don't allow setting self-encap without one or more of AH/ESP. */
9960 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
9961 		return (EINVAL);
9962 
9963 	/*
9964 	 * Are we dealing with a request to reset the policy (i.e.
9965 	 * zero requests).
9966 	 */
9967 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
9968 	    (esp_req & REQ_MASK) == 0 &&
9969 	    (se_req & REQ_MASK) == 0);
9970 
9971 	if (!is_pol_reset) {
9972 		/*
9973 		 * If we couldn't load IPsec, fail with "protocol
9974 		 * not supported".
9975 		 * IPsec may not have been loaded for a request with zero
9976 		 * policies, so we don't fail in this case.
9977 		 */
9978 		mutex_enter(&ipss->ipsec_loader_lock);
9979 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
9980 			mutex_exit(&ipss->ipsec_loader_lock);
9981 			return (EPROTONOSUPPORT);
9982 		}
9983 		mutex_exit(&ipss->ipsec_loader_lock);
9984 
9985 		/*
9986 		 * Test for valid requests. Invalid algorithms
9987 		 * need to be tested by IPsec code because new
9988 		 * algorithms can be added dynamically.
9989 		 */
9990 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9991 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9992 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
9993 			return (EINVAL);
9994 		}
9995 
9996 		/*
9997 		 * Only privileged users can issue these
9998 		 * requests.
9999 		 */
10000 		if (((ah_req & IPSEC_PREF_NEVER) ||
10001 		    (esp_req & IPSEC_PREF_NEVER) ||
10002 		    (se_req & IPSEC_PREF_NEVER)) &&
10003 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10004 			return (EPERM);
10005 		}
10006 
10007 		/*
10008 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10009 		 * are mutually exclusive.
10010 		 */
10011 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10012 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10013 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10014 			/* Both of them are set */
10015 			return (EINVAL);
10016 		}
10017 	}
10018 
10019 	mutex_enter(&connp->conn_lock);
10020 
10021 	/*
10022 	 * If we have already cached policies in ip_bind_connected*(), don't
10023 	 * let them change now. We cache policies for connections
10024 	 * whose src,dst [addr, port] is known.
10025 	 */
10026 	if (connp->conn_policy_cached) {
10027 		mutex_exit(&connp->conn_lock);
10028 		return (EINVAL);
10029 	}
10030 
10031 	/*
10032 	 * We have a zero policies, reset the connection policy if already
10033 	 * set. This will cause the connection to inherit the
10034 	 * global policy, if any.
10035 	 */
10036 	if (is_pol_reset) {
10037 		if (connp->conn_policy != NULL) {
10038 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10039 			connp->conn_policy = NULL;
10040 		}
10041 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10042 		connp->conn_in_enforce_policy = B_FALSE;
10043 		connp->conn_out_enforce_policy = B_FALSE;
10044 		mutex_exit(&connp->conn_lock);
10045 		return (0);
10046 	}
10047 
10048 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10049 	    ipst->ips_netstack);
10050 	if (ph == NULL)
10051 		goto enomem;
10052 
10053 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10054 	if (actp == NULL)
10055 		goto enomem;
10056 
10057 	/*
10058 	 * Always allocate IPv4 policy entries, since they can also
10059 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10060 	 */
10061 	bzero(&sel, sizeof (sel));
10062 	sel.ipsl_valid = IPSL_IPV4;
10063 
10064 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10065 	    ipst->ips_netstack);
10066 	if (pin4 == NULL)
10067 		goto enomem;
10068 
10069 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10070 	    ipst->ips_netstack);
10071 	if (pout4 == NULL)
10072 		goto enomem;
10073 
10074 	if (connp->conn_af_isv6) {
10075 		/*
10076 		 * We're looking at a v6 socket, also allocate the
10077 		 * v6-specific entries...
10078 		 */
10079 		sel.ipsl_valid = IPSL_IPV6;
10080 		pin6 = ipsec_policy_create(&sel, actp, nact,
10081 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10082 		if (pin6 == NULL)
10083 			goto enomem;
10084 
10085 		pout6 = ipsec_policy_create(&sel, actp, nact,
10086 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10087 		if (pout6 == NULL)
10088 			goto enomem;
10089 
10090 		/*
10091 		 * .. and file them away in the right place.
10092 		 */
10093 		fam = IPSEC_AF_V6;
10094 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10095 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10096 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10097 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10098 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10099 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10100 	}
10101 
10102 	ipsec_actvec_free(actp, nact);
10103 
10104 	/*
10105 	 * File the v4 policies.
10106 	 */
10107 	fam = IPSEC_AF_V4;
10108 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10109 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10110 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10111 
10112 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10113 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10114 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10115 
10116 	/*
10117 	 * If the requests need security, set enforce_policy.
10118 	 * If the requests are IPSEC_PREF_NEVER, one should
10119 	 * still set conn_out_enforce_policy so that an ipsec_out
10120 	 * gets attached in ip_wput. This is needed so that
10121 	 * for connections that we don't cache policy in ip_bind,
10122 	 * if global policy matches in ip_wput_attach_policy, we
10123 	 * don't wrongly inherit global policy. Similarly, we need
10124 	 * to set conn_in_enforce_policy also so that we don't verify
10125 	 * policy wrongly.
10126 	 */
10127 	if ((ah_req & REQ_MASK) != 0 ||
10128 	    (esp_req & REQ_MASK) != 0 ||
10129 	    (se_req & REQ_MASK) != 0) {
10130 		connp->conn_in_enforce_policy = B_TRUE;
10131 		connp->conn_out_enforce_policy = B_TRUE;
10132 		connp->conn_flags |= IPCL_CHECK_POLICY;
10133 	}
10134 
10135 	mutex_exit(&connp->conn_lock);
10136 	return (error);
10137 #undef REQ_MASK
10138 
10139 	/*
10140 	 * Common memory-allocation-failure exit path.
10141 	 */
10142 enomem:
10143 	mutex_exit(&connp->conn_lock);
10144 	if (actp != NULL)
10145 		ipsec_actvec_free(actp, nact);
10146 	if (pin4 != NULL)
10147 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10148 	if (pout4 != NULL)
10149 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10150 	if (pin6 != NULL)
10151 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10152 	if (pout6 != NULL)
10153 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10154 	return (ENOMEM);
10155 }
10156 
10157 /*
10158  * Only for options that pass in an IP addr. Currently only V4 options
10159  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10160  * So this function assumes level is IPPROTO_IP
10161  */
10162 int
10163 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10164     mblk_t *first_mp)
10165 {
10166 	ipif_t *ipif = NULL;
10167 	int error;
10168 	ill_t *ill;
10169 	int zoneid;
10170 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10171 
10172 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10173 
10174 	if (addr != INADDR_ANY || checkonly) {
10175 		ASSERT(connp != NULL);
10176 		zoneid = IPCL_ZONEID(connp);
10177 		if (option == IP_NEXTHOP) {
10178 			ipif = ipif_lookup_onlink_addr(addr,
10179 			    connp->conn_zoneid, ipst);
10180 		} else {
10181 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10182 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10183 			    &error, ipst);
10184 		}
10185 		if (ipif == NULL) {
10186 			if (error == EINPROGRESS)
10187 				return (error);
10188 			if ((option == IP_MULTICAST_IF) ||
10189 			    (option == IP_NEXTHOP))
10190 				return (EHOSTUNREACH);
10191 			else
10192 				return (EINVAL);
10193 		} else if (checkonly) {
10194 			if (option == IP_MULTICAST_IF) {
10195 				ill = ipif->ipif_ill;
10196 				/* not supported by the virtual network iface */
10197 				if (IS_VNI(ill)) {
10198 					ipif_refrele(ipif);
10199 					return (EINVAL);
10200 				}
10201 			}
10202 			ipif_refrele(ipif);
10203 			return (0);
10204 		}
10205 		ill = ipif->ipif_ill;
10206 		mutex_enter(&connp->conn_lock);
10207 		mutex_enter(&ill->ill_lock);
10208 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10209 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10210 			mutex_exit(&ill->ill_lock);
10211 			mutex_exit(&connp->conn_lock);
10212 			ipif_refrele(ipif);
10213 			return (option == IP_MULTICAST_IF ?
10214 			    EHOSTUNREACH : EINVAL);
10215 		}
10216 	} else {
10217 		mutex_enter(&connp->conn_lock);
10218 	}
10219 
10220 	/* None of the options below are supported on the VNI */
10221 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10222 		mutex_exit(&ill->ill_lock);
10223 		mutex_exit(&connp->conn_lock);
10224 		ipif_refrele(ipif);
10225 		return (EINVAL);
10226 	}
10227 
10228 	switch (option) {
10229 	case IP_MULTICAST_IF:
10230 		connp->conn_multicast_ipif = ipif;
10231 		break;
10232 	case IP_NEXTHOP:
10233 		connp->conn_nexthop_v4 = addr;
10234 		connp->conn_nexthop_set = B_TRUE;
10235 		break;
10236 	}
10237 
10238 	if (ipif != NULL) {
10239 		mutex_exit(&ill->ill_lock);
10240 		mutex_exit(&connp->conn_lock);
10241 		ipif_refrele(ipif);
10242 		return (0);
10243 	}
10244 	mutex_exit(&connp->conn_lock);
10245 	/* We succeded in cleared the option */
10246 	return (0);
10247 }
10248 
10249 /*
10250  * For options that pass in an ifindex specifying the ill. V6 options always
10251  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10252  */
10253 int
10254 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10255     int level, int option, mblk_t *first_mp)
10256 {
10257 	ill_t *ill = NULL;
10258 	int error = 0;
10259 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10260 
10261 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10262 	if (ifindex != 0) {
10263 		ASSERT(connp != NULL);
10264 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10265 		    first_mp, ip_restart_optmgmt, &error, ipst);
10266 		if (ill != NULL) {
10267 			if (checkonly) {
10268 				/* not supported by the virtual network iface */
10269 				if (IS_VNI(ill)) {
10270 					ill_refrele(ill);
10271 					return (EINVAL);
10272 				}
10273 				ill_refrele(ill);
10274 				return (0);
10275 			}
10276 			if (!ipif_lookup_zoneid(ill, connp->conn_zoneid,
10277 			    0, NULL)) {
10278 				ill_refrele(ill);
10279 				ill = NULL;
10280 				mutex_enter(&connp->conn_lock);
10281 				goto setit;
10282 			}
10283 			mutex_enter(&connp->conn_lock);
10284 			mutex_enter(&ill->ill_lock);
10285 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10286 				mutex_exit(&ill->ill_lock);
10287 				mutex_exit(&connp->conn_lock);
10288 				ill_refrele(ill);
10289 				ill = NULL;
10290 				mutex_enter(&connp->conn_lock);
10291 			}
10292 			goto setit;
10293 		} else if (error == EINPROGRESS) {
10294 			return (error);
10295 		} else {
10296 			error = 0;
10297 		}
10298 	}
10299 	mutex_enter(&connp->conn_lock);
10300 setit:
10301 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10302 
10303 	/*
10304 	 * The options below assume that the ILL (if any) transmits and/or
10305 	 * receives traffic. Neither of which is true for the virtual network
10306 	 * interface, so fail setting these on a VNI.
10307 	 */
10308 	if (IS_VNI(ill)) {
10309 		ASSERT(ill != NULL);
10310 		mutex_exit(&ill->ill_lock);
10311 		mutex_exit(&connp->conn_lock);
10312 		ill_refrele(ill);
10313 		return (EINVAL);
10314 	}
10315 
10316 	if (level == IPPROTO_IP) {
10317 		switch (option) {
10318 		case IP_BOUND_IF:
10319 			connp->conn_incoming_ill = ill;
10320 			connp->conn_outgoing_ill = ill;
10321 			break;
10322 
10323 		case IP_MULTICAST_IF:
10324 			/*
10325 			 * This option is an internal special. The socket
10326 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10327 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10328 			 * specifies an ifindex and we try first on V6 ill's.
10329 			 * If we don't find one, we they try using on v4 ill's
10330 			 * intenally and we come here.
10331 			 */
10332 			if (!checkonly && ill != NULL) {
10333 				ipif_t	*ipif;
10334 				ipif = ill->ill_ipif;
10335 
10336 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10337 					mutex_exit(&ill->ill_lock);
10338 					mutex_exit(&connp->conn_lock);
10339 					ill_refrele(ill);
10340 					ill = NULL;
10341 					mutex_enter(&connp->conn_lock);
10342 				} else {
10343 					connp->conn_multicast_ipif = ipif;
10344 				}
10345 			}
10346 			break;
10347 
10348 		case IP_DHCPINIT_IF:
10349 			if (connp->conn_dhcpinit_ill != NULL) {
10350 				/*
10351 				 * We've locked the conn so conn_cleanup_ill()
10352 				 * cannot clear conn_dhcpinit_ill -- so it's
10353 				 * safe to access the ill.
10354 				 */
10355 				ill_t *oill = connp->conn_dhcpinit_ill;
10356 
10357 				ASSERT(oill->ill_dhcpinit != 0);
10358 				atomic_dec_32(&oill->ill_dhcpinit);
10359 				connp->conn_dhcpinit_ill = NULL;
10360 			}
10361 
10362 			if (ill != NULL) {
10363 				connp->conn_dhcpinit_ill = ill;
10364 				atomic_inc_32(&ill->ill_dhcpinit);
10365 			}
10366 			break;
10367 		}
10368 	} else {
10369 		switch (option) {
10370 		case IPV6_BOUND_IF:
10371 			connp->conn_incoming_ill = ill;
10372 			connp->conn_outgoing_ill = ill;
10373 			break;
10374 
10375 		case IPV6_MULTICAST_IF:
10376 			/*
10377 			 * Set conn_multicast_ill to be the IPv6 ill.
10378 			 * Set conn_multicast_ipif to be an IPv4 ipif
10379 			 * for ifindex to make IPv4 mapped addresses
10380 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10381 			 * Even if no IPv6 ill exists for the ifindex
10382 			 * we need to check for an IPv4 ifindex in order
10383 			 * for this to work with mapped addresses. In that
10384 			 * case only set conn_multicast_ipif.
10385 			 */
10386 			if (!checkonly) {
10387 				if (ifindex == 0) {
10388 					connp->conn_multicast_ill = NULL;
10389 					connp->conn_multicast_ipif = NULL;
10390 				} else if (ill != NULL) {
10391 					connp->conn_multicast_ill = ill;
10392 				}
10393 			}
10394 			break;
10395 		}
10396 	}
10397 
10398 	if (ill != NULL) {
10399 		mutex_exit(&ill->ill_lock);
10400 		mutex_exit(&connp->conn_lock);
10401 		ill_refrele(ill);
10402 		return (0);
10403 	}
10404 	mutex_exit(&connp->conn_lock);
10405 	/*
10406 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10407 	 * locate the ill and could not set the option (ifindex != 0)
10408 	 */
10409 	return (ifindex == 0 ? 0 : EINVAL);
10410 }
10411 
10412 /* This routine sets socket options. */
10413 /* ARGSUSED */
10414 int
10415 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10416     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10417     void *dummy, cred_t *cr, mblk_t *first_mp)
10418 {
10419 	int		*i1 = (int *)invalp;
10420 	conn_t		*connp = Q_TO_CONN(q);
10421 	int		error = 0;
10422 	boolean_t	checkonly;
10423 	ire_t		*ire;
10424 	boolean_t	found;
10425 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10426 
10427 	switch (optset_context) {
10428 
10429 	case SETFN_OPTCOM_CHECKONLY:
10430 		checkonly = B_TRUE;
10431 		/*
10432 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10433 		 * inlen != 0 implies value supplied and
10434 		 * 	we have to "pretend" to set it.
10435 		 * inlen == 0 implies that there is no
10436 		 * 	value part in T_CHECK request and just validation
10437 		 * done elsewhere should be enough, we just return here.
10438 		 */
10439 		if (inlen == 0) {
10440 			*outlenp = 0;
10441 			return (0);
10442 		}
10443 		break;
10444 	case SETFN_OPTCOM_NEGOTIATE:
10445 	case SETFN_UD_NEGOTIATE:
10446 	case SETFN_CONN_NEGOTIATE:
10447 		checkonly = B_FALSE;
10448 		break;
10449 	default:
10450 		/*
10451 		 * We should never get here
10452 		 */
10453 		*outlenp = 0;
10454 		return (EINVAL);
10455 	}
10456 
10457 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10458 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10459 
10460 	/*
10461 	 * For fixed length options, no sanity check
10462 	 * of passed in length is done. It is assumed *_optcom_req()
10463 	 * routines do the right thing.
10464 	 */
10465 
10466 	switch (level) {
10467 	case SOL_SOCKET:
10468 		/*
10469 		 * conn_lock protects the bitfields, and is used to
10470 		 * set the fields atomically.
10471 		 */
10472 		switch (name) {
10473 		case SO_BROADCAST:
10474 			if (!checkonly) {
10475 				/* TODO: use value someplace? */
10476 				mutex_enter(&connp->conn_lock);
10477 				connp->conn_broadcast = *i1 ? 1 : 0;
10478 				mutex_exit(&connp->conn_lock);
10479 			}
10480 			break;	/* goto sizeof (int) option return */
10481 		case SO_USELOOPBACK:
10482 			if (!checkonly) {
10483 				/* TODO: use value someplace? */
10484 				mutex_enter(&connp->conn_lock);
10485 				connp->conn_loopback = *i1 ? 1 : 0;
10486 				mutex_exit(&connp->conn_lock);
10487 			}
10488 			break;	/* goto sizeof (int) option return */
10489 		case SO_DONTROUTE:
10490 			if (!checkonly) {
10491 				mutex_enter(&connp->conn_lock);
10492 				connp->conn_dontroute = *i1 ? 1 : 0;
10493 				mutex_exit(&connp->conn_lock);
10494 			}
10495 			break;	/* goto sizeof (int) option return */
10496 		case SO_REUSEADDR:
10497 			if (!checkonly) {
10498 				mutex_enter(&connp->conn_lock);
10499 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10500 				mutex_exit(&connp->conn_lock);
10501 			}
10502 			break;	/* goto sizeof (int) option return */
10503 		case SO_PROTOTYPE:
10504 			if (!checkonly) {
10505 				mutex_enter(&connp->conn_lock);
10506 				connp->conn_proto = *i1;
10507 				mutex_exit(&connp->conn_lock);
10508 			}
10509 			break;	/* goto sizeof (int) option return */
10510 		case SO_ALLZONES:
10511 			if (!checkonly) {
10512 				mutex_enter(&connp->conn_lock);
10513 				if (IPCL_IS_BOUND(connp)) {
10514 					mutex_exit(&connp->conn_lock);
10515 					return (EINVAL);
10516 				}
10517 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10518 				mutex_exit(&connp->conn_lock);
10519 			}
10520 			break;	/* goto sizeof (int) option return */
10521 		case SO_ANON_MLP:
10522 			if (!checkonly) {
10523 				mutex_enter(&connp->conn_lock);
10524 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10525 				mutex_exit(&connp->conn_lock);
10526 			}
10527 			break;	/* goto sizeof (int) option return */
10528 		case SO_MAC_EXEMPT:
10529 			if (secpolicy_net_mac_aware(cr) != 0 ||
10530 			    IPCL_IS_BOUND(connp))
10531 				return (EACCES);
10532 			if (!checkonly) {
10533 				mutex_enter(&connp->conn_lock);
10534 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10535 				mutex_exit(&connp->conn_lock);
10536 			}
10537 			break;	/* goto sizeof (int) option return */
10538 		default:
10539 			/*
10540 			 * "soft" error (negative)
10541 			 * option not handled at this level
10542 			 * Note: Do not modify *outlenp
10543 			 */
10544 			return (-EINVAL);
10545 		}
10546 		break;
10547 	case IPPROTO_IP:
10548 		switch (name) {
10549 		case IP_NEXTHOP:
10550 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10551 				return (EPERM);
10552 			/* FALLTHRU */
10553 		case IP_MULTICAST_IF: {
10554 			ipaddr_t addr = *i1;
10555 
10556 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10557 			    first_mp);
10558 			if (error != 0)
10559 				return (error);
10560 			break;	/* goto sizeof (int) option return */
10561 		}
10562 
10563 		case IP_MULTICAST_TTL:
10564 			/* Recorded in transport above IP */
10565 			*outvalp = *invalp;
10566 			*outlenp = sizeof (uchar_t);
10567 			return (0);
10568 		case IP_MULTICAST_LOOP:
10569 			if (!checkonly) {
10570 				mutex_enter(&connp->conn_lock);
10571 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10572 				mutex_exit(&connp->conn_lock);
10573 			}
10574 			*outvalp = *invalp;
10575 			*outlenp = sizeof (uchar_t);
10576 			return (0);
10577 		case IP_ADD_MEMBERSHIP:
10578 		case MCAST_JOIN_GROUP:
10579 		case IP_DROP_MEMBERSHIP:
10580 		case MCAST_LEAVE_GROUP: {
10581 			struct ip_mreq *mreqp;
10582 			struct group_req *greqp;
10583 			ire_t *ire;
10584 			boolean_t done = B_FALSE;
10585 			ipaddr_t group, ifaddr;
10586 			struct sockaddr_in *sin;
10587 			uint32_t *ifindexp;
10588 			boolean_t mcast_opt = B_TRUE;
10589 			mcast_record_t fmode;
10590 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10591 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10592 
10593 			switch (name) {
10594 			case IP_ADD_MEMBERSHIP:
10595 				mcast_opt = B_FALSE;
10596 				/* FALLTHRU */
10597 			case MCAST_JOIN_GROUP:
10598 				fmode = MODE_IS_EXCLUDE;
10599 				optfn = ip_opt_add_group;
10600 				break;
10601 
10602 			case IP_DROP_MEMBERSHIP:
10603 				mcast_opt = B_FALSE;
10604 				/* FALLTHRU */
10605 			case MCAST_LEAVE_GROUP:
10606 				fmode = MODE_IS_INCLUDE;
10607 				optfn = ip_opt_delete_group;
10608 				break;
10609 			}
10610 
10611 			if (mcast_opt) {
10612 				greqp = (struct group_req *)i1;
10613 				sin = (struct sockaddr_in *)&greqp->gr_group;
10614 				if (sin->sin_family != AF_INET) {
10615 					*outlenp = 0;
10616 					return (ENOPROTOOPT);
10617 				}
10618 				group = (ipaddr_t)sin->sin_addr.s_addr;
10619 				ifaddr = INADDR_ANY;
10620 				ifindexp = &greqp->gr_interface;
10621 			} else {
10622 				mreqp = (struct ip_mreq *)i1;
10623 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10624 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10625 				ifindexp = NULL;
10626 			}
10627 
10628 			/*
10629 			 * In the multirouting case, we need to replicate
10630 			 * the request on all interfaces that will take part
10631 			 * in replication.  We do so because multirouting is
10632 			 * reflective, thus we will probably receive multi-
10633 			 * casts on those interfaces.
10634 			 * The ip_multirt_apply_membership() succeeds if the
10635 			 * operation succeeds on at least one interface.
10636 			 */
10637 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10638 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10639 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10640 			if (ire != NULL) {
10641 				if (ire->ire_flags & RTF_MULTIRT) {
10642 					error = ip_multirt_apply_membership(
10643 					    optfn, ire, connp, checkonly, group,
10644 					    fmode, INADDR_ANY, first_mp);
10645 					done = B_TRUE;
10646 				}
10647 				ire_refrele(ire);
10648 			}
10649 			if (!done) {
10650 				error = optfn(connp, checkonly, group, ifaddr,
10651 				    ifindexp, fmode, INADDR_ANY, first_mp);
10652 			}
10653 			if (error) {
10654 				/*
10655 				 * EINPROGRESS is a soft error, needs retry
10656 				 * so don't make *outlenp zero.
10657 				 */
10658 				if (error != EINPROGRESS)
10659 					*outlenp = 0;
10660 				return (error);
10661 			}
10662 			/* OK return - copy input buffer into output buffer */
10663 			if (invalp != outvalp) {
10664 				/* don't trust bcopy for identical src/dst */
10665 				bcopy(invalp, outvalp, inlen);
10666 			}
10667 			*outlenp = inlen;
10668 			return (0);
10669 		}
10670 		case IP_BLOCK_SOURCE:
10671 		case IP_UNBLOCK_SOURCE:
10672 		case IP_ADD_SOURCE_MEMBERSHIP:
10673 		case IP_DROP_SOURCE_MEMBERSHIP:
10674 		case MCAST_BLOCK_SOURCE:
10675 		case MCAST_UNBLOCK_SOURCE:
10676 		case MCAST_JOIN_SOURCE_GROUP:
10677 		case MCAST_LEAVE_SOURCE_GROUP: {
10678 			struct ip_mreq_source *imreqp;
10679 			struct group_source_req *gsreqp;
10680 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10681 			uint32_t ifindex = 0;
10682 			mcast_record_t fmode;
10683 			struct sockaddr_in *sin;
10684 			ire_t *ire;
10685 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10686 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10687 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10688 
10689 			switch (name) {
10690 			case IP_BLOCK_SOURCE:
10691 				mcast_opt = B_FALSE;
10692 				/* FALLTHRU */
10693 			case MCAST_BLOCK_SOURCE:
10694 				fmode = MODE_IS_EXCLUDE;
10695 				optfn = ip_opt_add_group;
10696 				break;
10697 
10698 			case IP_UNBLOCK_SOURCE:
10699 				mcast_opt = B_FALSE;
10700 				/* FALLTHRU */
10701 			case MCAST_UNBLOCK_SOURCE:
10702 				fmode = MODE_IS_EXCLUDE;
10703 				optfn = ip_opt_delete_group;
10704 				break;
10705 
10706 			case IP_ADD_SOURCE_MEMBERSHIP:
10707 				mcast_opt = B_FALSE;
10708 				/* FALLTHRU */
10709 			case MCAST_JOIN_SOURCE_GROUP:
10710 				fmode = MODE_IS_INCLUDE;
10711 				optfn = ip_opt_add_group;
10712 				break;
10713 
10714 			case IP_DROP_SOURCE_MEMBERSHIP:
10715 				mcast_opt = B_FALSE;
10716 				/* FALLTHRU */
10717 			case MCAST_LEAVE_SOURCE_GROUP:
10718 				fmode = MODE_IS_INCLUDE;
10719 				optfn = ip_opt_delete_group;
10720 				break;
10721 			}
10722 
10723 			if (mcast_opt) {
10724 				gsreqp = (struct group_source_req *)i1;
10725 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10726 					*outlenp = 0;
10727 					return (ENOPROTOOPT);
10728 				}
10729 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10730 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10731 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10732 				src = (ipaddr_t)sin->sin_addr.s_addr;
10733 				ifindex = gsreqp->gsr_interface;
10734 			} else {
10735 				imreqp = (struct ip_mreq_source *)i1;
10736 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10737 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10738 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10739 			}
10740 
10741 			/*
10742 			 * In the multirouting case, we need to replicate
10743 			 * the request as noted in the mcast cases above.
10744 			 */
10745 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10746 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10747 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10748 			if (ire != NULL) {
10749 				if (ire->ire_flags & RTF_MULTIRT) {
10750 					error = ip_multirt_apply_membership(
10751 					    optfn, ire, connp, checkonly, grp,
10752 					    fmode, src, first_mp);
10753 					done = B_TRUE;
10754 				}
10755 				ire_refrele(ire);
10756 			}
10757 			if (!done) {
10758 				error = optfn(connp, checkonly, grp, ifaddr,
10759 				    &ifindex, fmode, src, first_mp);
10760 			}
10761 			if (error != 0) {
10762 				/*
10763 				 * EINPROGRESS is a soft error, needs retry
10764 				 * so don't make *outlenp zero.
10765 				 */
10766 				if (error != EINPROGRESS)
10767 					*outlenp = 0;
10768 				return (error);
10769 			}
10770 			/* OK return - copy input buffer into output buffer */
10771 			if (invalp != outvalp) {
10772 				bcopy(invalp, outvalp, inlen);
10773 			}
10774 			*outlenp = inlen;
10775 			return (0);
10776 		}
10777 		case IP_SEC_OPT:
10778 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10779 			if (error != 0) {
10780 				*outlenp = 0;
10781 				return (error);
10782 			}
10783 			break;
10784 		case IP_HDRINCL:
10785 		case IP_OPTIONS:
10786 		case T_IP_OPTIONS:
10787 		case IP_TOS:
10788 		case T_IP_TOS:
10789 		case IP_TTL:
10790 		case IP_RECVDSTADDR:
10791 		case IP_RECVOPTS:
10792 			/* OK return - copy input buffer into output buffer */
10793 			if (invalp != outvalp) {
10794 				/* don't trust bcopy for identical src/dst */
10795 				bcopy(invalp, outvalp, inlen);
10796 			}
10797 			*outlenp = inlen;
10798 			return (0);
10799 		case IP_RECVIF:
10800 			/* Retrieve the inbound interface index */
10801 			if (!checkonly) {
10802 				mutex_enter(&connp->conn_lock);
10803 				connp->conn_recvif = *i1 ? 1 : 0;
10804 				mutex_exit(&connp->conn_lock);
10805 			}
10806 			break;	/* goto sizeof (int) option return */
10807 		case IP_RECVPKTINFO:
10808 			if (!checkonly) {
10809 				mutex_enter(&connp->conn_lock);
10810 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
10811 				mutex_exit(&connp->conn_lock);
10812 			}
10813 			break;	/* goto sizeof (int) option return */
10814 		case IP_RECVSLLA:
10815 			/* Retrieve the source link layer address */
10816 			if (!checkonly) {
10817 				mutex_enter(&connp->conn_lock);
10818 				connp->conn_recvslla = *i1 ? 1 : 0;
10819 				mutex_exit(&connp->conn_lock);
10820 			}
10821 			break;	/* goto sizeof (int) option return */
10822 		case MRT_INIT:
10823 		case MRT_DONE:
10824 		case MRT_ADD_VIF:
10825 		case MRT_DEL_VIF:
10826 		case MRT_ADD_MFC:
10827 		case MRT_DEL_MFC:
10828 		case MRT_ASSERT:
10829 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
10830 				*outlenp = 0;
10831 				return (error);
10832 			}
10833 			error = ip_mrouter_set((int)name, q, checkonly,
10834 			    (uchar_t *)invalp, inlen, first_mp);
10835 			if (error) {
10836 				*outlenp = 0;
10837 				return (error);
10838 			}
10839 			/* OK return - copy input buffer into output buffer */
10840 			if (invalp != outvalp) {
10841 				/* don't trust bcopy for identical src/dst */
10842 				bcopy(invalp, outvalp, inlen);
10843 			}
10844 			*outlenp = inlen;
10845 			return (0);
10846 		case IP_BOUND_IF:
10847 		case IP_DHCPINIT_IF:
10848 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10849 			    level, name, first_mp);
10850 			if (error != 0)
10851 				return (error);
10852 			break; 		/* goto sizeof (int) option return */
10853 
10854 		case IP_UNSPEC_SRC:
10855 			/* Allow sending with a zero source address */
10856 			if (!checkonly) {
10857 				mutex_enter(&connp->conn_lock);
10858 				connp->conn_unspec_src = *i1 ? 1 : 0;
10859 				mutex_exit(&connp->conn_lock);
10860 			}
10861 			break;	/* goto sizeof (int) option return */
10862 		default:
10863 			/*
10864 			 * "soft" error (negative)
10865 			 * option not handled at this level
10866 			 * Note: Do not modify *outlenp
10867 			 */
10868 			return (-EINVAL);
10869 		}
10870 		break;
10871 	case IPPROTO_IPV6:
10872 		switch (name) {
10873 		case IPV6_BOUND_IF:
10874 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10875 			    level, name, first_mp);
10876 			if (error != 0)
10877 				return (error);
10878 			break; 		/* goto sizeof (int) option return */
10879 
10880 		case IPV6_MULTICAST_IF:
10881 			/*
10882 			 * The only possible errors are EINPROGRESS and
10883 			 * EINVAL. EINPROGRESS will be restarted and is not
10884 			 * a hard error. We call this option on both V4 and V6
10885 			 * If both return EINVAL, then this call returns
10886 			 * EINVAL. If at least one of them succeeds we
10887 			 * return success.
10888 			 */
10889 			found = B_FALSE;
10890 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10891 			    level, name, first_mp);
10892 			if (error == EINPROGRESS)
10893 				return (error);
10894 			if (error == 0)
10895 				found = B_TRUE;
10896 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10897 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
10898 			if (error == 0)
10899 				found = B_TRUE;
10900 			if (!found)
10901 				return (error);
10902 			break; 		/* goto sizeof (int) option return */
10903 
10904 		case IPV6_MULTICAST_HOPS:
10905 			/* Recorded in transport above IP */
10906 			break;	/* goto sizeof (int) option return */
10907 		case IPV6_MULTICAST_LOOP:
10908 			if (!checkonly) {
10909 				mutex_enter(&connp->conn_lock);
10910 				connp->conn_multicast_loop = *i1;
10911 				mutex_exit(&connp->conn_lock);
10912 			}
10913 			break;	/* goto sizeof (int) option return */
10914 		case IPV6_JOIN_GROUP:
10915 		case MCAST_JOIN_GROUP:
10916 		case IPV6_LEAVE_GROUP:
10917 		case MCAST_LEAVE_GROUP: {
10918 			struct ipv6_mreq *ip_mreqp;
10919 			struct group_req *greqp;
10920 			ire_t *ire;
10921 			boolean_t done = B_FALSE;
10922 			in6_addr_t groupv6;
10923 			uint32_t ifindex;
10924 			boolean_t mcast_opt = B_TRUE;
10925 			mcast_record_t fmode;
10926 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10927 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10928 
10929 			switch (name) {
10930 			case IPV6_JOIN_GROUP:
10931 				mcast_opt = B_FALSE;
10932 				/* FALLTHRU */
10933 			case MCAST_JOIN_GROUP:
10934 				fmode = MODE_IS_EXCLUDE;
10935 				optfn = ip_opt_add_group_v6;
10936 				break;
10937 
10938 			case IPV6_LEAVE_GROUP:
10939 				mcast_opt = B_FALSE;
10940 				/* FALLTHRU */
10941 			case MCAST_LEAVE_GROUP:
10942 				fmode = MODE_IS_INCLUDE;
10943 				optfn = ip_opt_delete_group_v6;
10944 				break;
10945 			}
10946 
10947 			if (mcast_opt) {
10948 				struct sockaddr_in *sin;
10949 				struct sockaddr_in6 *sin6;
10950 				greqp = (struct group_req *)i1;
10951 				if (greqp->gr_group.ss_family == AF_INET) {
10952 					sin = (struct sockaddr_in *)
10953 					    &(greqp->gr_group);
10954 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
10955 					    &groupv6);
10956 				} else {
10957 					sin6 = (struct sockaddr_in6 *)
10958 					    &(greqp->gr_group);
10959 					groupv6 = sin6->sin6_addr;
10960 				}
10961 				ifindex = greqp->gr_interface;
10962 			} else {
10963 				ip_mreqp = (struct ipv6_mreq *)i1;
10964 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
10965 				ifindex = ip_mreqp->ipv6mr_interface;
10966 			}
10967 			/*
10968 			 * In the multirouting case, we need to replicate
10969 			 * the request on all interfaces that will take part
10970 			 * in replication.  We do so because multirouting is
10971 			 * reflective, thus we will probably receive multi-
10972 			 * casts on those interfaces.
10973 			 * The ip_multirt_apply_membership_v6() succeeds if
10974 			 * the operation succeeds on at least one interface.
10975 			 */
10976 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
10977 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10978 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10979 			if (ire != NULL) {
10980 				if (ire->ire_flags & RTF_MULTIRT) {
10981 					error = ip_multirt_apply_membership_v6(
10982 					    optfn, ire, connp, checkonly,
10983 					    &groupv6, fmode, &ipv6_all_zeros,
10984 					    first_mp);
10985 					done = B_TRUE;
10986 				}
10987 				ire_refrele(ire);
10988 			}
10989 			if (!done) {
10990 				error = optfn(connp, checkonly, &groupv6,
10991 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
10992 			}
10993 			if (error) {
10994 				/*
10995 				 * EINPROGRESS is a soft error, needs retry
10996 				 * so don't make *outlenp zero.
10997 				 */
10998 				if (error != EINPROGRESS)
10999 					*outlenp = 0;
11000 				return (error);
11001 			}
11002 			/* OK return - copy input buffer into output buffer */
11003 			if (invalp != outvalp) {
11004 				/* don't trust bcopy for identical src/dst */
11005 				bcopy(invalp, outvalp, inlen);
11006 			}
11007 			*outlenp = inlen;
11008 			return (0);
11009 		}
11010 		case MCAST_BLOCK_SOURCE:
11011 		case MCAST_UNBLOCK_SOURCE:
11012 		case MCAST_JOIN_SOURCE_GROUP:
11013 		case MCAST_LEAVE_SOURCE_GROUP: {
11014 			struct group_source_req *gsreqp;
11015 			in6_addr_t v6grp, v6src;
11016 			uint32_t ifindex;
11017 			mcast_record_t fmode;
11018 			ire_t *ire;
11019 			boolean_t done = B_FALSE;
11020 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11021 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11022 
11023 			switch (name) {
11024 			case MCAST_BLOCK_SOURCE:
11025 				fmode = MODE_IS_EXCLUDE;
11026 				optfn = ip_opt_add_group_v6;
11027 				break;
11028 			case MCAST_UNBLOCK_SOURCE:
11029 				fmode = MODE_IS_EXCLUDE;
11030 				optfn = ip_opt_delete_group_v6;
11031 				break;
11032 			case MCAST_JOIN_SOURCE_GROUP:
11033 				fmode = MODE_IS_INCLUDE;
11034 				optfn = ip_opt_add_group_v6;
11035 				break;
11036 			case MCAST_LEAVE_SOURCE_GROUP:
11037 				fmode = MODE_IS_INCLUDE;
11038 				optfn = ip_opt_delete_group_v6;
11039 				break;
11040 			}
11041 
11042 			gsreqp = (struct group_source_req *)i1;
11043 			ifindex = gsreqp->gsr_interface;
11044 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11045 				struct sockaddr_in *s;
11046 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11047 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11048 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11049 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11050 			} else {
11051 				struct sockaddr_in6 *s6;
11052 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11053 				v6grp = s6->sin6_addr;
11054 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11055 				v6src = s6->sin6_addr;
11056 			}
11057 
11058 			/*
11059 			 * In the multirouting case, we need to replicate
11060 			 * the request as noted in the mcast cases above.
11061 			 */
11062 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11063 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11064 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11065 			if (ire != NULL) {
11066 				if (ire->ire_flags & RTF_MULTIRT) {
11067 					error = ip_multirt_apply_membership_v6(
11068 					    optfn, ire, connp, checkonly,
11069 					    &v6grp, fmode, &v6src, first_mp);
11070 					done = B_TRUE;
11071 				}
11072 				ire_refrele(ire);
11073 			}
11074 			if (!done) {
11075 				error = optfn(connp, checkonly, &v6grp,
11076 				    ifindex, fmode, &v6src, first_mp);
11077 			}
11078 			if (error != 0) {
11079 				/*
11080 				 * EINPROGRESS is a soft error, needs retry
11081 				 * so don't make *outlenp zero.
11082 				 */
11083 				if (error != EINPROGRESS)
11084 					*outlenp = 0;
11085 				return (error);
11086 			}
11087 			/* OK return - copy input buffer into output buffer */
11088 			if (invalp != outvalp) {
11089 				bcopy(invalp, outvalp, inlen);
11090 			}
11091 			*outlenp = inlen;
11092 			return (0);
11093 		}
11094 		case IPV6_UNICAST_HOPS:
11095 			/* Recorded in transport above IP */
11096 			break;	/* goto sizeof (int) option return */
11097 		case IPV6_UNSPEC_SRC:
11098 			/* Allow sending with a zero source address */
11099 			if (!checkonly) {
11100 				mutex_enter(&connp->conn_lock);
11101 				connp->conn_unspec_src = *i1 ? 1 : 0;
11102 				mutex_exit(&connp->conn_lock);
11103 			}
11104 			break;	/* goto sizeof (int) option return */
11105 		case IPV6_RECVPKTINFO:
11106 			if (!checkonly) {
11107 				mutex_enter(&connp->conn_lock);
11108 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11109 				mutex_exit(&connp->conn_lock);
11110 			}
11111 			break;	/* goto sizeof (int) option return */
11112 		case IPV6_RECVTCLASS:
11113 			if (!checkonly) {
11114 				if (*i1 < 0 || *i1 > 1) {
11115 					return (EINVAL);
11116 				}
11117 				mutex_enter(&connp->conn_lock);
11118 				connp->conn_ipv6_recvtclass = *i1;
11119 				mutex_exit(&connp->conn_lock);
11120 			}
11121 			break;
11122 		case IPV6_RECVPATHMTU:
11123 			if (!checkonly) {
11124 				if (*i1 < 0 || *i1 > 1) {
11125 					return (EINVAL);
11126 				}
11127 				mutex_enter(&connp->conn_lock);
11128 				connp->conn_ipv6_recvpathmtu = *i1;
11129 				mutex_exit(&connp->conn_lock);
11130 			}
11131 			break;
11132 		case IPV6_RECVHOPLIMIT:
11133 			if (!checkonly) {
11134 				mutex_enter(&connp->conn_lock);
11135 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11136 				mutex_exit(&connp->conn_lock);
11137 			}
11138 			break;	/* goto sizeof (int) option return */
11139 		case IPV6_RECVHOPOPTS:
11140 			if (!checkonly) {
11141 				mutex_enter(&connp->conn_lock);
11142 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11143 				mutex_exit(&connp->conn_lock);
11144 			}
11145 			break;	/* goto sizeof (int) option return */
11146 		case IPV6_RECVDSTOPTS:
11147 			if (!checkonly) {
11148 				mutex_enter(&connp->conn_lock);
11149 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11150 				mutex_exit(&connp->conn_lock);
11151 			}
11152 			break;	/* goto sizeof (int) option return */
11153 		case IPV6_RECVRTHDR:
11154 			if (!checkonly) {
11155 				mutex_enter(&connp->conn_lock);
11156 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11157 				mutex_exit(&connp->conn_lock);
11158 			}
11159 			break;	/* goto sizeof (int) option return */
11160 		case IPV6_RECVRTHDRDSTOPTS:
11161 			if (!checkonly) {
11162 				mutex_enter(&connp->conn_lock);
11163 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11164 				mutex_exit(&connp->conn_lock);
11165 			}
11166 			break;	/* goto sizeof (int) option return */
11167 		case IPV6_PKTINFO:
11168 			if (inlen == 0)
11169 				return (-EINVAL);	/* clearing option */
11170 			error = ip6_set_pktinfo(cr, connp,
11171 			    (struct in6_pktinfo *)invalp, first_mp);
11172 			if (error != 0)
11173 				*outlenp = 0;
11174 			else
11175 				*outlenp = inlen;
11176 			return (error);
11177 		case IPV6_NEXTHOP: {
11178 			struct sockaddr_in6 *sin6;
11179 
11180 			/* Verify that the nexthop is reachable */
11181 			if (inlen == 0)
11182 				return (-EINVAL);	/* clearing option */
11183 
11184 			sin6 = (struct sockaddr_in6 *)invalp;
11185 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11186 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11187 			    NULL, MATCH_IRE_DEFAULT, ipst);
11188 
11189 			if (ire == NULL) {
11190 				*outlenp = 0;
11191 				return (EHOSTUNREACH);
11192 			}
11193 			ire_refrele(ire);
11194 			return (-EINVAL);
11195 		}
11196 		case IPV6_SEC_OPT:
11197 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11198 			if (error != 0) {
11199 				*outlenp = 0;
11200 				return (error);
11201 			}
11202 			break;
11203 		case IPV6_SRC_PREFERENCES: {
11204 			/*
11205 			 * This is implemented strictly in the ip module
11206 			 * (here and in tcp_opt_*() to accomodate tcp
11207 			 * sockets).  Modules above ip pass this option
11208 			 * down here since ip is the only one that needs to
11209 			 * be aware of source address preferences.
11210 			 *
11211 			 * This socket option only affects connected
11212 			 * sockets that haven't already bound to a specific
11213 			 * IPv6 address.  In other words, sockets that
11214 			 * don't call bind() with an address other than the
11215 			 * unspecified address and that call connect().
11216 			 * ip_bind_connected_v6() passes these preferences
11217 			 * to the ipif_select_source_v6() function.
11218 			 */
11219 			if (inlen != sizeof (uint32_t))
11220 				return (EINVAL);
11221 			error = ip6_set_src_preferences(connp,
11222 			    *(uint32_t *)invalp);
11223 			if (error != 0) {
11224 				*outlenp = 0;
11225 				return (error);
11226 			} else {
11227 				*outlenp = sizeof (uint32_t);
11228 			}
11229 			break;
11230 		}
11231 		case IPV6_V6ONLY:
11232 			if (*i1 < 0 || *i1 > 1) {
11233 				return (EINVAL);
11234 			}
11235 			mutex_enter(&connp->conn_lock);
11236 			connp->conn_ipv6_v6only = *i1;
11237 			mutex_exit(&connp->conn_lock);
11238 			break;
11239 		default:
11240 			return (-EINVAL);
11241 		}
11242 		break;
11243 	default:
11244 		/*
11245 		 * "soft" error (negative)
11246 		 * option not handled at this level
11247 		 * Note: Do not modify *outlenp
11248 		 */
11249 		return (-EINVAL);
11250 	}
11251 	/*
11252 	 * Common case of return from an option that is sizeof (int)
11253 	 */
11254 	*(int *)outvalp = *i1;
11255 	*outlenp = sizeof (int);
11256 	return (0);
11257 }
11258 
11259 /*
11260  * This routine gets default values of certain options whose default
11261  * values are maintained by protocol specific code
11262  */
11263 /* ARGSUSED */
11264 int
11265 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11266 {
11267 	int *i1 = (int *)ptr;
11268 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11269 
11270 	switch (level) {
11271 	case IPPROTO_IP:
11272 		switch (name) {
11273 		case IP_MULTICAST_TTL:
11274 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11275 			return (sizeof (uchar_t));
11276 		case IP_MULTICAST_LOOP:
11277 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11278 			return (sizeof (uchar_t));
11279 		default:
11280 			return (-1);
11281 		}
11282 	case IPPROTO_IPV6:
11283 		switch (name) {
11284 		case IPV6_UNICAST_HOPS:
11285 			*i1 = ipst->ips_ipv6_def_hops;
11286 			return (sizeof (int));
11287 		case IPV6_MULTICAST_HOPS:
11288 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11289 			return (sizeof (int));
11290 		case IPV6_MULTICAST_LOOP:
11291 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11292 			return (sizeof (int));
11293 		case IPV6_V6ONLY:
11294 			*i1 = 1;
11295 			return (sizeof (int));
11296 		default:
11297 			return (-1);
11298 		}
11299 	default:
11300 		return (-1);
11301 	}
11302 	/* NOTREACHED */
11303 }
11304 
11305 /*
11306  * Given a destination address and a pointer to where to put the information
11307  * this routine fills in the mtuinfo.
11308  */
11309 int
11310 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11311     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11312 {
11313 	ire_t *ire;
11314 	ip_stack_t	*ipst = ns->netstack_ip;
11315 
11316 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11317 		return (-1);
11318 
11319 	bzero(mtuinfo, sizeof (*mtuinfo));
11320 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11321 	mtuinfo->ip6m_addr.sin6_port = port;
11322 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11323 
11324 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11325 	if (ire != NULL) {
11326 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11327 		ire_refrele(ire);
11328 	} else {
11329 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11330 	}
11331 	return (sizeof (struct ip6_mtuinfo));
11332 }
11333 
11334 /*
11335  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11336  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11337  * isn't.  This doesn't matter as the error checking is done properly for the
11338  * other MRT options coming in through ip_opt_set.
11339  */
11340 int
11341 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11342 {
11343 	conn_t		*connp = Q_TO_CONN(q);
11344 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11345 
11346 	switch (level) {
11347 	case IPPROTO_IP:
11348 		switch (name) {
11349 		case MRT_VERSION:
11350 		case MRT_ASSERT:
11351 			(void) ip_mrouter_get(name, q, ptr);
11352 			return (sizeof (int));
11353 		case IP_SEC_OPT:
11354 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11355 		case IP_NEXTHOP:
11356 			if (connp->conn_nexthop_set) {
11357 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11358 				return (sizeof (ipaddr_t));
11359 			} else
11360 				return (0);
11361 		case IP_RECVPKTINFO:
11362 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11363 			return (sizeof (int));
11364 		default:
11365 			break;
11366 		}
11367 		break;
11368 	case IPPROTO_IPV6:
11369 		switch (name) {
11370 		case IPV6_SEC_OPT:
11371 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11372 		case IPV6_SRC_PREFERENCES: {
11373 			return (ip6_get_src_preferences(connp,
11374 			    (uint32_t *)ptr));
11375 		}
11376 		case IPV6_V6ONLY:
11377 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11378 			return (sizeof (int));
11379 		case IPV6_PATHMTU:
11380 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11381 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11382 		default:
11383 			break;
11384 		}
11385 		break;
11386 	default:
11387 		break;
11388 	}
11389 	return (-1);
11390 }
11391 /* Named Dispatch routine to get a current value out of our parameter table. */
11392 /* ARGSUSED */
11393 static int
11394 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11395 {
11396 	ipparam_t *ippa = (ipparam_t *)cp;
11397 
11398 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11399 	return (0);
11400 }
11401 
11402 /* ARGSUSED */
11403 static int
11404 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11405 {
11406 
11407 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11408 	return (0);
11409 }
11410 
11411 /*
11412  * Set ip{,6}_forwarding values.  This means walking through all of the
11413  * ill's and toggling their forwarding values.
11414  */
11415 /* ARGSUSED */
11416 static int
11417 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11418 {
11419 	long new_value;
11420 	int *forwarding_value = (int *)cp;
11421 	ill_t *ill;
11422 	boolean_t isv6;
11423 	ill_walk_context_t ctx;
11424 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11425 
11426 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11427 
11428 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11429 	    new_value < 0 || new_value > 1) {
11430 		return (EINVAL);
11431 	}
11432 
11433 	*forwarding_value = new_value;
11434 
11435 	/*
11436 	 * Regardless of the current value of ip_forwarding, set all per-ill
11437 	 * values of ip_forwarding to the value being set.
11438 	 *
11439 	 * Bring all the ill's up to date with the new global value.
11440 	 */
11441 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11442 
11443 	if (isv6)
11444 		ill = ILL_START_WALK_V6(&ctx, ipst);
11445 	else
11446 		ill = ILL_START_WALK_V4(&ctx, ipst);
11447 
11448 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11449 		(void) ill_forward_set(ill, new_value != 0);
11450 
11451 	rw_exit(&ipst->ips_ill_g_lock);
11452 	return (0);
11453 }
11454 
11455 /*
11456  * Walk through the param array specified registering each element with the
11457  * Named Dispatch handler. This is called only during init. So it is ok
11458  * not to acquire any locks
11459  */
11460 static boolean_t
11461 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11462     ipndp_t *ipnd, size_t ipnd_cnt)
11463 {
11464 	for (; ippa_cnt-- > 0; ippa++) {
11465 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11466 			if (!nd_load(ndp, ippa->ip_param_name,
11467 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11468 				nd_free(ndp);
11469 				return (B_FALSE);
11470 			}
11471 		}
11472 	}
11473 
11474 	for (; ipnd_cnt-- > 0; ipnd++) {
11475 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11476 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11477 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11478 			    ipnd->ip_ndp_data)) {
11479 				nd_free(ndp);
11480 				return (B_FALSE);
11481 			}
11482 		}
11483 	}
11484 
11485 	return (B_TRUE);
11486 }
11487 
11488 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11489 /* ARGSUSED */
11490 static int
11491 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11492 {
11493 	long		new_value;
11494 	ipparam_t	*ippa = (ipparam_t *)cp;
11495 
11496 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11497 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11498 		return (EINVAL);
11499 	}
11500 	ippa->ip_param_value = new_value;
11501 	return (0);
11502 }
11503 
11504 /*
11505  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11506  * When an ipf is passed here for the first time, if
11507  * we already have in-order fragments on the queue, we convert from the fast-
11508  * path reassembly scheme to the hard-case scheme.  From then on, additional
11509  * fragments are reassembled here.  We keep track of the start and end offsets
11510  * of each piece, and the number of holes in the chain.  When the hole count
11511  * goes to zero, we are done!
11512  *
11513  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11514  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11515  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11516  * after the call to ip_reassemble().
11517  */
11518 int
11519 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11520     size_t msg_len)
11521 {
11522 	uint_t	end;
11523 	mblk_t	*next_mp;
11524 	mblk_t	*mp1;
11525 	uint_t	offset;
11526 	boolean_t incr_dups = B_TRUE;
11527 	boolean_t offset_zero_seen = B_FALSE;
11528 	boolean_t pkt_boundary_checked = B_FALSE;
11529 
11530 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11531 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11532 
11533 	/* Add in byte count */
11534 	ipf->ipf_count += msg_len;
11535 	if (ipf->ipf_end) {
11536 		/*
11537 		 * We were part way through in-order reassembly, but now there
11538 		 * is a hole.  We walk through messages already queued, and
11539 		 * mark them for hard case reassembly.  We know that up till
11540 		 * now they were in order starting from offset zero.
11541 		 */
11542 		offset = 0;
11543 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11544 			IP_REASS_SET_START(mp1, offset);
11545 			if (offset == 0) {
11546 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11547 				offset = -ipf->ipf_nf_hdr_len;
11548 			}
11549 			offset += mp1->b_wptr - mp1->b_rptr;
11550 			IP_REASS_SET_END(mp1, offset);
11551 		}
11552 		/* One hole at the end. */
11553 		ipf->ipf_hole_cnt = 1;
11554 		/* Brand it as a hard case, forever. */
11555 		ipf->ipf_end = 0;
11556 	}
11557 	/* Walk through all the new pieces. */
11558 	do {
11559 		end = start + (mp->b_wptr - mp->b_rptr);
11560 		/*
11561 		 * If start is 0, decrease 'end' only for the first mblk of
11562 		 * the fragment. Otherwise 'end' can get wrong value in the
11563 		 * second pass of the loop if first mblk is exactly the
11564 		 * size of ipf_nf_hdr_len.
11565 		 */
11566 		if (start == 0 && !offset_zero_seen) {
11567 			/* First segment */
11568 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11569 			end -= ipf->ipf_nf_hdr_len;
11570 			offset_zero_seen = B_TRUE;
11571 		}
11572 		next_mp = mp->b_cont;
11573 		/*
11574 		 * We are checking to see if there is any interesing data
11575 		 * to process.  If there isn't and the mblk isn't the
11576 		 * one which carries the unfragmentable header then we
11577 		 * drop it.  It's possible to have just the unfragmentable
11578 		 * header come through without any data.  That needs to be
11579 		 * saved.
11580 		 *
11581 		 * If the assert at the top of this function holds then the
11582 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11583 		 * is infrequently traveled enough that the test is left in
11584 		 * to protect against future code changes which break that
11585 		 * invariant.
11586 		 */
11587 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11588 			/* Empty.  Blast it. */
11589 			IP_REASS_SET_START(mp, 0);
11590 			IP_REASS_SET_END(mp, 0);
11591 			/*
11592 			 * If the ipf points to the mblk we are about to free,
11593 			 * update ipf to point to the next mblk (or NULL
11594 			 * if none).
11595 			 */
11596 			if (ipf->ipf_mp->b_cont == mp)
11597 				ipf->ipf_mp->b_cont = next_mp;
11598 			freeb(mp);
11599 			continue;
11600 		}
11601 		mp->b_cont = NULL;
11602 		IP_REASS_SET_START(mp, start);
11603 		IP_REASS_SET_END(mp, end);
11604 		if (!ipf->ipf_tail_mp) {
11605 			ipf->ipf_tail_mp = mp;
11606 			ipf->ipf_mp->b_cont = mp;
11607 			if (start == 0 || !more) {
11608 				ipf->ipf_hole_cnt = 1;
11609 				/*
11610 				 * if the first fragment comes in more than one
11611 				 * mblk, this loop will be executed for each
11612 				 * mblk. Need to adjust hole count so exiting
11613 				 * this routine will leave hole count at 1.
11614 				 */
11615 				if (next_mp)
11616 					ipf->ipf_hole_cnt++;
11617 			} else
11618 				ipf->ipf_hole_cnt = 2;
11619 			continue;
11620 		} else if (ipf->ipf_last_frag_seen && !more &&
11621 		    !pkt_boundary_checked) {
11622 			/*
11623 			 * We check datagram boundary only if this fragment
11624 			 * claims to be the last fragment and we have seen a
11625 			 * last fragment in the past too. We do this only
11626 			 * once for a given fragment.
11627 			 *
11628 			 * start cannot be 0 here as fragments with start=0
11629 			 * and MF=0 gets handled as a complete packet. These
11630 			 * fragments should not reach here.
11631 			 */
11632 
11633 			if (start + msgdsize(mp) !=
11634 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11635 				/*
11636 				 * We have two fragments both of which claim
11637 				 * to be the last fragment but gives conflicting
11638 				 * information about the whole datagram size.
11639 				 * Something fishy is going on. Drop the
11640 				 * fragment and free up the reassembly list.
11641 				 */
11642 				return (IP_REASS_FAILED);
11643 			}
11644 
11645 			/*
11646 			 * We shouldn't come to this code block again for this
11647 			 * particular fragment.
11648 			 */
11649 			pkt_boundary_checked = B_TRUE;
11650 		}
11651 
11652 		/* New stuff at or beyond tail? */
11653 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11654 		if (start >= offset) {
11655 			if (ipf->ipf_last_frag_seen) {
11656 				/* current fragment is beyond last fragment */
11657 				return (IP_REASS_FAILED);
11658 			}
11659 			/* Link it on end. */
11660 			ipf->ipf_tail_mp->b_cont = mp;
11661 			ipf->ipf_tail_mp = mp;
11662 			if (more) {
11663 				if (start != offset)
11664 					ipf->ipf_hole_cnt++;
11665 			} else if (start == offset && next_mp == NULL)
11666 					ipf->ipf_hole_cnt--;
11667 			continue;
11668 		}
11669 		mp1 = ipf->ipf_mp->b_cont;
11670 		offset = IP_REASS_START(mp1);
11671 		/* New stuff at the front? */
11672 		if (start < offset) {
11673 			if (start == 0) {
11674 				if (end >= offset) {
11675 					/* Nailed the hole at the begining. */
11676 					ipf->ipf_hole_cnt--;
11677 				}
11678 			} else if (end < offset) {
11679 				/*
11680 				 * A hole, stuff, and a hole where there used
11681 				 * to be just a hole.
11682 				 */
11683 				ipf->ipf_hole_cnt++;
11684 			}
11685 			mp->b_cont = mp1;
11686 			/* Check for overlap. */
11687 			while (end > offset) {
11688 				if (end < IP_REASS_END(mp1)) {
11689 					mp->b_wptr -= end - offset;
11690 					IP_REASS_SET_END(mp, offset);
11691 					BUMP_MIB(ill->ill_ip_mib,
11692 					    ipIfStatsReasmPartDups);
11693 					break;
11694 				}
11695 				/* Did we cover another hole? */
11696 				if ((mp1->b_cont &&
11697 				    IP_REASS_END(mp1) !=
11698 				    IP_REASS_START(mp1->b_cont) &&
11699 				    end >= IP_REASS_START(mp1->b_cont)) ||
11700 				    (!ipf->ipf_last_frag_seen && !more)) {
11701 					ipf->ipf_hole_cnt--;
11702 				}
11703 				/* Clip out mp1. */
11704 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11705 					/*
11706 					 * After clipping out mp1, this guy
11707 					 * is now hanging off the end.
11708 					 */
11709 					ipf->ipf_tail_mp = mp;
11710 				}
11711 				IP_REASS_SET_START(mp1, 0);
11712 				IP_REASS_SET_END(mp1, 0);
11713 				/* Subtract byte count */
11714 				ipf->ipf_count -= mp1->b_datap->db_lim -
11715 				    mp1->b_datap->db_base;
11716 				freeb(mp1);
11717 				BUMP_MIB(ill->ill_ip_mib,
11718 				    ipIfStatsReasmPartDups);
11719 				mp1 = mp->b_cont;
11720 				if (!mp1)
11721 					break;
11722 				offset = IP_REASS_START(mp1);
11723 			}
11724 			ipf->ipf_mp->b_cont = mp;
11725 			continue;
11726 		}
11727 		/*
11728 		 * The new piece starts somewhere between the start of the head
11729 		 * and before the end of the tail.
11730 		 */
11731 		for (; mp1; mp1 = mp1->b_cont) {
11732 			offset = IP_REASS_END(mp1);
11733 			if (start < offset) {
11734 				if (end <= offset) {
11735 					/* Nothing new. */
11736 					IP_REASS_SET_START(mp, 0);
11737 					IP_REASS_SET_END(mp, 0);
11738 					/* Subtract byte count */
11739 					ipf->ipf_count -= mp->b_datap->db_lim -
11740 					    mp->b_datap->db_base;
11741 					if (incr_dups) {
11742 						ipf->ipf_num_dups++;
11743 						incr_dups = B_FALSE;
11744 					}
11745 					freeb(mp);
11746 					BUMP_MIB(ill->ill_ip_mib,
11747 					    ipIfStatsReasmDuplicates);
11748 					break;
11749 				}
11750 				/*
11751 				 * Trim redundant stuff off beginning of new
11752 				 * piece.
11753 				 */
11754 				IP_REASS_SET_START(mp, offset);
11755 				mp->b_rptr += offset - start;
11756 				BUMP_MIB(ill->ill_ip_mib,
11757 				    ipIfStatsReasmPartDups);
11758 				start = offset;
11759 				if (!mp1->b_cont) {
11760 					/*
11761 					 * After trimming, this guy is now
11762 					 * hanging off the end.
11763 					 */
11764 					mp1->b_cont = mp;
11765 					ipf->ipf_tail_mp = mp;
11766 					if (!more) {
11767 						ipf->ipf_hole_cnt--;
11768 					}
11769 					break;
11770 				}
11771 			}
11772 			if (start >= IP_REASS_START(mp1->b_cont))
11773 				continue;
11774 			/* Fill a hole */
11775 			if (start > offset)
11776 				ipf->ipf_hole_cnt++;
11777 			mp->b_cont = mp1->b_cont;
11778 			mp1->b_cont = mp;
11779 			mp1 = mp->b_cont;
11780 			offset = IP_REASS_START(mp1);
11781 			if (end >= offset) {
11782 				ipf->ipf_hole_cnt--;
11783 				/* Check for overlap. */
11784 				while (end > offset) {
11785 					if (end < IP_REASS_END(mp1)) {
11786 						mp->b_wptr -= end - offset;
11787 						IP_REASS_SET_END(mp, offset);
11788 						/*
11789 						 * TODO we might bump
11790 						 * this up twice if there is
11791 						 * overlap at both ends.
11792 						 */
11793 						BUMP_MIB(ill->ill_ip_mib,
11794 						    ipIfStatsReasmPartDups);
11795 						break;
11796 					}
11797 					/* Did we cover another hole? */
11798 					if ((mp1->b_cont &&
11799 					    IP_REASS_END(mp1)
11800 					    != IP_REASS_START(mp1->b_cont) &&
11801 					    end >=
11802 					    IP_REASS_START(mp1->b_cont)) ||
11803 					    (!ipf->ipf_last_frag_seen &&
11804 					    !more)) {
11805 						ipf->ipf_hole_cnt--;
11806 					}
11807 					/* Clip out mp1. */
11808 					if ((mp->b_cont = mp1->b_cont) ==
11809 					    NULL) {
11810 						/*
11811 						 * After clipping out mp1,
11812 						 * this guy is now hanging
11813 						 * off the end.
11814 						 */
11815 						ipf->ipf_tail_mp = mp;
11816 					}
11817 					IP_REASS_SET_START(mp1, 0);
11818 					IP_REASS_SET_END(mp1, 0);
11819 					/* Subtract byte count */
11820 					ipf->ipf_count -=
11821 					    mp1->b_datap->db_lim -
11822 					    mp1->b_datap->db_base;
11823 					freeb(mp1);
11824 					BUMP_MIB(ill->ill_ip_mib,
11825 					    ipIfStatsReasmPartDups);
11826 					mp1 = mp->b_cont;
11827 					if (!mp1)
11828 						break;
11829 					offset = IP_REASS_START(mp1);
11830 				}
11831 			}
11832 			break;
11833 		}
11834 	} while (start = end, mp = next_mp);
11835 
11836 	/* Fragment just processed could be the last one. Remember this fact */
11837 	if (!more)
11838 		ipf->ipf_last_frag_seen = B_TRUE;
11839 
11840 	/* Still got holes? */
11841 	if (ipf->ipf_hole_cnt)
11842 		return (IP_REASS_PARTIAL);
11843 	/* Clean up overloaded fields to avoid upstream disasters. */
11844 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11845 		IP_REASS_SET_START(mp1, 0);
11846 		IP_REASS_SET_END(mp1, 0);
11847 	}
11848 	return (IP_REASS_COMPLETE);
11849 }
11850 
11851 /*
11852  * ipsec processing for the fast path, used for input UDP Packets
11853  * Returns true if ready for passup to UDP.
11854  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
11855  * was an ESP-in-UDP packet, etc.).
11856  */
11857 static boolean_t
11858 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
11859     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
11860 {
11861 	uint32_t	ill_index;
11862 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
11863 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
11864 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
11865 	udp_t		*udp = connp->conn_udp;
11866 
11867 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11868 	/* The ill_index of the incoming ILL */
11869 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
11870 
11871 	/* pass packet up to the transport */
11872 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
11873 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
11874 		    NULL, mctl_present);
11875 		if (*first_mpp == NULL) {
11876 			return (B_FALSE);
11877 		}
11878 	}
11879 
11880 	/* Initiate IPPF processing for fastpath UDP */
11881 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
11882 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
11883 		if (*mpp == NULL) {
11884 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
11885 			    "deferred/dropped during IPPF processing\n"));
11886 			return (B_FALSE);
11887 		}
11888 	}
11889 	/*
11890 	 * Remove 0-spi if it's 0, or move everything behind
11891 	 * the UDP header over it and forward to ESP via
11892 	 * ip_proto_input().
11893 	 */
11894 	if (udp->udp_nat_t_endpoint) {
11895 		if (mctl_present) {
11896 			/* mctl_present *shouldn't* happen. */
11897 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
11898 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
11899 			    &ipss->ipsec_dropper);
11900 			*first_mpp = NULL;
11901 			return (B_FALSE);
11902 		}
11903 
11904 		/* "ill" is "recv_ill" in actuality. */
11905 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
11906 			return (B_FALSE);
11907 
11908 		/* Else continue like a normal UDP packet. */
11909 	}
11910 
11911 	/*
11912 	 * We make the checks as below since we are in the fast path
11913 	 * and want to minimize the number of checks if the IP_RECVIF and/or
11914 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
11915 	 */
11916 	if (connp->conn_recvif || connp->conn_recvslla ||
11917 	    connp->conn_ip_recvpktinfo) {
11918 		if (connp->conn_recvif) {
11919 			in_flags = IPF_RECVIF;
11920 		}
11921 		/*
11922 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
11923 		 * so the flag passed to ip_add_info is based on IP version
11924 		 * of connp.
11925 		 */
11926 		if (connp->conn_ip_recvpktinfo) {
11927 			if (connp->conn_af_isv6) {
11928 				/*
11929 				 * V6 only needs index
11930 				 */
11931 				in_flags |= IPF_RECVIF;
11932 			} else {
11933 				/*
11934 				 * V4 needs index + matching address.
11935 				 */
11936 				in_flags |= IPF_RECVADDR;
11937 			}
11938 		}
11939 		if (connp->conn_recvslla) {
11940 			in_flags |= IPF_RECVSLLA;
11941 		}
11942 		/*
11943 		 * since in_flags are being set ill will be
11944 		 * referenced in ip_add_info, so it better not
11945 		 * be NULL.
11946 		 */
11947 		/*
11948 		 * the actual data will be contained in b_cont
11949 		 * upon successful return of the following call.
11950 		 * If the call fails then the original mblk is
11951 		 * returned.
11952 		 */
11953 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
11954 		    ipst);
11955 	}
11956 
11957 	return (B_TRUE);
11958 }
11959 
11960 /*
11961  * Fragmentation reassembly.  Each ILL has a hash table for
11962  * queuing packets undergoing reassembly for all IPIFs
11963  * associated with the ILL.  The hash is based on the packet
11964  * IP ident field.  The ILL frag hash table was allocated
11965  * as a timer block at the time the ILL was created.  Whenever
11966  * there is anything on the reassembly queue, the timer will
11967  * be running.  Returns B_TRUE if successful else B_FALSE;
11968  * frees mp on failure.
11969  */
11970 static boolean_t
11971 ip_rput_fragment(ill_t *ill, ill_t *recv_ill, mblk_t **mpp, ipha_t *ipha,
11972     uint32_t *cksum_val, uint16_t *cksum_flags)
11973 {
11974 	uint32_t	frag_offset_flags;
11975 	mblk_t		*mp = *mpp;
11976 	mblk_t		*t_mp;
11977 	ipaddr_t	dst;
11978 	uint8_t		proto = ipha->ipha_protocol;
11979 	uint32_t	sum_val;
11980 	uint16_t	sum_flags;
11981 	ipf_t		*ipf;
11982 	ipf_t		**ipfp;
11983 	ipfb_t		*ipfb;
11984 	uint16_t	ident;
11985 	uint32_t	offset;
11986 	ipaddr_t	src;
11987 	uint_t		hdr_length;
11988 	uint32_t	end;
11989 	mblk_t		*mp1;
11990 	mblk_t		*tail_mp;
11991 	size_t		count;
11992 	size_t		msg_len;
11993 	uint8_t		ecn_info = 0;
11994 	uint32_t	packet_size;
11995 	boolean_t	pruned = B_FALSE;
11996 	ip_stack_t *ipst = ill->ill_ipst;
11997 
11998 	if (cksum_val != NULL)
11999 		*cksum_val = 0;
12000 	if (cksum_flags != NULL)
12001 		*cksum_flags = 0;
12002 
12003 	/*
12004 	 * Drop the fragmented as early as possible, if
12005 	 * we don't have resource(s) to re-assemble.
12006 	 */
12007 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12008 		freemsg(mp);
12009 		return (B_FALSE);
12010 	}
12011 
12012 	/* Check for fragmentation offset; return if there's none */
12013 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12014 	    (IPH_MF | IPH_OFFSET)) == 0)
12015 		return (B_TRUE);
12016 
12017 	/*
12018 	 * We utilize hardware computed checksum info only for UDP since
12019 	 * IP fragmentation is a normal occurrence for the protocol.  In
12020 	 * addition, checksum offload support for IP fragments carrying
12021 	 * UDP payload is commonly implemented across network adapters.
12022 	 */
12023 	ASSERT(recv_ill != NULL);
12024 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(recv_ill) &&
12025 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12026 		mblk_t *mp1 = mp->b_cont;
12027 		int32_t len;
12028 
12029 		/* Record checksum information from the packet */
12030 		sum_val = (uint32_t)DB_CKSUM16(mp);
12031 		sum_flags = DB_CKSUMFLAGS(mp);
12032 
12033 		/* IP payload offset from beginning of mblk */
12034 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12035 
12036 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12037 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12038 		    offset >= DB_CKSUMSTART(mp) &&
12039 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12040 			uint32_t adj;
12041 			/*
12042 			 * Partial checksum has been calculated by hardware
12043 			 * and attached to the packet; in addition, any
12044 			 * prepended extraneous data is even byte aligned.
12045 			 * If any such data exists, we adjust the checksum;
12046 			 * this would also handle any postpended data.
12047 			 */
12048 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12049 			    mp, mp1, len, adj);
12050 
12051 			/* One's complement subtract extraneous checksum */
12052 			if (adj >= sum_val)
12053 				sum_val = ~(adj - sum_val) & 0xFFFF;
12054 			else
12055 				sum_val -= adj;
12056 		}
12057 	} else {
12058 		sum_val = 0;
12059 		sum_flags = 0;
12060 	}
12061 
12062 	/* Clear hardware checksumming flag */
12063 	DB_CKSUMFLAGS(mp) = 0;
12064 
12065 	ident = ipha->ipha_ident;
12066 	offset = (frag_offset_flags << 3) & 0xFFFF;
12067 	src = ipha->ipha_src;
12068 	dst = ipha->ipha_dst;
12069 	hdr_length = IPH_HDR_LENGTH(ipha);
12070 	end = ntohs(ipha->ipha_length) - hdr_length;
12071 
12072 	/* If end == 0 then we have a packet with no data, so just free it */
12073 	if (end == 0) {
12074 		freemsg(mp);
12075 		return (B_FALSE);
12076 	}
12077 
12078 	/* Record the ECN field info. */
12079 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12080 	if (offset != 0) {
12081 		/*
12082 		 * If this isn't the first piece, strip the header, and
12083 		 * add the offset to the end value.
12084 		 */
12085 		mp->b_rptr += hdr_length;
12086 		end += offset;
12087 	}
12088 
12089 	msg_len = MBLKSIZE(mp);
12090 	tail_mp = mp;
12091 	while (tail_mp->b_cont != NULL) {
12092 		tail_mp = tail_mp->b_cont;
12093 		msg_len += MBLKSIZE(tail_mp);
12094 	}
12095 
12096 	/* If the reassembly list for this ILL will get too big, prune it */
12097 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12098 	    ipst->ips_ip_reass_queue_bytes) {
12099 		ill_frag_prune(ill,
12100 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12101 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12102 		pruned = B_TRUE;
12103 	}
12104 
12105 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12106 	mutex_enter(&ipfb->ipfb_lock);
12107 
12108 	ipfp = &ipfb->ipfb_ipf;
12109 	/* Try to find an existing fragment queue for this packet. */
12110 	for (;;) {
12111 		ipf = ipfp[0];
12112 		if (ipf != NULL) {
12113 			/*
12114 			 * It has to match on ident and src/dst address.
12115 			 */
12116 			if (ipf->ipf_ident == ident &&
12117 			    ipf->ipf_src == src &&
12118 			    ipf->ipf_dst == dst &&
12119 			    ipf->ipf_protocol == proto) {
12120 				/*
12121 				 * If we have received too many
12122 				 * duplicate fragments for this packet
12123 				 * free it.
12124 				 */
12125 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12126 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12127 					freemsg(mp);
12128 					mutex_exit(&ipfb->ipfb_lock);
12129 					return (B_FALSE);
12130 				}
12131 				/* Found it. */
12132 				break;
12133 			}
12134 			ipfp = &ipf->ipf_hash_next;
12135 			continue;
12136 		}
12137 
12138 		/*
12139 		 * If we pruned the list, do we want to store this new
12140 		 * fragment?. We apply an optimization here based on the
12141 		 * fact that most fragments will be received in order.
12142 		 * So if the offset of this incoming fragment is zero,
12143 		 * it is the first fragment of a new packet. We will
12144 		 * keep it.  Otherwise drop the fragment, as we have
12145 		 * probably pruned the packet already (since the
12146 		 * packet cannot be found).
12147 		 */
12148 		if (pruned && offset != 0) {
12149 			mutex_exit(&ipfb->ipfb_lock);
12150 			freemsg(mp);
12151 			return (B_FALSE);
12152 		}
12153 
12154 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12155 			/*
12156 			 * Too many fragmented packets in this hash
12157 			 * bucket. Free the oldest.
12158 			 */
12159 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12160 		}
12161 
12162 		/* New guy.  Allocate a frag message. */
12163 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12164 		if (mp1 == NULL) {
12165 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12166 			freemsg(mp);
12167 reass_done:
12168 			mutex_exit(&ipfb->ipfb_lock);
12169 			return (B_FALSE);
12170 		}
12171 
12172 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12173 		mp1->b_cont = mp;
12174 
12175 		/* Initialize the fragment header. */
12176 		ipf = (ipf_t *)mp1->b_rptr;
12177 		ipf->ipf_mp = mp1;
12178 		ipf->ipf_ptphn = ipfp;
12179 		ipfp[0] = ipf;
12180 		ipf->ipf_hash_next = NULL;
12181 		ipf->ipf_ident = ident;
12182 		ipf->ipf_protocol = proto;
12183 		ipf->ipf_src = src;
12184 		ipf->ipf_dst = dst;
12185 		ipf->ipf_nf_hdr_len = 0;
12186 		/* Record reassembly start time. */
12187 		ipf->ipf_timestamp = gethrestime_sec();
12188 		/* Record ipf generation and account for frag header */
12189 		ipf->ipf_gen = ill->ill_ipf_gen++;
12190 		ipf->ipf_count = MBLKSIZE(mp1);
12191 		ipf->ipf_last_frag_seen = B_FALSE;
12192 		ipf->ipf_ecn = ecn_info;
12193 		ipf->ipf_num_dups = 0;
12194 		ipfb->ipfb_frag_pkts++;
12195 		ipf->ipf_checksum = 0;
12196 		ipf->ipf_checksum_flags = 0;
12197 
12198 		/* Store checksum value in fragment header */
12199 		if (sum_flags != 0) {
12200 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12201 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12202 			ipf->ipf_checksum = sum_val;
12203 			ipf->ipf_checksum_flags = sum_flags;
12204 		}
12205 
12206 		/*
12207 		 * We handle reassembly two ways.  In the easy case,
12208 		 * where all the fragments show up in order, we do
12209 		 * minimal bookkeeping, and just clip new pieces on
12210 		 * the end.  If we ever see a hole, then we go off
12211 		 * to ip_reassemble which has to mark the pieces and
12212 		 * keep track of the number of holes, etc.  Obviously,
12213 		 * the point of having both mechanisms is so we can
12214 		 * handle the easy case as efficiently as possible.
12215 		 */
12216 		if (offset == 0) {
12217 			/* Easy case, in-order reassembly so far. */
12218 			ipf->ipf_count += msg_len;
12219 			ipf->ipf_tail_mp = tail_mp;
12220 			/*
12221 			 * Keep track of next expected offset in
12222 			 * ipf_end.
12223 			 */
12224 			ipf->ipf_end = end;
12225 			ipf->ipf_nf_hdr_len = hdr_length;
12226 		} else {
12227 			/* Hard case, hole at the beginning. */
12228 			ipf->ipf_tail_mp = NULL;
12229 			/*
12230 			 * ipf_end == 0 means that we have given up
12231 			 * on easy reassembly.
12232 			 */
12233 			ipf->ipf_end = 0;
12234 
12235 			/* Forget checksum offload from now on */
12236 			ipf->ipf_checksum_flags = 0;
12237 
12238 			/*
12239 			 * ipf_hole_cnt is set by ip_reassemble.
12240 			 * ipf_count is updated by ip_reassemble.
12241 			 * No need to check for return value here
12242 			 * as we don't expect reassembly to complete
12243 			 * or fail for the first fragment itself.
12244 			 */
12245 			(void) ip_reassemble(mp, ipf,
12246 			    (frag_offset_flags & IPH_OFFSET) << 3,
12247 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12248 		}
12249 		/* Update per ipfb and ill byte counts */
12250 		ipfb->ipfb_count += ipf->ipf_count;
12251 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12252 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
12253 		/* If the frag timer wasn't already going, start it. */
12254 		mutex_enter(&ill->ill_lock);
12255 		ill_frag_timer_start(ill);
12256 		mutex_exit(&ill->ill_lock);
12257 		goto reass_done;
12258 	}
12259 
12260 	/*
12261 	 * If the packet's flag has changed (it could be coming up
12262 	 * from an interface different than the previous, therefore
12263 	 * possibly different checksum capability), then forget about
12264 	 * any stored checksum states.  Otherwise add the value to
12265 	 * the existing one stored in the fragment header.
12266 	 */
12267 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12268 		sum_val += ipf->ipf_checksum;
12269 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12270 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12271 		ipf->ipf_checksum = sum_val;
12272 	} else if (ipf->ipf_checksum_flags != 0) {
12273 		/* Forget checksum offload from now on */
12274 		ipf->ipf_checksum_flags = 0;
12275 	}
12276 
12277 	/*
12278 	 * We have a new piece of a datagram which is already being
12279 	 * reassembled.  Update the ECN info if all IP fragments
12280 	 * are ECN capable.  If there is one which is not, clear
12281 	 * all the info.  If there is at least one which has CE
12282 	 * code point, IP needs to report that up to transport.
12283 	 */
12284 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12285 		if (ecn_info == IPH_ECN_CE)
12286 			ipf->ipf_ecn = IPH_ECN_CE;
12287 	} else {
12288 		ipf->ipf_ecn = IPH_ECN_NECT;
12289 	}
12290 	if (offset && ipf->ipf_end == offset) {
12291 		/* The new fragment fits at the end */
12292 		ipf->ipf_tail_mp->b_cont = mp;
12293 		/* Update the byte count */
12294 		ipf->ipf_count += msg_len;
12295 		/* Update per ipfb and ill byte counts */
12296 		ipfb->ipfb_count += msg_len;
12297 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12298 		atomic_add_32(&ill->ill_frag_count, msg_len);
12299 		if (frag_offset_flags & IPH_MF) {
12300 			/* More to come. */
12301 			ipf->ipf_end = end;
12302 			ipf->ipf_tail_mp = tail_mp;
12303 			goto reass_done;
12304 		}
12305 	} else {
12306 		/* Go do the hard cases. */
12307 		int ret;
12308 
12309 		if (offset == 0)
12310 			ipf->ipf_nf_hdr_len = hdr_length;
12311 
12312 		/* Save current byte count */
12313 		count = ipf->ipf_count;
12314 		ret = ip_reassemble(mp, ipf,
12315 		    (frag_offset_flags & IPH_OFFSET) << 3,
12316 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12317 		/* Count of bytes added and subtracted (freeb()ed) */
12318 		count = ipf->ipf_count - count;
12319 		if (count) {
12320 			/* Update per ipfb and ill byte counts */
12321 			ipfb->ipfb_count += count;
12322 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12323 			atomic_add_32(&ill->ill_frag_count, count);
12324 		}
12325 		if (ret == IP_REASS_PARTIAL) {
12326 			goto reass_done;
12327 		} else if (ret == IP_REASS_FAILED) {
12328 			/* Reassembly failed. Free up all resources */
12329 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12330 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12331 				IP_REASS_SET_START(t_mp, 0);
12332 				IP_REASS_SET_END(t_mp, 0);
12333 			}
12334 			freemsg(mp);
12335 			goto reass_done;
12336 		}
12337 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12338 	}
12339 	/*
12340 	 * We have completed reassembly.  Unhook the frag header from
12341 	 * the reassembly list.
12342 	 *
12343 	 * Before we free the frag header, record the ECN info
12344 	 * to report back to the transport.
12345 	 */
12346 	ecn_info = ipf->ipf_ecn;
12347 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12348 	ipfp = ipf->ipf_ptphn;
12349 
12350 	/* We need to supply these to caller */
12351 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12352 		sum_val = ipf->ipf_checksum;
12353 	else
12354 		sum_val = 0;
12355 
12356 	mp1 = ipf->ipf_mp;
12357 	count = ipf->ipf_count;
12358 	ipf = ipf->ipf_hash_next;
12359 	if (ipf != NULL)
12360 		ipf->ipf_ptphn = ipfp;
12361 	ipfp[0] = ipf;
12362 	atomic_add_32(&ill->ill_frag_count, -count);
12363 	ASSERT(ipfb->ipfb_count >= count);
12364 	ipfb->ipfb_count -= count;
12365 	ipfb->ipfb_frag_pkts--;
12366 	mutex_exit(&ipfb->ipfb_lock);
12367 	/* Ditch the frag header. */
12368 	mp = mp1->b_cont;
12369 
12370 	freeb(mp1);
12371 
12372 	/* Restore original IP length in header. */
12373 	packet_size = (uint32_t)msgdsize(mp);
12374 	if (packet_size > IP_MAXPACKET) {
12375 		freemsg(mp);
12376 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12377 		return (B_FALSE);
12378 	}
12379 
12380 	if (DB_REF(mp) > 1) {
12381 		mblk_t *mp2 = copymsg(mp);
12382 
12383 		freemsg(mp);
12384 		if (mp2 == NULL) {
12385 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12386 			return (B_FALSE);
12387 		}
12388 		mp = mp2;
12389 	}
12390 	ipha = (ipha_t *)mp->b_rptr;
12391 
12392 	ipha->ipha_length = htons((uint16_t)packet_size);
12393 	/* We're now complete, zip the frag state */
12394 	ipha->ipha_fragment_offset_and_flags = 0;
12395 	/* Record the ECN info. */
12396 	ipha->ipha_type_of_service &= 0xFC;
12397 	ipha->ipha_type_of_service |= ecn_info;
12398 	*mpp = mp;
12399 
12400 	/* Reassembly is successful; return checksum information if needed */
12401 	if (cksum_val != NULL)
12402 		*cksum_val = sum_val;
12403 	if (cksum_flags != NULL)
12404 		*cksum_flags = sum_flags;
12405 
12406 	return (B_TRUE);
12407 }
12408 
12409 /*
12410  * Perform ip header check sum update local options.
12411  * return B_TRUE if all is well, else return B_FALSE and release
12412  * the mp. caller is responsible for decrementing ire ref cnt.
12413  */
12414 static boolean_t
12415 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12416     ip_stack_t *ipst)
12417 {
12418 	mblk_t		*first_mp;
12419 	boolean_t	mctl_present;
12420 	uint16_t	sum;
12421 
12422 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12423 	/*
12424 	 * Don't do the checksum if it has gone through AH/ESP
12425 	 * processing.
12426 	 */
12427 	if (!mctl_present) {
12428 		sum = ip_csum_hdr(ipha);
12429 		if (sum != 0) {
12430 			if (ill != NULL) {
12431 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12432 			} else {
12433 				BUMP_MIB(&ipst->ips_ip_mib,
12434 				    ipIfStatsInCksumErrs);
12435 			}
12436 			freemsg(first_mp);
12437 			return (B_FALSE);
12438 		}
12439 	}
12440 
12441 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12442 		if (mctl_present)
12443 			freeb(first_mp);
12444 		return (B_FALSE);
12445 	}
12446 
12447 	return (B_TRUE);
12448 }
12449 
12450 /*
12451  * All udp packet are delivered to the local host via this routine.
12452  */
12453 void
12454 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12455     ill_t *recv_ill)
12456 {
12457 	uint32_t	sum;
12458 	uint32_t	u1;
12459 	boolean_t	mctl_present;
12460 	conn_t		*connp;
12461 	mblk_t		*first_mp;
12462 	uint16_t	*up;
12463 	ill_t		*ill = (ill_t *)q->q_ptr;
12464 	uint16_t	reass_hck_flags = 0;
12465 	ip_stack_t	*ipst;
12466 
12467 	ASSERT(recv_ill != NULL);
12468 	ipst = recv_ill->ill_ipst;
12469 
12470 #define	rptr    ((uchar_t *)ipha)
12471 
12472 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12473 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12474 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12475 	ASSERT(ill != NULL);
12476 
12477 	/*
12478 	 * FAST PATH for udp packets
12479 	 */
12480 
12481 	/* u1 is # words of IP options */
12482 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12483 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12484 
12485 	/* IP options present */
12486 	if (u1 != 0)
12487 		goto ipoptions;
12488 
12489 	/* Check the IP header checksum.  */
12490 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12491 		/* Clear the IP header h/w cksum flag */
12492 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12493 	} else if (!mctl_present) {
12494 		/*
12495 		 * Don't verify header checksum if this packet is coming
12496 		 * back from AH/ESP as we already did it.
12497 		 */
12498 #define	uph	((uint16_t *)ipha)
12499 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12500 		    uph[6] + uph[7] + uph[8] + uph[9];
12501 #undef	uph
12502 		/* finish doing IP checksum */
12503 		sum = (sum & 0xFFFF) + (sum >> 16);
12504 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12505 		if (sum != 0 && sum != 0xFFFF) {
12506 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12507 			freemsg(first_mp);
12508 			return;
12509 		}
12510 	}
12511 
12512 	/*
12513 	 * Count for SNMP of inbound packets for ire.
12514 	 * if mctl is present this might be a secure packet and
12515 	 * has already been counted for in ip_proto_input().
12516 	 */
12517 	if (!mctl_present) {
12518 		UPDATE_IB_PKT_COUNT(ire);
12519 		ire->ire_last_used_time = lbolt;
12520 	}
12521 
12522 	/* packet part of fragmented IP packet? */
12523 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12524 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12525 		goto fragmented;
12526 	}
12527 
12528 	/* u1 = IP header length (20 bytes) */
12529 	u1 = IP_SIMPLE_HDR_LENGTH;
12530 
12531 	/* packet does not contain complete IP & UDP headers */
12532 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12533 		goto udppullup;
12534 
12535 	/* up points to UDP header */
12536 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12537 #define	iphs    ((uint16_t *)ipha)
12538 
12539 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12540 	if (up[3] != 0) {
12541 		mblk_t *mp1 = mp->b_cont;
12542 		boolean_t cksum_err;
12543 		uint16_t hck_flags = 0;
12544 
12545 		/* Pseudo-header checksum */
12546 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12547 		    iphs[9] + up[2];
12548 
12549 		/*
12550 		 * Revert to software checksum calculation if the interface
12551 		 * isn't capable of checksum offload or if IPsec is present.
12552 		 */
12553 		if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
12554 			hck_flags = DB_CKSUMFLAGS(mp);
12555 
12556 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12557 			IP_STAT(ipst, ip_in_sw_cksum);
12558 
12559 		IP_CKSUM_RECV(hck_flags, u1,
12560 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12561 		    (int32_t)((uchar_t *)up - rptr),
12562 		    mp, mp1, cksum_err);
12563 
12564 		if (cksum_err) {
12565 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12566 			if (hck_flags & HCK_FULLCKSUM)
12567 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12568 			else if (hck_flags & HCK_PARTIALCKSUM)
12569 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12570 			else
12571 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12572 
12573 			freemsg(first_mp);
12574 			return;
12575 		}
12576 	}
12577 
12578 	/* Non-fragmented broadcast or multicast packet? */
12579 	if (ire->ire_type == IRE_BROADCAST)
12580 		goto udpslowpath;
12581 
12582 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12583 	    ire->ire_zoneid, ipst)) != NULL) {
12584 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
12585 		IP_STAT(ipst, ip_udp_fast_path);
12586 
12587 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
12588 		    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
12589 			freemsg(mp);
12590 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12591 		} else {
12592 			if (!mctl_present) {
12593 				BUMP_MIB(ill->ill_ip_mib,
12594 				    ipIfStatsHCInDelivers);
12595 			}
12596 			/*
12597 			 * mp and first_mp can change.
12598 			 */
12599 			if (ip_udp_check(q, connp, recv_ill,
12600 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12601 				/* Send it upstream */
12602 				(connp->conn_recv)(connp, mp, NULL);
12603 			}
12604 		}
12605 		/*
12606 		 * freeb() cannot deal with null mblk being passed
12607 		 * in and first_mp can be set to null in the call
12608 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12609 		 */
12610 		if (mctl_present && first_mp != NULL) {
12611 			freeb(first_mp);
12612 		}
12613 		CONN_DEC_REF(connp);
12614 		return;
12615 	}
12616 
12617 	/*
12618 	 * if we got here we know the packet is not fragmented and
12619 	 * has no options. The classifier could not find a conn_t and
12620 	 * most likely its an icmp packet so send it through slow path.
12621 	 */
12622 
12623 	goto udpslowpath;
12624 
12625 ipoptions:
12626 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12627 		goto slow_done;
12628 	}
12629 
12630 	UPDATE_IB_PKT_COUNT(ire);
12631 	ire->ire_last_used_time = lbolt;
12632 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12633 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12634 fragmented:
12635 		/*
12636 		 * "sum" and "reass_hck_flags" are non-zero if the
12637 		 * reassembled packet has a valid hardware computed
12638 		 * checksum information associated with it.
12639 		 */
12640 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, &sum,
12641 		    &reass_hck_flags)) {
12642 			goto slow_done;
12643 		}
12644 
12645 		/*
12646 		 * Make sure that first_mp points back to mp as
12647 		 * the mp we came in with could have changed in
12648 		 * ip_rput_fragment().
12649 		 */
12650 		ASSERT(!mctl_present);
12651 		ipha = (ipha_t *)mp->b_rptr;
12652 		first_mp = mp;
12653 	}
12654 
12655 	/* Now we have a complete datagram, destined for this machine. */
12656 	u1 = IPH_HDR_LENGTH(ipha);
12657 	/* Pull up the UDP header, if necessary. */
12658 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12659 udppullup:
12660 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12661 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12662 			freemsg(first_mp);
12663 			goto slow_done;
12664 		}
12665 		ipha = (ipha_t *)mp->b_rptr;
12666 	}
12667 
12668 	/*
12669 	 * Validate the checksum for the reassembled packet; for the
12670 	 * pullup case we calculate the payload checksum in software.
12671 	 */
12672 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12673 	if (up[3] != 0) {
12674 		boolean_t cksum_err;
12675 
12676 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12677 			IP_STAT(ipst, ip_in_sw_cksum);
12678 
12679 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12680 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12681 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12682 		    iphs[9] + up[2], sum, cksum_err);
12683 
12684 		if (cksum_err) {
12685 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12686 
12687 			if (reass_hck_flags & HCK_FULLCKSUM)
12688 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12689 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12690 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12691 			else
12692 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12693 
12694 			freemsg(first_mp);
12695 			goto slow_done;
12696 		}
12697 	}
12698 udpslowpath:
12699 
12700 	/* Clear hardware checksum flag to be safe */
12701 	DB_CKSUMFLAGS(mp) = 0;
12702 
12703 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12704 	    (ire->ire_type == IRE_BROADCAST),
12705 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12706 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12707 
12708 slow_done:
12709 	IP_STAT(ipst, ip_udp_slow_path);
12710 	return;
12711 
12712 #undef  iphs
12713 #undef  rptr
12714 }
12715 
12716 /* ARGSUSED */
12717 static mblk_t *
12718 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12719     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12720     ill_rx_ring_t *ill_ring)
12721 {
12722 	conn_t		*connp;
12723 	uint32_t	sum;
12724 	uint32_t	u1;
12725 	uint16_t	*up;
12726 	int		offset;
12727 	ssize_t		len;
12728 	mblk_t		*mp1;
12729 	boolean_t	syn_present = B_FALSE;
12730 	tcph_t		*tcph;
12731 	uint_t		tcph_flags;
12732 	uint_t		ip_hdr_len;
12733 	ill_t		*ill = (ill_t *)q->q_ptr;
12734 	zoneid_t	zoneid = ire->ire_zoneid;
12735 	boolean_t	cksum_err;
12736 	uint16_t	hck_flags = 0;
12737 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12738 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12739 
12740 #define	rptr	((uchar_t *)ipha)
12741 
12742 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12743 	ASSERT(ill != NULL);
12744 
12745 	/*
12746 	 * FAST PATH for tcp packets
12747 	 */
12748 
12749 	/* u1 is # words of IP options */
12750 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12751 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12752 
12753 	/* IP options present */
12754 	if (u1) {
12755 		goto ipoptions;
12756 	} else if (!mctl_present) {
12757 		/* Check the IP header checksum.  */
12758 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12759 			/* Clear the IP header h/w cksum flag */
12760 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12761 		} else if (!mctl_present) {
12762 			/*
12763 			 * Don't verify header checksum if this packet
12764 			 * is coming back from AH/ESP as we already did it.
12765 			 */
12766 #define	uph	((uint16_t *)ipha)
12767 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12768 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12769 #undef	uph
12770 			/* finish doing IP checksum */
12771 			sum = (sum & 0xFFFF) + (sum >> 16);
12772 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12773 			if (sum != 0 && sum != 0xFFFF) {
12774 				BUMP_MIB(ill->ill_ip_mib,
12775 				    ipIfStatsInCksumErrs);
12776 				goto error;
12777 			}
12778 		}
12779 	}
12780 
12781 	if (!mctl_present) {
12782 		UPDATE_IB_PKT_COUNT(ire);
12783 		ire->ire_last_used_time = lbolt;
12784 	}
12785 
12786 	/* packet part of fragmented IP packet? */
12787 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12788 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12789 		goto fragmented;
12790 	}
12791 
12792 	/* u1 = IP header length (20 bytes) */
12793 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12794 
12795 	/* does packet contain IP+TCP headers? */
12796 	len = mp->b_wptr - rptr;
12797 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12798 		IP_STAT(ipst, ip_tcppullup);
12799 		goto tcppullup;
12800 	}
12801 
12802 	/* TCP options present? */
12803 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12804 
12805 	/*
12806 	 * If options need to be pulled up, then goto tcpoptions.
12807 	 * otherwise we are still in the fast path
12808 	 */
12809 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12810 		IP_STAT(ipst, ip_tcpoptions);
12811 		goto tcpoptions;
12812 	}
12813 
12814 	/* multiple mblks of tcp data? */
12815 	if ((mp1 = mp->b_cont) != NULL) {
12816 		/* more then two? */
12817 		if (mp1->b_cont != NULL) {
12818 			IP_STAT(ipst, ip_multipkttcp);
12819 			goto multipkttcp;
12820 		}
12821 		len += mp1->b_wptr - mp1->b_rptr;
12822 	}
12823 
12824 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12825 
12826 	/* part of pseudo checksum */
12827 
12828 	/* TCP datagram length */
12829 	u1 = len - IP_SIMPLE_HDR_LENGTH;
12830 
12831 #define	iphs    ((uint16_t *)ipha)
12832 
12833 #ifdef	_BIG_ENDIAN
12834 	u1 += IPPROTO_TCP;
12835 #else
12836 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12837 #endif
12838 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12839 
12840 	/*
12841 	 * Revert to software checksum calculation if the interface
12842 	 * isn't capable of checksum offload or if IPsec is present.
12843 	 */
12844 	if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
12845 		hck_flags = DB_CKSUMFLAGS(mp);
12846 
12847 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12848 		IP_STAT(ipst, ip_in_sw_cksum);
12849 
12850 	IP_CKSUM_RECV(hck_flags, u1,
12851 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12852 	    (int32_t)((uchar_t *)up - rptr),
12853 	    mp, mp1, cksum_err);
12854 
12855 	if (cksum_err) {
12856 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
12857 
12858 		if (hck_flags & HCK_FULLCKSUM)
12859 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
12860 		else if (hck_flags & HCK_PARTIALCKSUM)
12861 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
12862 		else
12863 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
12864 
12865 		goto error;
12866 	}
12867 
12868 try_again:
12869 
12870 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
12871 	    zoneid, ipst)) == NULL) {
12872 		/* Send the TH_RST */
12873 		goto no_conn;
12874 	}
12875 
12876 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
12877 	tcph_flags = tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG);
12878 
12879 	/*
12880 	 * TCP FAST PATH for AF_INET socket.
12881 	 *
12882 	 * TCP fast path to avoid extra work. An AF_INET socket type
12883 	 * does not have facility to receive extra information via
12884 	 * ip_process or ip_add_info. Also, when the connection was
12885 	 * established, we made a check if this connection is impacted
12886 	 * by any global IPsec policy or per connection policy (a
12887 	 * policy that comes in effect later will not apply to this
12888 	 * connection). Since all this can be determined at the
12889 	 * connection establishment time, a quick check of flags
12890 	 * can avoid extra work.
12891 	 */
12892 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
12893 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12894 		ASSERT(first_mp == mp);
12895 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
12896 		if (tcph_flags != (TH_SYN | TH_ACK)) {
12897 			SET_SQUEUE(mp, tcp_rput_data, connp);
12898 			return (mp);
12899 		}
12900 		mp->b_datap->db_struioflag |= STRUIO_CONNECT;
12901 		DB_CKSUMSTART(mp) = (intptr_t)ip_squeue_get(ill_ring);
12902 		SET_SQUEUE(mp, tcp_input, connp);
12903 		return (mp);
12904 	}
12905 
12906 	if (tcph_flags == TH_SYN) {
12907 		if (IPCL_IS_TCP(connp)) {
12908 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
12909 			DB_CKSUMSTART(mp) =
12910 			    (intptr_t)ip_squeue_get(ill_ring);
12911 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
12912 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
12913 				BUMP_MIB(ill->ill_ip_mib,
12914 				    ipIfStatsHCInDelivers);
12915 				SET_SQUEUE(mp, connp->conn_recv, connp);
12916 				return (mp);
12917 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
12918 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
12919 				BUMP_MIB(ill->ill_ip_mib,
12920 				    ipIfStatsHCInDelivers);
12921 				ip_squeue_enter_unbound++;
12922 				SET_SQUEUE(mp, tcp_conn_request_unbound,
12923 				    connp);
12924 				return (mp);
12925 			}
12926 			syn_present = B_TRUE;
12927 		}
12928 	}
12929 
12930 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
12931 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12932 
12933 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
12934 		/* No need to send this packet to TCP */
12935 		if ((flags & TH_RST) || (flags & TH_URG)) {
12936 			CONN_DEC_REF(connp);
12937 			freemsg(first_mp);
12938 			return (NULL);
12939 		}
12940 		if (flags & TH_ACK) {
12941 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
12942 			    ipst->ips_netstack->netstack_tcp, connp);
12943 			CONN_DEC_REF(connp);
12944 			return (NULL);
12945 		}
12946 
12947 		CONN_DEC_REF(connp);
12948 		freemsg(first_mp);
12949 		return (NULL);
12950 	}
12951 
12952 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12953 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
12954 		    ipha, NULL, mctl_present);
12955 		if (first_mp == NULL) {
12956 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12957 			CONN_DEC_REF(connp);
12958 			return (NULL);
12959 		}
12960 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
12961 			ASSERT(syn_present);
12962 			if (mctl_present) {
12963 				ASSERT(first_mp != mp);
12964 				first_mp->b_datap->db_struioflag |=
12965 				    STRUIO_POLICY;
12966 			} else {
12967 				ASSERT(first_mp == mp);
12968 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
12969 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
12970 			}
12971 		} else {
12972 			/*
12973 			 * Discard first_mp early since we're dealing with a
12974 			 * fully-connected conn_t and tcp doesn't do policy in
12975 			 * this case.
12976 			 */
12977 			if (mctl_present) {
12978 				freeb(first_mp);
12979 				mctl_present = B_FALSE;
12980 			}
12981 			first_mp = mp;
12982 		}
12983 	}
12984 
12985 	/* Initiate IPPF processing for fastpath */
12986 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12987 		uint32_t	ill_index;
12988 
12989 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
12990 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
12991 		if (mp == NULL) {
12992 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
12993 			    "deferred/dropped during IPPF processing\n"));
12994 			CONN_DEC_REF(connp);
12995 			if (mctl_present)
12996 				freeb(first_mp);
12997 			return (NULL);
12998 		} else if (mctl_present) {
12999 			/*
13000 			 * ip_process might return a new mp.
13001 			 */
13002 			ASSERT(first_mp != mp);
13003 			first_mp->b_cont = mp;
13004 		} else {
13005 			first_mp = mp;
13006 		}
13007 
13008 	}
13009 
13010 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13011 		/*
13012 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13013 		 * make sure IPF_RECVIF is passed to ip_add_info.
13014 		 */
13015 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13016 		    IPCL_ZONEID(connp), ipst);
13017 		if (mp == NULL) {
13018 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13019 			CONN_DEC_REF(connp);
13020 			if (mctl_present)
13021 				freeb(first_mp);
13022 			return (NULL);
13023 		} else if (mctl_present) {
13024 			/*
13025 			 * ip_add_info might return a new mp.
13026 			 */
13027 			ASSERT(first_mp != mp);
13028 			first_mp->b_cont = mp;
13029 		} else {
13030 			first_mp = mp;
13031 		}
13032 	}
13033 
13034 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13035 	if (IPCL_IS_TCP(connp)) {
13036 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13037 		return (first_mp);
13038 	} else {
13039 		/* SOCK_RAW, IPPROTO_TCP case */
13040 		(connp->conn_recv)(connp, first_mp, NULL);
13041 		CONN_DEC_REF(connp);
13042 		return (NULL);
13043 	}
13044 
13045 no_conn:
13046 	/* Initiate IPPf processing, if needed. */
13047 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13048 		uint32_t ill_index;
13049 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13050 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13051 		if (first_mp == NULL) {
13052 			return (NULL);
13053 		}
13054 	}
13055 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13056 
13057 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13058 	    ipst->ips_netstack->netstack_tcp, NULL);
13059 	return (NULL);
13060 ipoptions:
13061 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13062 		goto slow_done;
13063 	}
13064 
13065 	UPDATE_IB_PKT_COUNT(ire);
13066 	ire->ire_last_used_time = lbolt;
13067 
13068 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13069 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13070 fragmented:
13071 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL)) {
13072 			if (mctl_present)
13073 				freeb(first_mp);
13074 			goto slow_done;
13075 		}
13076 		/*
13077 		 * Make sure that first_mp points back to mp as
13078 		 * the mp we came in with could have changed in
13079 		 * ip_rput_fragment().
13080 		 */
13081 		ASSERT(!mctl_present);
13082 		ipha = (ipha_t *)mp->b_rptr;
13083 		first_mp = mp;
13084 	}
13085 
13086 	/* Now we have a complete datagram, destined for this machine. */
13087 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13088 
13089 	len = mp->b_wptr - mp->b_rptr;
13090 	/* Pull up a minimal TCP header, if necessary. */
13091 	if (len < (u1 + 20)) {
13092 tcppullup:
13093 		if (!pullupmsg(mp, u1 + 20)) {
13094 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13095 			goto error;
13096 		}
13097 		ipha = (ipha_t *)mp->b_rptr;
13098 		len = mp->b_wptr - mp->b_rptr;
13099 	}
13100 
13101 	/*
13102 	 * Extract the offset field from the TCP header.  As usual, we
13103 	 * try to help the compiler more than the reader.
13104 	 */
13105 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13106 	if (offset != 5) {
13107 tcpoptions:
13108 		if (offset < 5) {
13109 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13110 			goto error;
13111 		}
13112 		/*
13113 		 * There must be TCP options.
13114 		 * Make sure we can grab them.
13115 		 */
13116 		offset <<= 2;
13117 		offset += u1;
13118 		if (len < offset) {
13119 			if (!pullupmsg(mp, offset)) {
13120 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13121 				goto error;
13122 			}
13123 			ipha = (ipha_t *)mp->b_rptr;
13124 			len = mp->b_wptr - rptr;
13125 		}
13126 	}
13127 
13128 	/* Get the total packet length in len, including headers. */
13129 	if (mp->b_cont) {
13130 multipkttcp:
13131 		len = msgdsize(mp);
13132 	}
13133 
13134 	/*
13135 	 * Check the TCP checksum by pulling together the pseudo-
13136 	 * header checksum, and passing it to ip_csum to be added in
13137 	 * with the TCP datagram.
13138 	 *
13139 	 * Since we are not using the hwcksum if available we must
13140 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13141 	 * If either of these fails along the way the mblk is freed.
13142 	 * If this logic ever changes and mblk is reused to say send
13143 	 * ICMP's back, then this flag may need to be cleared in
13144 	 * other places as well.
13145 	 */
13146 	DB_CKSUMFLAGS(mp) = 0;
13147 
13148 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13149 
13150 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13151 #ifdef	_BIG_ENDIAN
13152 	u1 += IPPROTO_TCP;
13153 #else
13154 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13155 #endif
13156 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13157 	/*
13158 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13159 	 */
13160 	IP_STAT(ipst, ip_in_sw_cksum);
13161 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13162 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13163 		goto error;
13164 	}
13165 
13166 	IP_STAT(ipst, ip_tcp_slow_path);
13167 	goto try_again;
13168 #undef  iphs
13169 #undef  rptr
13170 
13171 error:
13172 	freemsg(first_mp);
13173 slow_done:
13174 	return (NULL);
13175 }
13176 
13177 /* ARGSUSED */
13178 static void
13179 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13180     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13181 {
13182 	conn_t		*connp;
13183 	uint32_t	sum;
13184 	uint32_t	u1;
13185 	ssize_t		len;
13186 	sctp_hdr_t	*sctph;
13187 	zoneid_t	zoneid = ire->ire_zoneid;
13188 	uint32_t	pktsum;
13189 	uint32_t	calcsum;
13190 	uint32_t	ports;
13191 	in6_addr_t	map_src, map_dst;
13192 	ill_t		*ill = (ill_t *)q->q_ptr;
13193 	ip_stack_t	*ipst;
13194 	sctp_stack_t	*sctps;
13195 	boolean_t	sctp_csum_err = B_FALSE;
13196 
13197 	ASSERT(recv_ill != NULL);
13198 	ipst = recv_ill->ill_ipst;
13199 	sctps = ipst->ips_netstack->netstack_sctp;
13200 
13201 #define	rptr	((uchar_t *)ipha)
13202 
13203 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13204 	ASSERT(ill != NULL);
13205 
13206 	/* u1 is # words of IP options */
13207 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13208 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13209 
13210 	/* IP options present */
13211 	if (u1 > 0) {
13212 		goto ipoptions;
13213 	} else {
13214 		/* Check the IP header checksum.  */
13215 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill) &&
13216 		    !mctl_present) {
13217 #define	uph	((uint16_t *)ipha)
13218 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13219 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13220 #undef	uph
13221 			/* finish doing IP checksum */
13222 			sum = (sum & 0xFFFF) + (sum >> 16);
13223 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13224 			/*
13225 			 * Don't verify header checksum if this packet
13226 			 * is coming back from AH/ESP as we already did it.
13227 			 */
13228 			if (sum != 0 && sum != 0xFFFF) {
13229 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13230 				goto error;
13231 			}
13232 		}
13233 		/*
13234 		 * Since there is no SCTP h/w cksum support yet, just
13235 		 * clear the flag.
13236 		 */
13237 		DB_CKSUMFLAGS(mp) = 0;
13238 	}
13239 
13240 	/*
13241 	 * Don't verify header checksum if this packet is coming
13242 	 * back from AH/ESP as we already did it.
13243 	 */
13244 	if (!mctl_present) {
13245 		UPDATE_IB_PKT_COUNT(ire);
13246 		ire->ire_last_used_time = lbolt;
13247 	}
13248 
13249 	/* packet part of fragmented IP packet? */
13250 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13251 	if (u1 & (IPH_MF | IPH_OFFSET))
13252 		goto fragmented;
13253 
13254 	/* u1 = IP header length (20 bytes) */
13255 	u1 = IP_SIMPLE_HDR_LENGTH;
13256 
13257 find_sctp_client:
13258 	/* Pullup if we don't have the sctp common header. */
13259 	len = MBLKL(mp);
13260 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13261 		if (mp->b_cont == NULL ||
13262 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13263 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13264 			goto error;
13265 		}
13266 		ipha = (ipha_t *)mp->b_rptr;
13267 		len = MBLKL(mp);
13268 	}
13269 
13270 	sctph = (sctp_hdr_t *)(rptr + u1);
13271 #ifdef	DEBUG
13272 	if (!skip_sctp_cksum) {
13273 #endif
13274 		pktsum = sctph->sh_chksum;
13275 		sctph->sh_chksum = 0;
13276 		calcsum = sctp_cksum(mp, u1);
13277 		sctph->sh_chksum = pktsum;
13278 		if (calcsum != pktsum)
13279 			sctp_csum_err = B_TRUE;
13280 #ifdef	DEBUG	/* skip_sctp_cksum */
13281 	}
13282 #endif
13283 	/* get the ports */
13284 	ports = *(uint32_t *)&sctph->sh_sport;
13285 
13286 	IRE_REFRELE(ire);
13287 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13288 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13289 	if (sctp_csum_err) {
13290 		/*
13291 		 * No potential sctp checksum errors go to the Sun
13292 		 * sctp stack however they might be Adler-32 summed
13293 		 * packets a userland stack bound to a raw IP socket
13294 		 * could reasonably use. Note though that Adler-32 is
13295 		 * a long deprecated algorithm and customer sctp
13296 		 * networks should eventually migrate to CRC-32 at
13297 		 * which time this facility should be removed.
13298 		 */
13299 		flags |= IP_FF_SCTP_CSUM_ERR;
13300 		goto no_conn;
13301 	}
13302 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13303 	    sctps)) == NULL) {
13304 		/* Check for raw socket or OOTB handling */
13305 		goto no_conn;
13306 	}
13307 
13308 	/* Found a client; up it goes */
13309 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13310 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13311 	return;
13312 
13313 no_conn:
13314 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13315 	    ports, mctl_present, flags, B_TRUE, zoneid);
13316 	return;
13317 
13318 ipoptions:
13319 	DB_CKSUMFLAGS(mp) = 0;
13320 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13321 		goto slow_done;
13322 
13323 	UPDATE_IB_PKT_COUNT(ire);
13324 	ire->ire_last_used_time = lbolt;
13325 
13326 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13327 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13328 fragmented:
13329 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
13330 			goto slow_done;
13331 		/*
13332 		 * Make sure that first_mp points back to mp as
13333 		 * the mp we came in with could have changed in
13334 		 * ip_rput_fragment().
13335 		 */
13336 		ASSERT(!mctl_present);
13337 		ipha = (ipha_t *)mp->b_rptr;
13338 		first_mp = mp;
13339 	}
13340 
13341 	/* Now we have a complete datagram, destined for this machine. */
13342 	u1 = IPH_HDR_LENGTH(ipha);
13343 	goto find_sctp_client;
13344 #undef  iphs
13345 #undef  rptr
13346 
13347 error:
13348 	freemsg(first_mp);
13349 slow_done:
13350 	IRE_REFRELE(ire);
13351 }
13352 
13353 #define	VER_BITS	0xF0
13354 #define	VERSION_6	0x60
13355 
13356 static boolean_t
13357 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13358     ipaddr_t *dstp, ip_stack_t *ipst)
13359 {
13360 	uint_t	opt_len;
13361 	ipha_t *ipha;
13362 	ssize_t len;
13363 	uint_t	pkt_len;
13364 
13365 	ASSERT(ill != NULL);
13366 	IP_STAT(ipst, ip_ipoptions);
13367 	ipha = *iphapp;
13368 
13369 #define	rptr    ((uchar_t *)ipha)
13370 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13371 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13372 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13373 		freemsg(mp);
13374 		return (B_FALSE);
13375 	}
13376 
13377 	/* multiple mblk or too short */
13378 	pkt_len = ntohs(ipha->ipha_length);
13379 
13380 	/* Get the number of words of IP options in the IP header. */
13381 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13382 	if (opt_len) {
13383 		/* IP Options present!  Validate and process. */
13384 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13385 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13386 			goto done;
13387 		}
13388 		/*
13389 		 * Recompute complete header length and make sure we
13390 		 * have access to all of it.
13391 		 */
13392 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13393 		if (len > (mp->b_wptr - rptr)) {
13394 			if (len > pkt_len) {
13395 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13396 				goto done;
13397 			}
13398 			if (!pullupmsg(mp, len)) {
13399 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13400 				goto done;
13401 			}
13402 			ipha = (ipha_t *)mp->b_rptr;
13403 		}
13404 		/*
13405 		 * Go off to ip_rput_options which returns the next hop
13406 		 * destination address, which may have been affected
13407 		 * by source routing.
13408 		 */
13409 		IP_STAT(ipst, ip_opt);
13410 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13411 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13412 			return (B_FALSE);
13413 		}
13414 	}
13415 	*iphapp = ipha;
13416 	return (B_TRUE);
13417 done:
13418 	/* clear b_prev - used by ip_mroute_decap */
13419 	mp->b_prev = NULL;
13420 	freemsg(mp);
13421 	return (B_FALSE);
13422 #undef  rptr
13423 }
13424 
13425 /*
13426  * Deal with the fact that there is no ire for the destination.
13427  */
13428 static ire_t *
13429 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13430 {
13431 	ipha_t	*ipha;
13432 	ill_t	*ill;
13433 	ire_t	*ire;
13434 	ip_stack_t *ipst;
13435 	enum	ire_forward_action ret_action;
13436 
13437 	ipha = (ipha_t *)mp->b_rptr;
13438 	ill = (ill_t *)q->q_ptr;
13439 
13440 	ASSERT(ill != NULL);
13441 	ipst = ill->ill_ipst;
13442 
13443 	/*
13444 	 * No IRE for this destination, so it can't be for us.
13445 	 * Unless we are forwarding, drop the packet.
13446 	 * We have to let source routed packets through
13447 	 * since we don't yet know if they are 'ping -l'
13448 	 * packets i.e. if they will go out over the
13449 	 * same interface as they came in on.
13450 	 */
13451 	if (ll_multicast) {
13452 		freemsg(mp);
13453 		return (NULL);
13454 	}
13455 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13456 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13457 		freemsg(mp);
13458 		return (NULL);
13459 	}
13460 
13461 	/*
13462 	 * Mark this packet as having originated externally.
13463 	 *
13464 	 * For non-forwarding code path, ire_send later double
13465 	 * checks this interface to see if it is still exists
13466 	 * post-ARP resolution.
13467 	 *
13468 	 * Also, IPQOS uses this to differentiate between
13469 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13470 	 * QOS packet processing in ip_wput_attach_llhdr().
13471 	 * The QoS module can mark the b_band for a fastpath message
13472 	 * or the dl_priority field in a unitdata_req header for
13473 	 * CoS marking. This info can only be found in
13474 	 * ip_wput_attach_llhdr().
13475 	 */
13476 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13477 	/*
13478 	 * Clear the indication that this may have a hardware checksum
13479 	 * as we are not using it
13480 	 */
13481 	DB_CKSUMFLAGS(mp) = 0;
13482 
13483 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13484 	    MBLK_GETLABEL(mp), ipst);
13485 
13486 	if (ire == NULL && ret_action == Forward_check_multirt) {
13487 		/* Let ip_newroute handle CGTP  */
13488 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13489 		return (NULL);
13490 	}
13491 
13492 	if (ire != NULL)
13493 		return (ire);
13494 
13495 	mp->b_prev = mp->b_next = 0;
13496 
13497 	if (ret_action == Forward_blackhole) {
13498 		freemsg(mp);
13499 		return (NULL);
13500 	}
13501 	/* send icmp unreachable */
13502 	q = WR(q);
13503 	/* Sent by forwarding path, and router is global zone */
13504 	if (ip_source_routed(ipha, ipst)) {
13505 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13506 		    GLOBAL_ZONEID, ipst);
13507 	} else {
13508 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13509 		    ipst);
13510 	}
13511 
13512 	return (NULL);
13513 
13514 }
13515 
13516 /*
13517  * check ip header length and align it.
13518  */
13519 static boolean_t
13520 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13521 {
13522 	ssize_t len;
13523 	ill_t *ill;
13524 	ipha_t	*ipha;
13525 
13526 	len = MBLKL(mp);
13527 
13528 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13529 		ill = (ill_t *)q->q_ptr;
13530 
13531 		if (!OK_32PTR(mp->b_rptr))
13532 			IP_STAT(ipst, ip_notaligned1);
13533 		else
13534 			IP_STAT(ipst, ip_notaligned2);
13535 		/* Guard against bogus device drivers */
13536 		if (len < 0) {
13537 			/* clear b_prev - used by ip_mroute_decap */
13538 			mp->b_prev = NULL;
13539 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13540 			freemsg(mp);
13541 			return (B_FALSE);
13542 		}
13543 
13544 		if (ip_rput_pullups++ == 0) {
13545 			ipha = (ipha_t *)mp->b_rptr;
13546 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13547 			    "ip_check_and_align_header: %s forced us to "
13548 			    " pullup pkt, hdr len %ld, hdr addr %p",
13549 			    ill->ill_name, len, (void *)ipha);
13550 		}
13551 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13552 			/* clear b_prev - used by ip_mroute_decap */
13553 			mp->b_prev = NULL;
13554 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13555 			freemsg(mp);
13556 			return (B_FALSE);
13557 		}
13558 	}
13559 	return (B_TRUE);
13560 }
13561 
13562 /*
13563  * Handle the situation where a packet came in on `ill' but matched an IRE
13564  * whose ire_rfq doesn't match `ill'.  We return the IRE that should be used
13565  * for interface statistics.
13566  */
13567 ire_t *
13568 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13569 {
13570 	ire_t		*new_ire;
13571 	ill_t		*ire_ill;
13572 	uint_t		ifindex;
13573 	ip_stack_t	*ipst = ill->ill_ipst;
13574 	boolean_t	strict_check = B_FALSE;
13575 
13576 	/*
13577 	 * IPMP common case: if IRE and ILL are in the same group, there's no
13578 	 * issue (e.g. packet received on an underlying interface matched an
13579 	 * IRE_LOCAL on its associated group interface).
13580 	 */
13581 	if (ire->ire_rfq != NULL &&
13582 	    IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr)) {
13583 		return (ire);
13584 	}
13585 
13586 	/*
13587 	 * Do another ire lookup here, using the ingress ill, to see if the
13588 	 * interface is in a usesrc group.
13589 	 * As long as the ills belong to the same group, we don't consider
13590 	 * them to be arriving on the wrong interface. Thus, if the switch
13591 	 * is doing inbound load spreading, we won't drop packets when the
13592 	 * ip*_strict_dst_multihoming switch is on.
13593 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13594 	 * where the local address may not be unique. In this case we were
13595 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13596 	 * actually returned. The new lookup, which is more specific, should
13597 	 * only find the IRE_LOCAL associated with the ingress ill if one
13598 	 * exists.
13599 	 */
13600 
13601 	if (ire->ire_ipversion == IPV4_VERSION) {
13602 		if (ipst->ips_ip_strict_dst_multihoming)
13603 			strict_check = B_TRUE;
13604 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13605 		    ill->ill_ipif, ALL_ZONES, NULL,
13606 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13607 	} else {
13608 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13609 		if (ipst->ips_ipv6_strict_dst_multihoming)
13610 			strict_check = B_TRUE;
13611 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13612 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13613 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13614 	}
13615 	/*
13616 	 * If the same ire that was returned in ip_input() is found then this
13617 	 * is an indication that usesrc groups are in use. The packet
13618 	 * arrived on a different ill in the group than the one associated with
13619 	 * the destination address.  If a different ire was found then the same
13620 	 * IP address must be hosted on multiple ills. This is possible with
13621 	 * unnumbered point2point interfaces. We switch to use this new ire in
13622 	 * order to have accurate interface statistics.
13623 	 */
13624 	if (new_ire != NULL) {
13625 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13626 			ire_refrele(ire);
13627 			ire = new_ire;
13628 		} else {
13629 			ire_refrele(new_ire);
13630 		}
13631 		return (ire);
13632 	} else if ((ire->ire_rfq == NULL) &&
13633 	    (ire->ire_ipversion == IPV4_VERSION)) {
13634 		/*
13635 		 * The best match could have been the original ire which
13636 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13637 		 * the strict multihoming checks are irrelevant as we consider
13638 		 * local addresses hosted on lo0 to be interface agnostic. We
13639 		 * only expect a null ire_rfq on IREs which are associated with
13640 		 * lo0 hence we can return now.
13641 		 */
13642 		return (ire);
13643 	}
13644 
13645 	/*
13646 	 * Chase pointers once and store locally.
13647 	 */
13648 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13649 	    (ill_t *)(ire->ire_rfq->q_ptr);
13650 	ifindex = ill->ill_usesrc_ifindex;
13651 
13652 	/*
13653 	 * Check if it's a legal address on the 'usesrc' interface.
13654 	 */
13655 	if ((ifindex != 0) && (ire_ill != NULL) &&
13656 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13657 		return (ire);
13658 	}
13659 
13660 	/*
13661 	 * If the ip*_strict_dst_multihoming switch is on then we can
13662 	 * only accept this packet if the interface is marked as routing.
13663 	 */
13664 	if (!(strict_check))
13665 		return (ire);
13666 
13667 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13668 	    ILLF_ROUTER) != 0) {
13669 		return (ire);
13670 	}
13671 
13672 	ire_refrele(ire);
13673 	return (NULL);
13674 }
13675 
13676 /*
13677  *
13678  * This is the fast forward path. If we are here, we dont need to
13679  * worry about RSVP, CGTP, or TSol. Furthermore the ftable lookup
13680  * needed to find the nexthop in this case is much simpler
13681  */
13682 ire_t *
13683 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13684 {
13685 	ipha_t	*ipha;
13686 	ire_t	*src_ire;
13687 	ill_t	*stq_ill;
13688 	uint_t	hlen;
13689 	uint_t	pkt_len;
13690 	uint32_t sum;
13691 	queue_t	*dev_q;
13692 	ip_stack_t *ipst = ill->ill_ipst;
13693 	mblk_t *fpmp;
13694 	enum	ire_forward_action ret_action;
13695 
13696 	ipha = (ipha_t *)mp->b_rptr;
13697 
13698 	if (ire != NULL &&
13699 	    ire->ire_zoneid != GLOBAL_ZONEID &&
13700 	    ire->ire_zoneid != ALL_ZONES) {
13701 		/*
13702 		 * Should only use IREs that are visible to the global
13703 		 * zone for forwarding.
13704 		 */
13705 		ire_refrele(ire);
13706 		ire = ire_cache_lookup(dst, GLOBAL_ZONEID, NULL, ipst);
13707 		/*
13708 		 * ire_cache_lookup() can return ire of IRE_LOCAL in
13709 		 * transient cases. In such case, just drop the packet
13710 		 */
13711 		if (ire->ire_type != IRE_CACHE)
13712 			goto drop;
13713 	}
13714 
13715 	/*
13716 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13717 	 * The loopback address check for both src and dst has already
13718 	 * been checked in ip_input
13719 	 */
13720 
13721 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13722 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13723 		goto drop;
13724 	}
13725 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13726 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13727 
13728 	if (src_ire != NULL) {
13729 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13730 		ire_refrele(src_ire);
13731 		goto drop;
13732 	}
13733 
13734 	/* No ire cache of nexthop. So first create one  */
13735 	if (ire == NULL) {
13736 
13737 		ire = ire_forward_simple(dst, &ret_action, ipst);
13738 
13739 		/*
13740 		 * We only come to ip_fast_forward if ip_cgtp_filter
13741 		 * is not set. So ire_forward() should not return with
13742 		 * Forward_check_multirt as the next action.
13743 		 */
13744 		ASSERT(ret_action != Forward_check_multirt);
13745 		if (ire == NULL) {
13746 			/* An attempt was made to forward the packet */
13747 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13748 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13749 			mp->b_prev = mp->b_next = 0;
13750 			/* send icmp unreachable */
13751 			/* Sent by forwarding path, and router is global zone */
13752 			if (ret_action == Forward_ret_icmp_err) {
13753 				if (ip_source_routed(ipha, ipst)) {
13754 					icmp_unreachable(ill->ill_wq, mp,
13755 					    ICMP_SOURCE_ROUTE_FAILED,
13756 					    GLOBAL_ZONEID, ipst);
13757 				} else {
13758 					icmp_unreachable(ill->ill_wq, mp,
13759 					    ICMP_HOST_UNREACHABLE,
13760 					    GLOBAL_ZONEID, ipst);
13761 				}
13762 			} else {
13763 				freemsg(mp);
13764 			}
13765 			return (NULL);
13766 		}
13767 	}
13768 
13769 	/*
13770 	 * Forwarding fastpath exception case:
13771 	 * If any of the following are true, we take the slowpath:
13772 	 *	o forwarding is not enabled
13773 	 *	o incoming and outgoing interface are the same, or in the same
13774 	 *	  IPMP group.
13775 	 *	o corresponding ire is in incomplete state
13776 	 *	o packet needs fragmentation
13777 	 *	o ARP cache is not resolved
13778 	 *
13779 	 * The codeflow from here on is thus:
13780 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13781 	 */
13782 	pkt_len = ntohs(ipha->ipha_length);
13783 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13784 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13785 	    (ill == stq_ill) || IS_IN_SAME_ILLGRP(ill, stq_ill) ||
13786 	    (ire->ire_nce == NULL) ||
13787 	    (pkt_len > ire->ire_max_frag) ||
13788 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
13789 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
13790 	    ipha->ipha_ttl <= 1) {
13791 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13792 		    ipha, ill, B_FALSE, B_TRUE);
13793 		return (ire);
13794 	}
13795 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13796 
13797 	DTRACE_PROBE4(ip4__forwarding__start,
13798 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13799 
13800 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13801 	    ipst->ips_ipv4firewall_forwarding,
13802 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
13803 
13804 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13805 
13806 	if (mp == NULL)
13807 		goto drop;
13808 
13809 	mp->b_datap->db_struioun.cksum.flags = 0;
13810 	/* Adjust the checksum to reflect the ttl decrement. */
13811 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13812 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13813 	ipha->ipha_ttl--;
13814 
13815 	/*
13816 	 * Write the link layer header.  We can do this safely here,
13817 	 * because we have already tested to make sure that the IP
13818 	 * policy is not set, and that we have a fast path destination
13819 	 * header.
13820 	 */
13821 	mp->b_rptr -= hlen;
13822 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
13823 
13824 	UPDATE_IB_PKT_COUNT(ire);
13825 	ire->ire_last_used_time = lbolt;
13826 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
13827 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
13828 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
13829 
13830 	if (!ILL_DIRECT_CAPABLE(stq_ill) || DB_TYPE(mp) != M_DATA) {
13831 		dev_q = ire->ire_stq->q_next;
13832 		if (DEV_Q_FLOW_BLOCKED(dev_q))
13833 			goto indiscard;
13834 	}
13835 
13836 	DTRACE_PROBE4(ip4__physical__out__start,
13837 	    ill_t *, NULL, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13838 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
13839 	    ipst->ips_ipv4firewall_physical_out,
13840 	    NULL, stq_ill, ipha, mp, mp, 0, ipst);
13841 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
13842 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,
13843 	    ipha, __dtrace_ipsr_ill_t *, stq_ill, ipha_t *, ipha,
13844 	    ip6_t *, NULL, int, 0);
13845 
13846 	if (mp != NULL) {
13847 		if (ipst->ips_ipobs_enabled) {
13848 			zoneid_t szone;
13849 
13850 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
13851 			    ipst, ALL_ZONES);
13852 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
13853 			    ALL_ZONES, ill, IPV4_VERSION, hlen, ipst);
13854 		}
13855 
13856 		ILL_SEND_TX(stq_ill, ire, dst, mp, IP_DROP_ON_NO_DESC);
13857 	}
13858 	return (ire);
13859 
13860 indiscard:
13861 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13862 drop:
13863 	if (mp != NULL)
13864 		freemsg(mp);
13865 	return (ire);
13866 
13867 }
13868 
13869 /*
13870  * This function is called in the forwarding slowpath, when
13871  * either the ire lacks the link-layer address, or the packet needs
13872  * further processing(eg. fragmentation), before transmission.
13873  */
13874 
13875 static void
13876 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13877     ill_t *ill, boolean_t ll_multicast, boolean_t from_ip_fast_forward)
13878 {
13879 	queue_t		*dev_q;
13880 	ire_t		*src_ire;
13881 	ip_stack_t	*ipst = ill->ill_ipst;
13882 	boolean_t	same_illgrp = B_FALSE;
13883 
13884 	ASSERT(ire->ire_stq != NULL);
13885 
13886 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
13887 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
13888 
13889 	/*
13890 	 * If the caller of this function is ip_fast_forward() skip the
13891 	 * next three checks as it does not apply.
13892 	 */
13893 	if (from_ip_fast_forward)
13894 		goto skip;
13895 
13896 	if (ll_multicast != 0) {
13897 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13898 		goto drop_pkt;
13899 	}
13900 
13901 	/*
13902 	 * check if ipha_src is a broadcast address. Note that this
13903 	 * check is redundant when we get here from ip_fast_forward()
13904 	 * which has already done this check. However, since we can
13905 	 * also get here from ip_rput_process_broadcast() or, for
13906 	 * for the slow path through ip_fast_forward(), we perform
13907 	 * the check again for code-reusability
13908 	 */
13909 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13910 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13911 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
13912 		if (src_ire != NULL)
13913 			ire_refrele(src_ire);
13914 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13915 		ip2dbg(("ip_rput_process_forward: Received packet with"
13916 		    " bad src/dst address on %s\n", ill->ill_name));
13917 		goto drop_pkt;
13918 	}
13919 
13920 	/*
13921 	 * Check if we want to forward this one at this time.
13922 	 * We allow source routed packets on a host provided that
13923 	 * they go out the same ill or illgrp as they came in on.
13924 	 *
13925 	 * XXX To be quicker, we may wish to not chase pointers to
13926 	 * get the ILLF_ROUTER flag and instead store the
13927 	 * forwarding policy in the ire.  An unfortunate
13928 	 * side-effect of that would be requiring an ire flush
13929 	 * whenever the ILLF_ROUTER flag changes.
13930 	 */
13931 skip:
13932 	same_illgrp = IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr);
13933 
13934 	if (((ill->ill_flags &
13935 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags & ILLF_ROUTER) == 0) &&
13936 	    !(ip_source_routed(ipha, ipst) &&
13937 	    (ire->ire_rfq == q || same_illgrp))) {
13938 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13939 		if (ip_source_routed(ipha, ipst)) {
13940 			q = WR(q);
13941 			/*
13942 			 * Clear the indication that this may have
13943 			 * hardware checksum as we are not using it.
13944 			 */
13945 			DB_CKSUMFLAGS(mp) = 0;
13946 			/* Sent by forwarding path, and router is global zone */
13947 			icmp_unreachable(q, mp,
13948 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
13949 			return;
13950 		}
13951 		goto drop_pkt;
13952 	}
13953 
13954 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13955 
13956 	/* Packet is being forwarded. Turning off hwcksum flag. */
13957 	DB_CKSUMFLAGS(mp) = 0;
13958 	if (ipst->ips_ip_g_send_redirects) {
13959 		/*
13960 		 * Check whether the incoming interface and outgoing
13961 		 * interface is part of the same group. If so,
13962 		 * send redirects.
13963 		 *
13964 		 * Check the source address to see if it originated
13965 		 * on the same logical subnet it is going back out on.
13966 		 * If so, we should be able to send it a redirect.
13967 		 * Avoid sending a redirect if the destination
13968 		 * is directly connected (i.e., ipha_dst is the same
13969 		 * as ire_gateway_addr or the ire_addr of the
13970 		 * nexthop IRE_CACHE ), or if the packet was source
13971 		 * routed out this interface.
13972 		 */
13973 		ipaddr_t src, nhop;
13974 		mblk_t	*mp1;
13975 		ire_t	*nhop_ire = NULL;
13976 
13977 		/*
13978 		 * Check whether ire_rfq and q are from the same ill or illgrp.
13979 		 * If so, send redirects.
13980 		 */
13981 		if ((ire->ire_rfq == q || same_illgrp) &&
13982 		    !ip_source_routed(ipha, ipst)) {
13983 
13984 			nhop = (ire->ire_gateway_addr != 0 ?
13985 			    ire->ire_gateway_addr : ire->ire_addr);
13986 
13987 			if (ipha->ipha_dst == nhop) {
13988 				/*
13989 				 * We avoid sending a redirect if the
13990 				 * destination is directly connected
13991 				 * because it is possible that multiple
13992 				 * IP subnets may have been configured on
13993 				 * the link, and the source may not
13994 				 * be on the same subnet as ip destination,
13995 				 * even though they are on the same
13996 				 * physical link.
13997 				 */
13998 				goto sendit;
13999 			}
14000 
14001 			src = ipha->ipha_src;
14002 
14003 			/*
14004 			 * We look up the interface ire for the nexthop,
14005 			 * to see if ipha_src is in the same subnet
14006 			 * as the nexthop.
14007 			 *
14008 			 * Note that, if, in the future, IRE_CACHE entries
14009 			 * are obsoleted,  this lookup will not be needed,
14010 			 * as the ire passed to this function will be the
14011 			 * same as the nhop_ire computed below.
14012 			 */
14013 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14014 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14015 			    0, NULL, MATCH_IRE_TYPE, ipst);
14016 
14017 			if (nhop_ire != NULL) {
14018 				if ((src & nhop_ire->ire_mask) ==
14019 				    (nhop & nhop_ire->ire_mask)) {
14020 					/*
14021 					 * The source is directly connected.
14022 					 * Just copy the ip header (which is
14023 					 * in the first mblk)
14024 					 */
14025 					mp1 = copyb(mp);
14026 					if (mp1 != NULL) {
14027 						icmp_send_redirect(WR(q), mp1,
14028 						    nhop, ipst);
14029 					}
14030 				}
14031 				ire_refrele(nhop_ire);
14032 			}
14033 		}
14034 	}
14035 sendit:
14036 	dev_q = ire->ire_stq->q_next;
14037 	if (DEV_Q_FLOW_BLOCKED(dev_q)) {
14038 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14039 		freemsg(mp);
14040 		return;
14041 	}
14042 
14043 	ip_rput_forward(ire, ipha, mp, ill);
14044 	return;
14045 
14046 drop_pkt:
14047 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14048 	freemsg(mp);
14049 }
14050 
14051 ire_t *
14052 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14053     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14054 {
14055 	queue_t		*q;
14056 	uint16_t	hcksumflags;
14057 	ip_stack_t	*ipst = ill->ill_ipst;
14058 
14059 	q = *qp;
14060 
14061 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14062 
14063 	/*
14064 	 * Clear the indication that this may have hardware
14065 	 * checksum as we are not using it for forwarding.
14066 	 */
14067 	hcksumflags = DB_CKSUMFLAGS(mp);
14068 	DB_CKSUMFLAGS(mp) = 0;
14069 
14070 	/*
14071 	 * Directed broadcast forwarding: if the packet came in over a
14072 	 * different interface then it is routed out over we can forward it.
14073 	 */
14074 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14075 		ire_refrele(ire);
14076 		freemsg(mp);
14077 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14078 		return (NULL);
14079 	}
14080 	/*
14081 	 * For multicast we have set dst to be INADDR_BROADCAST
14082 	 * for delivering to all STREAMS.
14083 	 */
14084 	if (!CLASSD(ipha->ipha_dst)) {
14085 		ire_t *new_ire;
14086 		ipif_t *ipif;
14087 
14088 		ipif = ipif_get_next_ipif(NULL, ill);
14089 		if (ipif == NULL) {
14090 discard:		ire_refrele(ire);
14091 			freemsg(mp);
14092 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14093 			return (NULL);
14094 		}
14095 		new_ire = ire_ctable_lookup(dst, 0, 0,
14096 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14097 		ipif_refrele(ipif);
14098 
14099 		if (new_ire != NULL) {
14100 			/*
14101 			 * If the matching IRE_BROADCAST is part of an IPMP
14102 			 * group, then drop the packet unless our ill has been
14103 			 * nominated to receive for the group.
14104 			 */
14105 			if (IS_IPMP(new_ire->ire_ipif->ipif_ill) &&
14106 			    new_ire->ire_rfq != q) {
14107 				ire_refrele(new_ire);
14108 				goto discard;
14109 			}
14110 
14111 			/*
14112 			 * In the special case of multirouted broadcast
14113 			 * packets, we unconditionally need to "gateway"
14114 			 * them to the appropriate interface here.
14115 			 * In the normal case, this cannot happen, because
14116 			 * there is no broadcast IRE tagged with the
14117 			 * RTF_MULTIRT flag.
14118 			 */
14119 			if (new_ire->ire_flags & RTF_MULTIRT) {
14120 				ire_refrele(new_ire);
14121 				if (ire->ire_rfq != NULL) {
14122 					q = ire->ire_rfq;
14123 					*qp = q;
14124 				}
14125 			} else {
14126 				ire_refrele(ire);
14127 				ire = new_ire;
14128 			}
14129 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14130 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14131 				/*
14132 				 * Free the message if
14133 				 * ip_g_forward_directed_bcast is turned
14134 				 * off for non-local broadcast.
14135 				 */
14136 				ire_refrele(ire);
14137 				freemsg(mp);
14138 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14139 				return (NULL);
14140 			}
14141 		} else {
14142 			/*
14143 			 * This CGTP packet successfully passed the
14144 			 * CGTP filter, but the related CGTP
14145 			 * broadcast IRE has not been found,
14146 			 * meaning that the redundant ipif is
14147 			 * probably down. However, if we discarded
14148 			 * this packet, its duplicate would be
14149 			 * filtered out by the CGTP filter so none
14150 			 * of them would get through. So we keep
14151 			 * going with this one.
14152 			 */
14153 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14154 			if (ire->ire_rfq != NULL) {
14155 				q = ire->ire_rfq;
14156 				*qp = q;
14157 			}
14158 		}
14159 	}
14160 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14161 		/*
14162 		 * Verify that there are not more then one
14163 		 * IRE_BROADCAST with this broadcast address which
14164 		 * has ire_stq set.
14165 		 * TODO: simplify, loop over all IRE's
14166 		 */
14167 		ire_t	*ire1;
14168 		int	num_stq = 0;
14169 		mblk_t	*mp1;
14170 
14171 		/* Find the first one with ire_stq set */
14172 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14173 		for (ire1 = ire; ire1 &&
14174 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14175 		    ire1 = ire1->ire_next)
14176 			;
14177 		if (ire1) {
14178 			ire_refrele(ire);
14179 			ire = ire1;
14180 			IRE_REFHOLD(ire);
14181 		}
14182 
14183 		/* Check if there are additional ones with stq set */
14184 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14185 			if (ire->ire_addr != ire1->ire_addr)
14186 				break;
14187 			if (ire1->ire_stq) {
14188 				num_stq++;
14189 				break;
14190 			}
14191 		}
14192 		rw_exit(&ire->ire_bucket->irb_lock);
14193 		if (num_stq == 1 && ire->ire_stq != NULL) {
14194 			ip1dbg(("ip_rput_process_broadcast: directed "
14195 			    "broadcast to 0x%x\n",
14196 			    ntohl(ire->ire_addr)));
14197 			mp1 = copymsg(mp);
14198 			if (mp1) {
14199 				switch (ipha->ipha_protocol) {
14200 				case IPPROTO_UDP:
14201 					ip_udp_input(q, mp1, ipha, ire, ill);
14202 					break;
14203 				default:
14204 					ip_proto_input(q, mp1, ipha, ire, ill,
14205 					    0);
14206 					break;
14207 				}
14208 			}
14209 			/*
14210 			 * Adjust ttl to 2 (1+1 - the forward engine
14211 			 * will decrement it by one.
14212 			 */
14213 			if (ip_csum_hdr(ipha)) {
14214 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14215 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14216 				freemsg(mp);
14217 				ire_refrele(ire);
14218 				return (NULL);
14219 			}
14220 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14221 			ipha->ipha_hdr_checksum = 0;
14222 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14223 			ip_rput_process_forward(q, mp, ire, ipha,
14224 			    ill, ll_multicast, B_FALSE);
14225 			ire_refrele(ire);
14226 			return (NULL);
14227 		}
14228 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14229 		    ntohl(ire->ire_addr)));
14230 	}
14231 
14232 
14233 	/* Restore any hardware checksum flags */
14234 	DB_CKSUMFLAGS(mp) = hcksumflags;
14235 	return (ire);
14236 }
14237 
14238 /* ARGSUSED */
14239 static boolean_t
14240 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14241     int *ll_multicast, ipaddr_t *dstp)
14242 {
14243 	ip_stack_t	*ipst = ill->ill_ipst;
14244 
14245 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14246 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14247 	    ntohs(ipha->ipha_length));
14248 
14249 	/*
14250 	 * So that we don't end up with dups, only one ill an IPMP group is
14251 	 * nominated to receive multicast traffic.
14252 	 */
14253 	if (IS_UNDER_IPMP(ill) && !ill->ill_nom_cast)
14254 		goto drop_pkt;
14255 
14256 	/*
14257 	 * Forward packets only if we have joined the allmulti
14258 	 * group on this interface.
14259 	 */
14260 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14261 		int retval;
14262 
14263 		/*
14264 		 * Clear the indication that this may have hardware
14265 		 * checksum as we are not using it.
14266 		 */
14267 		DB_CKSUMFLAGS(mp) = 0;
14268 		retval = ip_mforward(ill, ipha, mp);
14269 		/* ip_mforward updates mib variables if needed */
14270 		/* clear b_prev - used by ip_mroute_decap */
14271 		mp->b_prev = NULL;
14272 
14273 		switch (retval) {
14274 		case 0:
14275 			/*
14276 			 * pkt is okay and arrived on phyint.
14277 			 *
14278 			 * If we are running as a multicast router
14279 			 * we need to see all IGMP and/or PIM packets.
14280 			 */
14281 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14282 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14283 				goto done;
14284 			}
14285 			break;
14286 		case -1:
14287 			/* pkt is mal-formed, toss it */
14288 			goto drop_pkt;
14289 		case 1:
14290 			/* pkt is okay and arrived on a tunnel */
14291 			/*
14292 			 * If we are running a multicast router
14293 			 *  we need to see all igmp packets.
14294 			 */
14295 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14296 				*dstp = INADDR_BROADCAST;
14297 				*ll_multicast = 1;
14298 				return (B_FALSE);
14299 			}
14300 
14301 			goto drop_pkt;
14302 		}
14303 	}
14304 
14305 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14306 		/*
14307 		 * This might just be caused by the fact that
14308 		 * multiple IP Multicast addresses map to the same
14309 		 * link layer multicast - no need to increment counter!
14310 		 */
14311 		freemsg(mp);
14312 		return (B_TRUE);
14313 	}
14314 done:
14315 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14316 	/*
14317 	 * This assumes the we deliver to all streams for multicast
14318 	 * and broadcast packets.
14319 	 */
14320 	*dstp = INADDR_BROADCAST;
14321 	*ll_multicast = 1;
14322 	return (B_FALSE);
14323 drop_pkt:
14324 	ip2dbg(("ip_rput: drop pkt\n"));
14325 	freemsg(mp);
14326 	return (B_TRUE);
14327 }
14328 
14329 /*
14330  * This function is used to both return an indication of whether or not
14331  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14332  * and in doing so, determine whether or not it is broadcast vs multicast.
14333  * For it to be a broadcast packet, we must have the appropriate mblk_t
14334  * hanging off the ill_t.  If this is either not present or doesn't match
14335  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14336  * to be multicast.  Thus NICs that have no broadcast address (or no
14337  * capability for one, such as point to point links) cannot return as
14338  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14339  * the return values simplifies the current use of the return value of this
14340  * function, which is to pass through the multicast/broadcast characteristic
14341  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14342  * changing the return value to some other symbol demands the appropriate
14343  * "translation" when hpe_flags is set prior to calling hook_run() for
14344  * packet events.
14345  */
14346 int
14347 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14348 {
14349 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14350 	mblk_t *bmp;
14351 
14352 	if (ind->dl_group_address) {
14353 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14354 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14355 		    MBLKL(mb) &&
14356 		    (bmp = ill->ill_bcast_mp) != NULL) {
14357 			dl_unitdata_req_t *dlur;
14358 			uint8_t *bphys_addr;
14359 
14360 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14361 			if (ill->ill_sap_length < 0)
14362 				bphys_addr = (uchar_t *)dlur +
14363 				    dlur->dl_dest_addr_offset;
14364 			else
14365 				bphys_addr = (uchar_t *)dlur +
14366 				    dlur->dl_dest_addr_offset +
14367 				    ill->ill_sap_length;
14368 
14369 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14370 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14371 				return (HPE_BROADCAST);
14372 			}
14373 			return (HPE_MULTICAST);
14374 		}
14375 		return (HPE_MULTICAST);
14376 	}
14377 	return (0);
14378 }
14379 
14380 static boolean_t
14381 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14382     int *ll_multicast, mblk_t **mpp)
14383 {
14384 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14385 	boolean_t must_copy = B_FALSE;
14386 	struct iocblk   *iocp;
14387 	ipha_t		*ipha;
14388 	ip_stack_t	*ipst = ill->ill_ipst;
14389 
14390 #define	rptr    ((uchar_t *)ipha)
14391 
14392 	first_mp = *first_mpp;
14393 	mp = *mpp;
14394 
14395 	ASSERT(first_mp == mp);
14396 
14397 	/*
14398 	 * if db_ref > 1 then copymsg and free original. Packet may be
14399 	 * changed and do not want other entity who has a reference to this
14400 	 * message to trip over the changes. This is a blind change because
14401 	 * trying to catch all places that might change packet is too
14402 	 * difficult (since it may be a module above this one)
14403 	 *
14404 	 * This corresponds to the non-fast path case. We walk down the full
14405 	 * chain in this case, and check the db_ref count of all the dblks,
14406 	 * and do a copymsg if required. It is possible that the db_ref counts
14407 	 * of the data blocks in the mblk chain can be different.
14408 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14409 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14410 	 * 'snoop' is running.
14411 	 */
14412 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14413 		if (mp1->b_datap->db_ref > 1) {
14414 			must_copy = B_TRUE;
14415 			break;
14416 		}
14417 	}
14418 
14419 	if (must_copy) {
14420 		mp1 = copymsg(mp);
14421 		if (mp1 == NULL) {
14422 			for (mp1 = mp; mp1 != NULL;
14423 			    mp1 = mp1->b_cont) {
14424 				mp1->b_next = NULL;
14425 				mp1->b_prev = NULL;
14426 			}
14427 			freemsg(mp);
14428 			if (ill != NULL) {
14429 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14430 			} else {
14431 				BUMP_MIB(&ipst->ips_ip_mib,
14432 				    ipIfStatsInDiscards);
14433 			}
14434 			return (B_TRUE);
14435 		}
14436 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14437 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14438 			/* Copy b_prev - used by ip_mroute_decap */
14439 			to_mp->b_prev = from_mp->b_prev;
14440 			from_mp->b_prev = NULL;
14441 		}
14442 		*first_mpp = first_mp = mp1;
14443 		freemsg(mp);
14444 		mp = mp1;
14445 		*mpp = mp1;
14446 	}
14447 
14448 	ipha = (ipha_t *)mp->b_rptr;
14449 
14450 	/*
14451 	 * previous code has a case for M_DATA.
14452 	 * We want to check how that happens.
14453 	 */
14454 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14455 	switch (first_mp->b_datap->db_type) {
14456 	case M_PROTO:
14457 	case M_PCPROTO:
14458 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14459 		    DL_UNITDATA_IND) {
14460 			/* Go handle anything other than data elsewhere. */
14461 			ip_rput_dlpi(q, mp);
14462 			return (B_TRUE);
14463 		}
14464 
14465 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14466 		/* Ditch the DLPI header. */
14467 		mp1 = mp->b_cont;
14468 		ASSERT(first_mp == mp);
14469 		*first_mpp = mp1;
14470 		freeb(mp);
14471 		*mpp = mp1;
14472 		return (B_FALSE);
14473 	case M_IOCACK:
14474 		ip1dbg(("got iocack "));
14475 		iocp = (struct iocblk *)mp->b_rptr;
14476 		switch (iocp->ioc_cmd) {
14477 		case DL_IOC_HDR_INFO:
14478 			ill = (ill_t *)q->q_ptr;
14479 			ill_fastpath_ack(ill, mp);
14480 			return (B_TRUE);
14481 		case SIOCSTUNPARAM:
14482 		case OSIOCSTUNPARAM:
14483 			/* Go through qwriter_ip */
14484 			break;
14485 		case SIOCGTUNPARAM:
14486 		case OSIOCGTUNPARAM:
14487 			ip_rput_other(NULL, q, mp, NULL);
14488 			return (B_TRUE);
14489 		default:
14490 			putnext(q, mp);
14491 			return (B_TRUE);
14492 		}
14493 		/* FALLTHRU */
14494 	case M_ERROR:
14495 	case M_HANGUP:
14496 		/*
14497 		 * Since this is on the ill stream we unconditionally
14498 		 * bump up the refcount
14499 		 */
14500 		ill_refhold(ill);
14501 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14502 		return (B_TRUE);
14503 	case M_CTL:
14504 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14505 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14506 		    IPHADA_M_CTL)) {
14507 			/*
14508 			 * It's an IPsec accelerated packet.
14509 			 * Make sure that the ill from which we received the
14510 			 * packet has enabled IPsec hardware acceleration.
14511 			 */
14512 			if (!(ill->ill_capabilities &
14513 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14514 				/* IPsec kstats: bean counter */
14515 				freemsg(mp);
14516 				return (B_TRUE);
14517 			}
14518 
14519 			/*
14520 			 * Make mp point to the mblk following the M_CTL,
14521 			 * then process according to type of mp.
14522 			 * After this processing, first_mp will point to
14523 			 * the data-attributes and mp to the pkt following
14524 			 * the M_CTL.
14525 			 */
14526 			mp = first_mp->b_cont;
14527 			if (mp == NULL) {
14528 				freemsg(first_mp);
14529 				return (B_TRUE);
14530 			}
14531 			/*
14532 			 * A Hardware Accelerated packet can only be M_DATA
14533 			 * ESP or AH packet.
14534 			 */
14535 			if (mp->b_datap->db_type != M_DATA) {
14536 				/* non-M_DATA IPsec accelerated packet */
14537 				IPSECHW_DEBUG(IPSECHW_PKT,
14538 				    ("non-M_DATA IPsec accelerated pkt\n"));
14539 				freemsg(first_mp);
14540 				return (B_TRUE);
14541 			}
14542 			ipha = (ipha_t *)mp->b_rptr;
14543 			if (ipha->ipha_protocol != IPPROTO_AH &&
14544 			    ipha->ipha_protocol != IPPROTO_ESP) {
14545 				IPSECHW_DEBUG(IPSECHW_PKT,
14546 				    ("non-M_DATA IPsec accelerated pkt\n"));
14547 				freemsg(first_mp);
14548 				return (B_TRUE);
14549 			}
14550 			*mpp = mp;
14551 			return (B_FALSE);
14552 		}
14553 		putnext(q, mp);
14554 		return (B_TRUE);
14555 	case M_IOCNAK:
14556 		ip1dbg(("got iocnak "));
14557 		iocp = (struct iocblk *)mp->b_rptr;
14558 		switch (iocp->ioc_cmd) {
14559 		case SIOCSTUNPARAM:
14560 		case OSIOCSTUNPARAM:
14561 			/*
14562 			 * Since this is on the ill stream we unconditionally
14563 			 * bump up the refcount
14564 			 */
14565 			ill_refhold(ill);
14566 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14567 			return (B_TRUE);
14568 		case DL_IOC_HDR_INFO:
14569 		case SIOCGTUNPARAM:
14570 		case OSIOCGTUNPARAM:
14571 			ip_rput_other(NULL, q, mp, NULL);
14572 			return (B_TRUE);
14573 		default:
14574 			break;
14575 		}
14576 		/* FALLTHRU */
14577 	default:
14578 		putnext(q, mp);
14579 		return (B_TRUE);
14580 	}
14581 }
14582 
14583 /* Read side put procedure.  Packets coming from the wire arrive here. */
14584 void
14585 ip_rput(queue_t *q, mblk_t *mp)
14586 {
14587 	ill_t	*ill;
14588 	union DL_primitives *dl;
14589 
14590 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14591 
14592 	ill = (ill_t *)q->q_ptr;
14593 
14594 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14595 		/*
14596 		 * If things are opening or closing, only accept high-priority
14597 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14598 		 * created; on close, things hanging off the ill may have been
14599 		 * freed already.)
14600 		 */
14601 		dl = (union DL_primitives *)mp->b_rptr;
14602 		if (DB_TYPE(mp) != M_PCPROTO ||
14603 		    dl->dl_primitive == DL_UNITDATA_IND) {
14604 			/*
14605 			 * SIOC[GS]TUNPARAM ioctls can come here.
14606 			 */
14607 			inet_freemsg(mp);
14608 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14609 			    "ip_rput_end: q %p (%S)", q, "uninit");
14610 			return;
14611 		}
14612 	}
14613 
14614 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14615 	    "ip_rput_end: q %p (%S)", q, "end");
14616 
14617 	ip_input(ill, NULL, mp, NULL);
14618 }
14619 
14620 static mblk_t *
14621 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14622 {
14623 	mblk_t *mp1;
14624 	boolean_t adjusted = B_FALSE;
14625 	ip_stack_t *ipst = ill->ill_ipst;
14626 
14627 	IP_STAT(ipst, ip_db_ref);
14628 	/*
14629 	 * The IP_RECVSLLA option depends on having the
14630 	 * link layer header. First check that:
14631 	 * a> the underlying device is of type ether,
14632 	 * since this option is currently supported only
14633 	 * over ethernet.
14634 	 * b> there is enough room to copy over the link
14635 	 * layer header.
14636 	 *
14637 	 * Once the checks are done, adjust rptr so that
14638 	 * the link layer header will be copied via
14639 	 * copymsg. Note that, IFT_ETHER may be returned
14640 	 * by some non-ethernet drivers but in this case
14641 	 * the second check will fail.
14642 	 */
14643 	if (ill->ill_type == IFT_ETHER &&
14644 	    (mp->b_rptr - mp->b_datap->db_base) >=
14645 	    sizeof (struct ether_header)) {
14646 		mp->b_rptr -= sizeof (struct ether_header);
14647 		adjusted = B_TRUE;
14648 	}
14649 	mp1 = copymsg(mp);
14650 
14651 	if (mp1 == NULL) {
14652 		mp->b_next = NULL;
14653 		/* clear b_prev - used by ip_mroute_decap */
14654 		mp->b_prev = NULL;
14655 		freemsg(mp);
14656 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14657 		return (NULL);
14658 	}
14659 
14660 	if (adjusted) {
14661 		/*
14662 		 * Copy is done. Restore the pointer in
14663 		 * the _new_ mblk
14664 		 */
14665 		mp1->b_rptr += sizeof (struct ether_header);
14666 	}
14667 
14668 	/* Copy b_prev - used by ip_mroute_decap */
14669 	mp1->b_prev = mp->b_prev;
14670 	mp->b_prev = NULL;
14671 
14672 	/* preserve the hardware checksum flags and data, if present */
14673 	if (DB_CKSUMFLAGS(mp) != 0) {
14674 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14675 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14676 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14677 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14678 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14679 	}
14680 
14681 	freemsg(mp);
14682 	return (mp1);
14683 }
14684 
14685 #define	ADD_TO_CHAIN(head, tail, cnt, mp) {    			\
14686 	if (tail != NULL)					\
14687 		tail->b_next = mp;				\
14688 	else							\
14689 		head = mp;					\
14690 	tail = mp;						\
14691 	cnt++;							\
14692 }
14693 
14694 /*
14695  * Direct read side procedure capable of dealing with chains. GLDv3 based
14696  * drivers call this function directly with mblk chains while STREAMS
14697  * read side procedure ip_rput() calls this for single packet with ip_ring
14698  * set to NULL to process one packet at a time.
14699  *
14700  * The ill will always be valid if this function is called directly from
14701  * the driver.
14702  *
14703  * If ip_input() is called from GLDv3:
14704  *
14705  *   - This must be a non-VLAN IP stream.
14706  *   - 'mp' is either an untagged or a special priority-tagged packet.
14707  *   - Any VLAN tag that was in the MAC header has been stripped.
14708  *
14709  * If the IP header in packet is not 32-bit aligned, every message in the
14710  * chain will be aligned before further operations. This is required on SPARC
14711  * platform.
14712  */
14713 /* ARGSUSED */
14714 void
14715 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14716     struct mac_header_info_s *mhip)
14717 {
14718 	ipaddr_t		dst = NULL;
14719 	ipaddr_t		prev_dst;
14720 	ire_t			*ire = NULL;
14721 	ipha_t			*ipha;
14722 	uint_t			pkt_len;
14723 	ssize_t			len;
14724 	uint_t			opt_len;
14725 	int			ll_multicast;
14726 	int			cgtp_flt_pkt;
14727 	queue_t			*q = ill->ill_rq;
14728 	squeue_t		*curr_sqp = NULL;
14729 	mblk_t 			*head = NULL;
14730 	mblk_t			*tail = NULL;
14731 	mblk_t			*first_mp;
14732 	int			cnt = 0;
14733 	ip_stack_t		*ipst = ill->ill_ipst;
14734 	mblk_t			*mp;
14735 	mblk_t			*dmp;
14736 	uint8_t			tag;
14737 
14738 	ASSERT(mp_chain != NULL);
14739 	ASSERT(ill != NULL);
14740 
14741 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14742 
14743 	tag = (ip_ring != NULL) ? SQTAG_IP_INPUT_RX_RING : SQTAG_IP_INPUT;
14744 
14745 #define	rptr	((uchar_t *)ipha)
14746 
14747 	while (mp_chain != NULL) {
14748 		mp = mp_chain;
14749 		mp_chain = mp_chain->b_next;
14750 		mp->b_next = NULL;
14751 		ll_multicast = 0;
14752 
14753 		/*
14754 		 * We do ire caching from one iteration to
14755 		 * another. In the event the packet chain contains
14756 		 * all packets from the same dst, this caching saves
14757 		 * an ire_cache_lookup for each of the succeeding
14758 		 * packets in a packet chain.
14759 		 */
14760 		prev_dst = dst;
14761 
14762 		/*
14763 		 * if db_ref > 1 then copymsg and free original. Packet
14764 		 * may be changed and we do not want the other entity
14765 		 * who has a reference to this message to trip over the
14766 		 * changes. This is a blind change because trying to
14767 		 * catch all places that might change the packet is too
14768 		 * difficult.
14769 		 *
14770 		 * This corresponds to the fast path case, where we have
14771 		 * a chain of M_DATA mblks.  We check the db_ref count
14772 		 * of only the 1st data block in the mblk chain. There
14773 		 * doesn't seem to be a reason why a device driver would
14774 		 * send up data with varying db_ref counts in the mblk
14775 		 * chain. In any case the Fast path is a private
14776 		 * interface, and our drivers don't do such a thing.
14777 		 * Given the above assumption, there is no need to walk
14778 		 * down the entire mblk chain (which could have a
14779 		 * potential performance problem)
14780 		 *
14781 		 * The "(DB_REF(mp) > 1)" check was moved from ip_rput()
14782 		 * to here because of exclusive ip stacks and vnics.
14783 		 * Packets transmitted from exclusive stack over vnic
14784 		 * can have db_ref > 1 and when it gets looped back to
14785 		 * another vnic in a different zone, you have ip_input()
14786 		 * getting dblks with db_ref > 1. So if someone
14787 		 * complains of TCP performance under this scenario,
14788 		 * take a serious look here on the impact of copymsg().
14789 		 */
14790 
14791 		if (DB_REF(mp) > 1) {
14792 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14793 				continue;
14794 		}
14795 
14796 		/*
14797 		 * Check and align the IP header.
14798 		 */
14799 		first_mp = mp;
14800 		if (DB_TYPE(mp) == M_DATA) {
14801 			dmp = mp;
14802 		} else if (DB_TYPE(mp) == M_PROTO &&
14803 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14804 			dmp = mp->b_cont;
14805 		} else {
14806 			dmp = NULL;
14807 		}
14808 		if (dmp != NULL) {
14809 			/*
14810 			 * IP header ptr not aligned?
14811 			 * OR IP header not complete in first mblk
14812 			 */
14813 			if (!OK_32PTR(dmp->b_rptr) ||
14814 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14815 				if (!ip_check_and_align_header(q, dmp, ipst))
14816 					continue;
14817 			}
14818 		}
14819 
14820 		/*
14821 		 * ip_input fast path
14822 		 */
14823 
14824 		/* mblk type is not M_DATA */
14825 		if (DB_TYPE(mp) != M_DATA) {
14826 			if (ip_rput_process_notdata(q, &first_mp, ill,
14827 			    &ll_multicast, &mp))
14828 				continue;
14829 
14830 			/*
14831 			 * The only way we can get here is if we had a
14832 			 * packet that was either a DL_UNITDATA_IND or
14833 			 * an M_CTL for an IPsec accelerated packet.
14834 			 *
14835 			 * In either case, the first_mp will point to
14836 			 * the leading M_PROTO or M_CTL.
14837 			 */
14838 			ASSERT(first_mp != NULL);
14839 		} else if (mhip != NULL) {
14840 			/*
14841 			 * ll_multicast is set here so that it is ready
14842 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
14843 			 * manipulates ll_multicast in the same fashion when
14844 			 * called from ip_rput_process_notdata.
14845 			 */
14846 			switch (mhip->mhi_dsttype) {
14847 			case MAC_ADDRTYPE_MULTICAST :
14848 				ll_multicast = HPE_MULTICAST;
14849 				break;
14850 			case MAC_ADDRTYPE_BROADCAST :
14851 				ll_multicast = HPE_BROADCAST;
14852 				break;
14853 			default :
14854 				break;
14855 			}
14856 		}
14857 
14858 		/* Only M_DATA can come here and it is always aligned */
14859 		ASSERT(DB_TYPE(mp) == M_DATA);
14860 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
14861 
14862 		ipha = (ipha_t *)mp->b_rptr;
14863 		len = mp->b_wptr - rptr;
14864 		pkt_len = ntohs(ipha->ipha_length);
14865 
14866 		/*
14867 		 * We must count all incoming packets, even if they end
14868 		 * up being dropped later on.
14869 		 */
14870 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
14871 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
14872 
14873 		/* multiple mblk or too short */
14874 		len -= pkt_len;
14875 		if (len != 0) {
14876 			/*
14877 			 * Make sure we have data length consistent
14878 			 * with the IP header.
14879 			 */
14880 			if (mp->b_cont == NULL) {
14881 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14882 					BUMP_MIB(ill->ill_ip_mib,
14883 					    ipIfStatsInHdrErrors);
14884 					ip2dbg(("ip_input: drop pkt\n"));
14885 					freemsg(mp);
14886 					continue;
14887 				}
14888 				mp->b_wptr = rptr + pkt_len;
14889 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
14890 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14891 					BUMP_MIB(ill->ill_ip_mib,
14892 					    ipIfStatsInHdrErrors);
14893 					ip2dbg(("ip_input: drop pkt\n"));
14894 					freemsg(mp);
14895 					continue;
14896 				}
14897 				(void) adjmsg(mp, -len);
14898 				IP_STAT(ipst, ip_multimblk3);
14899 			}
14900 		}
14901 
14902 		/* Obtain the dst of the current packet */
14903 		dst = ipha->ipha_dst;
14904 
14905 		DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL,
14906 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *,
14907 		    ipha, ip6_t *, NULL, int, 0);
14908 
14909 		/*
14910 		 * The following test for loopback is faster than
14911 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
14912 		 * operations.
14913 		 * Note that these addresses are always in network byte order
14914 		 */
14915 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
14916 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
14917 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
14918 			freemsg(mp);
14919 			continue;
14920 		}
14921 
14922 		/*
14923 		 * The event for packets being received from a 'physical'
14924 		 * interface is placed after validation of the source and/or
14925 		 * destination address as being local so that packets can be
14926 		 * redirected to loopback addresses using ipnat.
14927 		 */
14928 		DTRACE_PROBE4(ip4__physical__in__start,
14929 		    ill_t *, ill, ill_t *, NULL,
14930 		    ipha_t *, ipha, mblk_t *, first_mp);
14931 
14932 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
14933 		    ipst->ips_ipv4firewall_physical_in,
14934 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
14935 
14936 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
14937 
14938 		if (first_mp == NULL) {
14939 			continue;
14940 		}
14941 		dst = ipha->ipha_dst;
14942 		/*
14943 		 * Attach any necessary label information to
14944 		 * this packet
14945 		 */
14946 		if (is_system_labeled() &&
14947 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
14948 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14949 			freemsg(mp);
14950 			continue;
14951 		}
14952 
14953 		if (ipst->ips_ipobs_enabled) {
14954 			zoneid_t dzone;
14955 
14956 			/*
14957 			 * On the inbound path the src zone will be unknown as
14958 			 * this packet has come from the wire.
14959 			 */
14960 			dzone = ip_get_zoneid_v4(dst, mp, ipst, ALL_ZONES);
14961 			ipobs_hook(mp, IPOBS_HOOK_INBOUND, ALL_ZONES, dzone,
14962 			    ill, IPV4_VERSION, 0, ipst);
14963 		}
14964 
14965 		/*
14966 		 * Reuse the cached ire only if the ipha_dst of the previous
14967 		 * packet is the same as the current packet AND it is not
14968 		 * INADDR_ANY.
14969 		 */
14970 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
14971 		    (ire != NULL)) {
14972 			ire_refrele(ire);
14973 			ire = NULL;
14974 		}
14975 
14976 		opt_len = ipha->ipha_version_and_hdr_length -
14977 		    IP_SIMPLE_HDR_VERSION;
14978 
14979 		/*
14980 		 * Check to see if we can take the fastpath.
14981 		 * That is possible if the following conditions are met
14982 		 *	o Tsol disabled
14983 		 *	o CGTP disabled
14984 		 *	o ipp_action_count is 0
14985 		 *	o no options in the packet
14986 		 *	o not a RSVP packet
14987 		 * 	o not a multicast packet
14988 		 *	o ill not in IP_DHCPINIT_IF mode
14989 		 */
14990 		if (!is_system_labeled() &&
14991 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
14992 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
14993 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
14994 			if (ire == NULL)
14995 				ire = ire_cache_lookup_simple(dst, ipst);
14996 			/*
14997 			 * Unless forwarding is enabled, dont call
14998 			 * ip_fast_forward(). Incoming packet is for forwarding
14999 			 */
15000 			if ((ill->ill_flags & ILLF_ROUTER) &&
15001 			    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15002 				ire = ip_fast_forward(ire, dst, ill, mp);
15003 				continue;
15004 			}
15005 			/* incoming packet is for local consumption */
15006 			if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15007 				goto local;
15008 		}
15009 
15010 		/*
15011 		 * Disable ire caching for anything more complex
15012 		 * than the simple fast path case we checked for above.
15013 		 */
15014 		if (ire != NULL) {
15015 			ire_refrele(ire);
15016 			ire = NULL;
15017 		}
15018 
15019 		/*
15020 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15021 		 * server to unicast DHCP packets to a DHCP client using the
15022 		 * IP address it is offering to the client.  This can be
15023 		 * disabled through the "broadcast bit", but not all DHCP
15024 		 * servers honor that bit.  Therefore, to interoperate with as
15025 		 * many DHCP servers as possible, the DHCP client allows the
15026 		 * server to unicast, but we treat those packets as broadcast
15027 		 * here.  Note that we don't rewrite the packet itself since
15028 		 * (a) that would mess up the checksums and (b) the DHCP
15029 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15030 		 * hand it the packet regardless.
15031 		 */
15032 		if (ill->ill_dhcpinit != 0 &&
15033 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15034 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15035 			udpha_t *udpha;
15036 
15037 			/*
15038 			 * Reload ipha since pullupmsg() can change b_rptr.
15039 			 */
15040 			ipha = (ipha_t *)mp->b_rptr;
15041 			udpha = (udpha_t *)&ipha[1];
15042 
15043 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15044 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15045 				    mblk_t *, mp);
15046 				dst = INADDR_BROADCAST;
15047 			}
15048 		}
15049 
15050 		/* Full-blown slow path */
15051 		if (opt_len != 0) {
15052 			if (len != 0)
15053 				IP_STAT(ipst, ip_multimblk4);
15054 			else
15055 				IP_STAT(ipst, ip_ipoptions);
15056 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15057 			    &dst, ipst))
15058 				continue;
15059 		}
15060 
15061 		/*
15062 		 * Invoke the CGTP (multirouting) filtering module to process
15063 		 * the incoming packet. Packets identified as duplicates
15064 		 * must be discarded. Filtering is active only if the
15065 		 * the ip_cgtp_filter ndd variable is non-zero.
15066 		 */
15067 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15068 		if (ipst->ips_ip_cgtp_filter &&
15069 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15070 			netstackid_t stackid;
15071 
15072 			stackid = ipst->ips_netstack->netstack_stackid;
15073 			cgtp_flt_pkt =
15074 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15075 			    ill->ill_phyint->phyint_ifindex, mp);
15076 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15077 				freemsg(first_mp);
15078 				continue;
15079 			}
15080 		}
15081 
15082 		/*
15083 		 * If rsvpd is running, let RSVP daemon handle its processing
15084 		 * and forwarding of RSVP multicast/unicast packets.
15085 		 * If rsvpd is not running but mrouted is running, RSVP
15086 		 * multicast packets are forwarded as multicast traffic
15087 		 * and RSVP unicast packets are forwarded by unicast router.
15088 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15089 		 * packets are not forwarded, but the unicast packets are
15090 		 * forwarded like unicast traffic.
15091 		 */
15092 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15093 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15094 		    NULL) {
15095 			/* RSVP packet and rsvpd running. Treat as ours */
15096 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15097 			/*
15098 			 * This assumes that we deliver to all streams for
15099 			 * multicast and broadcast packets.
15100 			 * We have to force ll_multicast to 1 to handle the
15101 			 * M_DATA messages passed in from ip_mroute_decap.
15102 			 */
15103 			dst = INADDR_BROADCAST;
15104 			ll_multicast = 1;
15105 		} else if (CLASSD(dst)) {
15106 			/* packet is multicast */
15107 			mp->b_next = NULL;
15108 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15109 			    &ll_multicast, &dst))
15110 				continue;
15111 		}
15112 
15113 		if (ire == NULL) {
15114 			ire = ire_cache_lookup(dst, ALL_ZONES,
15115 			    MBLK_GETLABEL(mp), ipst);
15116 		}
15117 
15118 		if (ire != NULL && ire->ire_stq != NULL &&
15119 		    ire->ire_zoneid != GLOBAL_ZONEID &&
15120 		    ire->ire_zoneid != ALL_ZONES) {
15121 			/*
15122 			 * Should only use IREs that are visible from the
15123 			 * global zone for forwarding.
15124 			 */
15125 			ire_refrele(ire);
15126 			ire = ire_cache_lookup(dst, GLOBAL_ZONEID,
15127 			    MBLK_GETLABEL(mp), ipst);
15128 		}
15129 
15130 		if (ire == NULL) {
15131 			/*
15132 			 * No IRE for this destination, so it can't be for us.
15133 			 * Unless we are forwarding, drop the packet.
15134 			 * We have to let source routed packets through
15135 			 * since we don't yet know if they are 'ping -l'
15136 			 * packets i.e. if they will go out over the
15137 			 * same interface as they came in on.
15138 			 */
15139 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15140 			if (ire == NULL)
15141 				continue;
15142 		}
15143 
15144 		/*
15145 		 * Broadcast IRE may indicate either broadcast or
15146 		 * multicast packet
15147 		 */
15148 		if (ire->ire_type == IRE_BROADCAST) {
15149 			/*
15150 			 * Skip broadcast checks if packet is UDP multicast;
15151 			 * we'd rather not enter ip_rput_process_broadcast()
15152 			 * unless the packet is broadcast for real, since
15153 			 * that routine is a no-op for multicast.
15154 			 */
15155 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15156 			    !CLASSD(ipha->ipha_dst)) {
15157 				ire = ip_rput_process_broadcast(&q, mp,
15158 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15159 				    ll_multicast);
15160 				if (ire == NULL)
15161 					continue;
15162 			}
15163 		} else if (ire->ire_stq != NULL) {
15164 			/* fowarding? */
15165 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15166 			    ll_multicast, B_FALSE);
15167 			/* ip_rput_process_forward consumed the packet */
15168 			continue;
15169 		}
15170 
15171 local:
15172 		/*
15173 		 * If the queue in the ire is different to the ingress queue
15174 		 * then we need to check to see if we can accept the packet.
15175 		 * Note that for multicast packets and broadcast packets sent
15176 		 * to a broadcast address which is shared between multiple
15177 		 * interfaces we should not do this since we just got a random
15178 		 * broadcast ire.
15179 		 */
15180 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15181 			ire = ip_check_multihome(&ipha->ipha_dst, ire, ill);
15182 			if (ire == NULL) {
15183 				/* Drop packet */
15184 				BUMP_MIB(ill->ill_ip_mib,
15185 				    ipIfStatsForwProhibits);
15186 				freemsg(mp);
15187 				continue;
15188 			}
15189 			if (ire->ire_rfq != NULL)
15190 				q = ire->ire_rfq;
15191 		}
15192 
15193 		switch (ipha->ipha_protocol) {
15194 		case IPPROTO_TCP:
15195 			ASSERT(first_mp == mp);
15196 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15197 			    mp, 0, q, ip_ring)) != NULL) {
15198 				if (curr_sqp == NULL) {
15199 					curr_sqp = GET_SQUEUE(mp);
15200 					ASSERT(cnt == 0);
15201 					cnt++;
15202 					head = tail = mp;
15203 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15204 					ASSERT(tail != NULL);
15205 					cnt++;
15206 					tail->b_next = mp;
15207 					tail = mp;
15208 				} else {
15209 					/*
15210 					 * A different squeue. Send the
15211 					 * chain for the previous squeue on
15212 					 * its way. This shouldn't happen
15213 					 * often unless interrupt binding
15214 					 * changes.
15215 					 */
15216 					IP_STAT(ipst, ip_input_multi_squeue);
15217 					SQUEUE_ENTER(curr_sqp, head,
15218 					    tail, cnt, SQ_PROCESS, tag);
15219 					curr_sqp = GET_SQUEUE(mp);
15220 					head = mp;
15221 					tail = mp;
15222 					cnt = 1;
15223 				}
15224 			}
15225 			continue;
15226 		case IPPROTO_UDP:
15227 			ASSERT(first_mp == mp);
15228 			ip_udp_input(q, mp, ipha, ire, ill);
15229 			continue;
15230 		case IPPROTO_SCTP:
15231 			ASSERT(first_mp == mp);
15232 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15233 			    q, dst);
15234 			/* ire has been released by ip_sctp_input */
15235 			ire = NULL;
15236 			continue;
15237 		default:
15238 			ip_proto_input(q, first_mp, ipha, ire, ill, 0);
15239 			continue;
15240 		}
15241 	}
15242 
15243 	if (ire != NULL)
15244 		ire_refrele(ire);
15245 
15246 	if (head != NULL)
15247 		SQUEUE_ENTER(curr_sqp, head, tail, cnt, SQ_PROCESS, tag);
15248 
15249 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15250 	    "ip_input_end: q %p (%S)", q, "end");
15251 #undef  rptr
15252 }
15253 
15254 /*
15255  * ip_accept_tcp() - This function is called by the squeue when it retrieves
15256  * a chain of packets in the poll mode. The packets have gone through the
15257  * data link processing but not IP processing. For performance and latency
15258  * reasons, the squeue wants to process the chain in line instead of feeding
15259  * it back via ip_input path.
15260  *
15261  * So this is a light weight function which checks to see if the packets
15262  * retrived are indeed TCP packets (TCP squeue always polls TCP soft ring
15263  * but we still do the paranoid check) meant for local machine and we don't
15264  * have labels etc enabled. Packets that meet the criterion are returned to
15265  * the squeue and processed inline while the rest go via ip_input path.
15266  */
15267 /*ARGSUSED*/
15268 mblk_t *
15269 ip_accept_tcp(ill_t *ill, ill_rx_ring_t *ip_ring, squeue_t *target_sqp,
15270     mblk_t *mp_chain, mblk_t **last, uint_t *cnt)
15271 {
15272 	mblk_t 		*mp;
15273 	ipaddr_t	dst = NULL;
15274 	ipaddr_t	prev_dst;
15275 	ire_t		*ire = NULL;
15276 	ipha_t		*ipha;
15277 	uint_t		pkt_len;
15278 	ssize_t		len;
15279 	uint_t		opt_len;
15280 	queue_t		*q = ill->ill_rq;
15281 	squeue_t	*curr_sqp;
15282 	mblk_t 		*ahead = NULL;	/* Accepted head */
15283 	mblk_t		*atail = NULL;	/* Accepted tail */
15284 	uint_t		acnt = 0;	/* Accepted count */
15285 	mblk_t		*utail = NULL;	/* Unaccepted head */
15286 	mblk_t		*uhead = NULL;	/* Unaccepted tail */
15287 	uint_t		ucnt = 0;	/* Unaccepted cnt */
15288 	ip_stack_t	*ipst = ill->ill_ipst;
15289 
15290 	*cnt = 0;
15291 
15292 	ASSERT(ill != NULL);
15293 	ASSERT(ip_ring != NULL);
15294 
15295 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_accept_tcp: q %p", q);
15296 
15297 #define	rptr	((uchar_t *)ipha)
15298 
15299 	while (mp_chain != NULL) {
15300 		mp = mp_chain;
15301 		mp_chain = mp_chain->b_next;
15302 		mp->b_next = NULL;
15303 
15304 		/*
15305 		 * We do ire caching from one iteration to
15306 		 * another. In the event the packet chain contains
15307 		 * all packets from the same dst, this caching saves
15308 		 * an ire_cache_lookup for each of the succeeding
15309 		 * packets in a packet chain.
15310 		 */
15311 		prev_dst = dst;
15312 
15313 		ipha = (ipha_t *)mp->b_rptr;
15314 		len = mp->b_wptr - rptr;
15315 
15316 		ASSERT(!MBLK_RX_FANOUT_SLOWPATH(mp, ipha));
15317 
15318 		/*
15319 		 * If it is a non TCP packet, or doesn't have H/W cksum,
15320 		 * or doesn't have min len, reject.
15321 		 */
15322 		if ((ipha->ipha_protocol != IPPROTO_TCP) || (len <
15323 		    (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH))) {
15324 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15325 			continue;
15326 		}
15327 
15328 		pkt_len = ntohs(ipha->ipha_length);
15329 		if (len != pkt_len) {
15330 			if (len > pkt_len) {
15331 				mp->b_wptr = rptr + pkt_len;
15332 			} else {
15333 				ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15334 				continue;
15335 			}
15336 		}
15337 
15338 		opt_len = ipha->ipha_version_and_hdr_length -
15339 		    IP_SIMPLE_HDR_VERSION;
15340 		dst = ipha->ipha_dst;
15341 
15342 		/* IP version bad or there are IP options */
15343 		if (opt_len && (!ip_rput_multimblk_ipoptions(q, ill,
15344 		    mp, &ipha, &dst, ipst)))
15345 			continue;
15346 
15347 		if (is_system_labeled() || (ill->ill_dhcpinit != 0) ||
15348 		    (ipst->ips_ip_cgtp_filter &&
15349 		    ipst->ips_ip_cgtp_filter_ops != NULL)) {
15350 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15351 			continue;
15352 		}
15353 
15354 		/*
15355 		 * Reuse the cached ire only if the ipha_dst of the previous
15356 		 * packet is the same as the current packet AND it is not
15357 		 * INADDR_ANY.
15358 		 */
15359 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15360 		    (ire != NULL)) {
15361 			ire_refrele(ire);
15362 			ire = NULL;
15363 		}
15364 
15365 		if (ire == NULL)
15366 			ire = ire_cache_lookup_simple(dst, ipst);
15367 
15368 		/*
15369 		 * Unless forwarding is enabled, dont call
15370 		 * ip_fast_forward(). Incoming packet is for forwarding
15371 		 */
15372 		if ((ill->ill_flags & ILLF_ROUTER) &&
15373 		    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15374 
15375 			DTRACE_PROBE4(ip4__physical__in__start,
15376 			    ill_t *, ill, ill_t *, NULL,
15377 			    ipha_t *, ipha, mblk_t *, mp);
15378 
15379 			FW_HOOKS(ipst->ips_ip4_physical_in_event,
15380 			    ipst->ips_ipv4firewall_physical_in,
15381 			    ill, NULL, ipha, mp, mp, 0, ipst);
15382 
15383 			DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15384 
15385 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15386 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets,
15387 			    pkt_len);
15388 
15389 			ire = ip_fast_forward(ire, dst, ill, mp);
15390 			continue;
15391 		}
15392 
15393 		/* incoming packet is for local consumption */
15394 		if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15395 			goto local_accept;
15396 
15397 		/*
15398 		 * Disable ire caching for anything more complex
15399 		 * than the simple fast path case we checked for above.
15400 		 */
15401 		if (ire != NULL) {
15402 			ire_refrele(ire);
15403 			ire = NULL;
15404 		}
15405 
15406 		ire = ire_cache_lookup(dst, ALL_ZONES, MBLK_GETLABEL(mp),
15407 		    ipst);
15408 		if (ire == NULL || ire->ire_type == IRE_BROADCAST ||
15409 		    ire->ire_stq != NULL) {
15410 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15411 			if (ire != NULL) {
15412 				ire_refrele(ire);
15413 				ire = NULL;
15414 			}
15415 			continue;
15416 		}
15417 
15418 local_accept:
15419 
15420 		if (ire->ire_rfq != q) {
15421 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15422 			if (ire != NULL) {
15423 				ire_refrele(ire);
15424 				ire = NULL;
15425 			}
15426 			continue;
15427 		}
15428 
15429 		/*
15430 		 * The event for packets being received from a 'physical'
15431 		 * interface is placed after validation of the source and/or
15432 		 * destination address as being local so that packets can be
15433 		 * redirected to loopback addresses using ipnat.
15434 		 */
15435 		DTRACE_PROBE4(ip4__physical__in__start,
15436 		    ill_t *, ill, ill_t *, NULL,
15437 		    ipha_t *, ipha, mblk_t *, mp);
15438 
15439 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15440 		    ipst->ips_ipv4firewall_physical_in,
15441 		    ill, NULL, ipha, mp, mp, 0, ipst);
15442 
15443 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15444 
15445 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15446 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15447 
15448 		if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire, mp,
15449 		    0, q, ip_ring)) != NULL) {
15450 			if ((curr_sqp = GET_SQUEUE(mp)) == target_sqp) {
15451 				ADD_TO_CHAIN(ahead, atail, acnt, mp);
15452 			} else {
15453 				SQUEUE_ENTER(curr_sqp, mp, mp, 1,
15454 				    SQ_FILL, SQTAG_IP_INPUT);
15455 			}
15456 		}
15457 	}
15458 
15459 	if (ire != NULL)
15460 		ire_refrele(ire);
15461 
15462 	if (uhead != NULL)
15463 		ip_input(ill, ip_ring, uhead, NULL);
15464 
15465 	if (ahead != NULL) {
15466 		*last = atail;
15467 		*cnt = acnt;
15468 		return (ahead);
15469 	}
15470 
15471 	return (NULL);
15472 #undef  rptr
15473 }
15474 
15475 static void
15476 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15477     t_uscalar_t err)
15478 {
15479 	if (dl_err == DL_SYSERR) {
15480 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15481 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15482 		    ill->ill_name, dl_primstr(prim), err);
15483 		return;
15484 	}
15485 
15486 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15487 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15488 	    dl_errstr(dl_err));
15489 }
15490 
15491 /*
15492  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15493  * than DL_UNITDATA_IND messages. If we need to process this message
15494  * exclusively, we call qwriter_ip, in which case we also need to call
15495  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15496  */
15497 void
15498 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15499 {
15500 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15501 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15502 	ill_t		*ill = q->q_ptr;
15503 	t_uscalar_t	prim = dloa->dl_primitive;
15504 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
15505 
15506 	ip1dbg(("ip_rput_dlpi"));
15507 
15508 	/*
15509 	 * If we received an ACK but didn't send a request for it, then it
15510 	 * can't be part of any pending operation; discard up-front.
15511 	 */
15512 	switch (prim) {
15513 	case DL_ERROR_ACK:
15514 		reqprim = dlea->dl_error_primitive;
15515 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
15516 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
15517 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
15518 		    dlea->dl_unix_errno));
15519 		break;
15520 	case DL_OK_ACK:
15521 		reqprim = dloa->dl_correct_primitive;
15522 		break;
15523 	case DL_INFO_ACK:
15524 		reqprim = DL_INFO_REQ;
15525 		break;
15526 	case DL_BIND_ACK:
15527 		reqprim = DL_BIND_REQ;
15528 		break;
15529 	case DL_PHYS_ADDR_ACK:
15530 		reqprim = DL_PHYS_ADDR_REQ;
15531 		break;
15532 	case DL_NOTIFY_ACK:
15533 		reqprim = DL_NOTIFY_REQ;
15534 		break;
15535 	case DL_CONTROL_ACK:
15536 		reqprim = DL_CONTROL_REQ;
15537 		break;
15538 	case DL_CAPABILITY_ACK:
15539 		reqprim = DL_CAPABILITY_REQ;
15540 		break;
15541 	}
15542 
15543 	if (prim != DL_NOTIFY_IND) {
15544 		if (reqprim == DL_PRIM_INVAL ||
15545 		    !ill_dlpi_pending(ill, reqprim)) {
15546 			/* Not a DLPI message we support or expected */
15547 			freemsg(mp);
15548 			return;
15549 		}
15550 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
15551 		    dl_primstr(reqprim)));
15552 	}
15553 
15554 	switch (reqprim) {
15555 	case DL_UNBIND_REQ:
15556 		/*
15557 		 * NOTE: we mark the unbind as complete even if we got a
15558 		 * DL_ERROR_ACK, since there's not much else we can do.
15559 		 */
15560 		mutex_enter(&ill->ill_lock);
15561 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15562 		cv_signal(&ill->ill_cv);
15563 		mutex_exit(&ill->ill_lock);
15564 		break;
15565 
15566 	case DL_ENABMULTI_REQ:
15567 		if (prim == DL_OK_ACK) {
15568 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15569 				ill->ill_dlpi_multicast_state = IDS_OK;
15570 		}
15571 		break;
15572 	}
15573 
15574 	/*
15575 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
15576 	 * need to become writer to continue to process it.  Because an
15577 	 * exclusive operation doesn't complete until replies to all queued
15578 	 * DLPI messages have been received, we know we're in the middle of an
15579 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
15580 	 *
15581 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15582 	 * Since this is on the ill stream we unconditionally bump up the
15583 	 * refcount without doing ILL_CAN_LOOKUP().
15584 	 */
15585 	ill_refhold(ill);
15586 	if (prim == DL_NOTIFY_IND)
15587 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15588 	else
15589 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15590 }
15591 
15592 /*
15593  * Handling of DLPI messages that require exclusive access to the ipsq.
15594  *
15595  * Need to do ill_pending_mp_release on ioctl completion, which could
15596  * happen here. (along with mi_copy_done)
15597  */
15598 /* ARGSUSED */
15599 static void
15600 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15601 {
15602 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15603 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15604 	int		err = 0;
15605 	ill_t		*ill;
15606 	ipif_t		*ipif = NULL;
15607 	mblk_t		*mp1 = NULL;
15608 	conn_t		*connp = NULL;
15609 	t_uscalar_t	paddrreq;
15610 	mblk_t		*mp_hw;
15611 	boolean_t	success;
15612 	boolean_t	ioctl_aborted = B_FALSE;
15613 	boolean_t	log = B_TRUE;
15614 	ip_stack_t		*ipst;
15615 
15616 	ip1dbg(("ip_rput_dlpi_writer .."));
15617 	ill = (ill_t *)q->q_ptr;
15618 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
15619 	ASSERT(IAM_WRITER_ILL(ill));
15620 
15621 	ipst = ill->ill_ipst;
15622 
15623 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
15624 	/*
15625 	 * The current ioctl could have been aborted by the user and a new
15626 	 * ioctl to bring up another ill could have started. We could still
15627 	 * get a response from the driver later.
15628 	 */
15629 	if (ipif != NULL && ipif->ipif_ill != ill)
15630 		ioctl_aborted = B_TRUE;
15631 
15632 	switch (dloa->dl_primitive) {
15633 	case DL_ERROR_ACK:
15634 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15635 		    dl_primstr(dlea->dl_error_primitive)));
15636 
15637 		switch (dlea->dl_error_primitive) {
15638 		case DL_DISABMULTI_REQ:
15639 			if (!ill->ill_isv6)
15640 				ipsq_current_finish(ipsq);
15641 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15642 			break;
15643 		case DL_PROMISCON_REQ:
15644 		case DL_PROMISCOFF_REQ:
15645 		case DL_UNBIND_REQ:
15646 		case DL_ATTACH_REQ:
15647 		case DL_INFO_REQ:
15648 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15649 			break;
15650 		case DL_NOTIFY_REQ:
15651 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15652 			log = B_FALSE;
15653 			break;
15654 		case DL_PHYS_ADDR_REQ:
15655 			/*
15656 			 * For IPv6 only, there are two additional
15657 			 * phys_addr_req's sent to the driver to get the
15658 			 * IPv6 token and lla. This allows IP to acquire
15659 			 * the hardware address format for a given interface
15660 			 * without having built in knowledge of the hardware
15661 			 * address. ill_phys_addr_pend keeps track of the last
15662 			 * DL_PAR sent so we know which response we are
15663 			 * dealing with. ill_dlpi_done will update
15664 			 * ill_phys_addr_pend when it sends the next req.
15665 			 * We don't complete the IOCTL until all three DL_PARs
15666 			 * have been attempted, so set *_len to 0 and break.
15667 			 */
15668 			paddrreq = ill->ill_phys_addr_pend;
15669 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15670 			if (paddrreq == DL_IPV6_TOKEN) {
15671 				ill->ill_token_length = 0;
15672 				log = B_FALSE;
15673 				break;
15674 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15675 				ill->ill_nd_lla_len = 0;
15676 				log = B_FALSE;
15677 				break;
15678 			}
15679 			/*
15680 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15681 			 * We presumably have an IOCTL hanging out waiting
15682 			 * for completion. Find it and complete the IOCTL
15683 			 * with the error noted.
15684 			 * However, ill_dl_phys was called on an ill queue
15685 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15686 			 * set. But the ioctl is known to be pending on ill_wq.
15687 			 */
15688 			if (!ill->ill_ifname_pending)
15689 				break;
15690 			ill->ill_ifname_pending = 0;
15691 			if (!ioctl_aborted)
15692 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15693 			if (mp1 != NULL) {
15694 				/*
15695 				 * This operation (SIOCSLIFNAME) must have
15696 				 * happened on the ill. Assert there is no conn
15697 				 */
15698 				ASSERT(connp == NULL);
15699 				q = ill->ill_wq;
15700 			}
15701 			break;
15702 		case DL_BIND_REQ:
15703 			ill_dlpi_done(ill, DL_BIND_REQ);
15704 			if (ill->ill_ifname_pending)
15705 				break;
15706 			/*
15707 			 * Something went wrong with the bind.  We presumably
15708 			 * have an IOCTL hanging out waiting for completion.
15709 			 * Find it, take down the interface that was coming
15710 			 * up, and complete the IOCTL with the error noted.
15711 			 */
15712 			if (!ioctl_aborted)
15713 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15714 			if (mp1 != NULL) {
15715 				/*
15716 				 * This operation (SIOCSLIFFLAGS) must have
15717 				 * happened from a conn.
15718 				 */
15719 				ASSERT(connp != NULL);
15720 				q = CONNP_TO_WQ(connp);
15721 				(void) ipif_down(ipif, NULL, NULL);
15722 				/* error is set below the switch */
15723 			}
15724 			break;
15725 		case DL_ENABMULTI_REQ:
15726 			if (!ill->ill_isv6)
15727 				ipsq_current_finish(ipsq);
15728 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15729 
15730 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15731 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15732 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15733 				ipif_t *ipif;
15734 
15735 				printf("ip: joining multicasts failed (%d)"
15736 				    " on %s - will use link layer "
15737 				    "broadcasts for multicast\n",
15738 				    dlea->dl_errno, ill->ill_name);
15739 
15740 				/*
15741 				 * Set up the multicast mapping alone.
15742 				 * writer, so ok to access ill->ill_ipif
15743 				 * without any lock.
15744 				 */
15745 				ipif = ill->ill_ipif;
15746 				mutex_enter(&ill->ill_phyint->phyint_lock);
15747 				ill->ill_phyint->phyint_flags |=
15748 				    PHYI_MULTI_BCAST;
15749 				mutex_exit(&ill->ill_phyint->phyint_lock);
15750 
15751 				if (!ill->ill_isv6) {
15752 					(void) ipif_arp_setup_multicast(ipif,
15753 					    NULL);
15754 				} else {
15755 					(void) ipif_ndp_setup_multicast(ipif,
15756 					    NULL);
15757 				}
15758 			}
15759 			freemsg(mp);	/* Don't want to pass this up */
15760 			return;
15761 		case DL_CONTROL_REQ:
15762 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15763 			    "DL_CONTROL_REQ\n"));
15764 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15765 			freemsg(mp);
15766 			return;
15767 		case DL_CAPABILITY_REQ:
15768 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15769 			    "DL_CAPABILITY REQ\n"));
15770 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
15771 				ill->ill_dlpi_capab_state = IDCS_FAILED;
15772 			ill_capability_done(ill);
15773 			freemsg(mp);
15774 			return;
15775 		}
15776 		/*
15777 		 * Note the error for IOCTL completion (mp1 is set when
15778 		 * ready to complete ioctl). If ill_ifname_pending_err is
15779 		 * set, an error occured during plumbing (ill_ifname_pending),
15780 		 * so we want to report that error.
15781 		 *
15782 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15783 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15784 		 * expected to get errack'd if the driver doesn't support
15785 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15786 		 * if these error conditions are encountered.
15787 		 */
15788 		if (mp1 != NULL) {
15789 			if (ill->ill_ifname_pending_err != 0)  {
15790 				err = ill->ill_ifname_pending_err;
15791 				ill->ill_ifname_pending_err = 0;
15792 			} else {
15793 				err = dlea->dl_unix_errno ?
15794 				    dlea->dl_unix_errno : ENXIO;
15795 			}
15796 		/*
15797 		 * If we're plumbing an interface and an error hasn't already
15798 		 * been saved, set ill_ifname_pending_err to the error passed
15799 		 * up. Ignore the error if log is B_FALSE (see comment above).
15800 		 */
15801 		} else if (log && ill->ill_ifname_pending &&
15802 		    ill->ill_ifname_pending_err == 0) {
15803 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15804 			    dlea->dl_unix_errno : ENXIO;
15805 		}
15806 
15807 		if (log)
15808 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15809 			    dlea->dl_errno, dlea->dl_unix_errno);
15810 		break;
15811 	case DL_CAPABILITY_ACK:
15812 		ill_capability_ack(ill, mp);
15813 		/*
15814 		 * The message has been handed off to ill_capability_ack
15815 		 * and must not be freed below
15816 		 */
15817 		mp = NULL;
15818 		break;
15819 
15820 	case DL_CONTROL_ACK:
15821 		/* We treat all of these as "fire and forget" */
15822 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15823 		break;
15824 	case DL_INFO_ACK:
15825 		/* Call a routine to handle this one. */
15826 		ill_dlpi_done(ill, DL_INFO_REQ);
15827 		ip_ll_subnet_defaults(ill, mp);
15828 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15829 		return;
15830 	case DL_BIND_ACK:
15831 		/*
15832 		 * We should have an IOCTL waiting on this unless
15833 		 * sent by ill_dl_phys, in which case just return
15834 		 */
15835 		ill_dlpi_done(ill, DL_BIND_REQ);
15836 		if (ill->ill_ifname_pending)
15837 			break;
15838 
15839 		if (!ioctl_aborted)
15840 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15841 		if (mp1 == NULL)
15842 			break;
15843 		/*
15844 		 * Because mp1 was added by ill_dl_up(), and it always
15845 		 * passes a valid connp, connp must be valid here.
15846 		 */
15847 		ASSERT(connp != NULL);
15848 		q = CONNP_TO_WQ(connp);
15849 
15850 		/*
15851 		 * We are exclusive. So nothing can change even after
15852 		 * we get the pending mp. If need be we can put it back
15853 		 * and restart, as in calling ipif_arp_up()  below.
15854 		 */
15855 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15856 
15857 		mutex_enter(&ill->ill_lock);
15858 		ill->ill_dl_up = 1;
15859 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
15860 		mutex_exit(&ill->ill_lock);
15861 
15862 		/*
15863 		 * Now bring up the resolver; when that is complete, we'll
15864 		 * create IREs.  Note that we intentionally mirror what
15865 		 * ipif_up() would have done, because we got here by way of
15866 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15867 		 */
15868 		if (ill->ill_isv6) {
15869 			if (ill->ill_flags & ILLF_XRESOLV) {
15870 				mutex_enter(&connp->conn_lock);
15871 				mutex_enter(&ill->ill_lock);
15872 				success = ipsq_pending_mp_add(connp, ipif, q,
15873 				    mp1, 0);
15874 				mutex_exit(&ill->ill_lock);
15875 				mutex_exit(&connp->conn_lock);
15876 				if (success) {
15877 					err = ipif_resolver_up(ipif,
15878 					    Res_act_initial);
15879 					if (err == EINPROGRESS) {
15880 						freemsg(mp);
15881 						return;
15882 					}
15883 					ASSERT(err != 0);
15884 					mp1 = ipsq_pending_mp_get(ipsq, &connp);
15885 					ASSERT(mp1 != NULL);
15886 				} else {
15887 					/* conn has started closing */
15888 					err = EINTR;
15889 				}
15890 			} else { /* Non XRESOLV interface */
15891 				(void) ipif_resolver_up(ipif, Res_act_initial);
15892 				if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
15893 					err = ipif_up_done_v6(ipif);
15894 			}
15895 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15896 			/*
15897 			 * ARP and other v4 external resolvers.
15898 			 * Leave the pending mblk intact so that
15899 			 * the ioctl completes in ip_rput().
15900 			 */
15901 			mutex_enter(&connp->conn_lock);
15902 			mutex_enter(&ill->ill_lock);
15903 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15904 			mutex_exit(&ill->ill_lock);
15905 			mutex_exit(&connp->conn_lock);
15906 			if (success) {
15907 				err = ipif_resolver_up(ipif, Res_act_initial);
15908 				if (err == EINPROGRESS) {
15909 					freemsg(mp);
15910 					return;
15911 				}
15912 				ASSERT(err != 0);
15913 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15914 			} else {
15915 				/* The conn has started closing */
15916 				err = EINTR;
15917 			}
15918 		} else {
15919 			/*
15920 			 * This one is complete. Reply to pending ioctl.
15921 			 */
15922 			(void) ipif_resolver_up(ipif, Res_act_initial);
15923 			err = ipif_up_done(ipif);
15924 		}
15925 
15926 		if ((err == 0) && (ill->ill_up_ipifs)) {
15927 			err = ill_up_ipifs(ill, q, mp1);
15928 			if (err == EINPROGRESS) {
15929 				freemsg(mp);
15930 				return;
15931 			}
15932 		}
15933 
15934 		/*
15935 		 * If we have a moved ipif to bring up, and everything has
15936 		 * succeeded to this point, bring it up on the IPMP ill.
15937 		 * Otherwise, leave it down -- the admin can try to bring it
15938 		 * up by hand if need be.
15939 		 */
15940 		if (ill->ill_move_ipif != NULL) {
15941 			if (err != 0) {
15942 				ill->ill_move_ipif = NULL;
15943 			} else {
15944 				ipif = ill->ill_move_ipif;
15945 				ill->ill_move_ipif = NULL;
15946 				err = ipif_up(ipif, q, mp1);
15947 				if (err == EINPROGRESS) {
15948 					freemsg(mp);
15949 					return;
15950 				}
15951 			}
15952 		}
15953 		break;
15954 
15955 	case DL_NOTIFY_IND: {
15956 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15957 		ire_t *ire;
15958 		uint_t orig_mtu;
15959 		boolean_t need_ire_walk_v4 = B_FALSE;
15960 		boolean_t need_ire_walk_v6 = B_FALSE;
15961 
15962 		switch (notify->dl_notification) {
15963 		case DL_NOTE_PHYS_ADDR:
15964 			err = ill_set_phys_addr(ill, mp);
15965 			break;
15966 
15967 		case DL_NOTE_FASTPATH_FLUSH:
15968 			ill_fastpath_flush(ill);
15969 			break;
15970 
15971 		case DL_NOTE_SDU_SIZE:
15972 			/*
15973 			 * Change the MTU size of the interface, of all
15974 			 * attached ipif's, and of all relevant ire's.  The
15975 			 * new value's a uint32_t at notify->dl_data.
15976 			 * Mtu change Vs. new ire creation - protocol below.
15977 			 *
15978 			 * a Mark the ipif as IPIF_CHANGING.
15979 			 * b Set the new mtu in the ipif.
15980 			 * c Change the ire_max_frag on all affected ires
15981 			 * d Unmark the IPIF_CHANGING
15982 			 *
15983 			 * To see how the protocol works, assume an interface
15984 			 * route is also being added simultaneously by
15985 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15986 			 * the ire. If the ire is created before step a,
15987 			 * it will be cleaned up by step c. If the ire is
15988 			 * created after step d, it will see the new value of
15989 			 * ipif_mtu. Any attempt to create the ire between
15990 			 * steps a to d will fail because of the IPIF_CHANGING
15991 			 * flag. Note that ire_create() is passed a pointer to
15992 			 * the ipif_mtu, and not the value. During ire_add
15993 			 * under the bucket lock, the ire_max_frag of the
15994 			 * new ire being created is set from the ipif/ire from
15995 			 * which it is being derived.
15996 			 */
15997 			mutex_enter(&ill->ill_lock);
15998 
15999 			orig_mtu = ill->ill_max_mtu;
16000 			ill->ill_max_frag = (uint_t)notify->dl_data;
16001 			ill->ill_max_mtu = (uint_t)notify->dl_data;
16002 
16003 			/*
16004 			 * If ill_user_mtu was set (via SIOCSLIFLNKINFO),
16005 			 * clamp ill_max_mtu at it.
16006 			 */
16007 			if (ill->ill_user_mtu != 0 &&
16008 			    ill->ill_user_mtu < ill->ill_max_mtu)
16009 				ill->ill_max_mtu = ill->ill_user_mtu;
16010 
16011 			/*
16012 			 * If the MTU is unchanged, we're done.
16013 			 */
16014 			if (orig_mtu == ill->ill_max_mtu) {
16015 				mutex_exit(&ill->ill_lock);
16016 				break;
16017 			}
16018 
16019 			if (ill->ill_isv6) {
16020 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16021 					ill->ill_max_mtu = IPV6_MIN_MTU;
16022 			} else {
16023 				if (ill->ill_max_mtu < IP_MIN_MTU)
16024 					ill->ill_max_mtu = IP_MIN_MTU;
16025 			}
16026 			for (ipif = ill->ill_ipif; ipif != NULL;
16027 			    ipif = ipif->ipif_next) {
16028 				/*
16029 				 * Don't override the mtu if the user
16030 				 * has explicitly set it.
16031 				 */
16032 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16033 					continue;
16034 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16035 				if (ipif->ipif_isv6)
16036 					ire = ipif_to_ire_v6(ipif);
16037 				else
16038 					ire = ipif_to_ire(ipif);
16039 				if (ire != NULL) {
16040 					ire->ire_max_frag = ipif->ipif_mtu;
16041 					ire_refrele(ire);
16042 				}
16043 				if (ipif->ipif_flags & IPIF_UP) {
16044 					if (ill->ill_isv6)
16045 						need_ire_walk_v6 = B_TRUE;
16046 					else
16047 						need_ire_walk_v4 = B_TRUE;
16048 				}
16049 			}
16050 			mutex_exit(&ill->ill_lock);
16051 			if (need_ire_walk_v4)
16052 				ire_walk_v4(ill_mtu_change, (char *)ill,
16053 				    ALL_ZONES, ipst);
16054 			if (need_ire_walk_v6)
16055 				ire_walk_v6(ill_mtu_change, (char *)ill,
16056 				    ALL_ZONES, ipst);
16057 
16058 			/*
16059 			 * Refresh IPMP meta-interface MTU if necessary.
16060 			 */
16061 			if (IS_UNDER_IPMP(ill))
16062 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
16063 			break;
16064 
16065 		case DL_NOTE_LINK_UP:
16066 		case DL_NOTE_LINK_DOWN: {
16067 			/*
16068 			 * We are writer. ill / phyint / ipsq assocs stable.
16069 			 * The RUNNING flag reflects the state of the link.
16070 			 */
16071 			phyint_t *phyint = ill->ill_phyint;
16072 			uint64_t new_phyint_flags;
16073 			boolean_t changed = B_FALSE;
16074 			boolean_t went_up;
16075 
16076 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16077 			mutex_enter(&phyint->phyint_lock);
16078 
16079 			new_phyint_flags = went_up ?
16080 			    phyint->phyint_flags | PHYI_RUNNING :
16081 			    phyint->phyint_flags & ~PHYI_RUNNING;
16082 
16083 			if (IS_IPMP(ill)) {
16084 				new_phyint_flags = went_up ?
16085 				    new_phyint_flags & ~PHYI_FAILED :
16086 				    new_phyint_flags | PHYI_FAILED;
16087 			}
16088 
16089 			if (new_phyint_flags != phyint->phyint_flags) {
16090 				phyint->phyint_flags = new_phyint_flags;
16091 				changed = B_TRUE;
16092 			}
16093 			mutex_exit(&phyint->phyint_lock);
16094 			/*
16095 			 * ill_restart_dad handles the DAD restart and routing
16096 			 * socket notification logic.
16097 			 */
16098 			if (changed) {
16099 				ill_restart_dad(phyint->phyint_illv4, went_up);
16100 				ill_restart_dad(phyint->phyint_illv6, went_up);
16101 			}
16102 			break;
16103 		}
16104 		case DL_NOTE_PROMISC_ON_PHYS:
16105 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16106 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16107 			mutex_enter(&ill->ill_lock);
16108 			ill->ill_promisc_on_phys = B_TRUE;
16109 			mutex_exit(&ill->ill_lock);
16110 			break;
16111 		case DL_NOTE_PROMISC_OFF_PHYS:
16112 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16113 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16114 			mutex_enter(&ill->ill_lock);
16115 			ill->ill_promisc_on_phys = B_FALSE;
16116 			mutex_exit(&ill->ill_lock);
16117 			break;
16118 		case DL_NOTE_CAPAB_RENEG:
16119 			/*
16120 			 * Something changed on the driver side.
16121 			 * It wants us to renegotiate the capabilities
16122 			 * on this ill. One possible cause is the aggregation
16123 			 * interface under us where a port got added or
16124 			 * went away.
16125 			 *
16126 			 * If the capability negotiation is already done
16127 			 * or is in progress, reset the capabilities and
16128 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16129 			 * so that when the ack comes back, we can start
16130 			 * the renegotiation process.
16131 			 *
16132 			 * Note that if ill_capab_reneg is already B_TRUE
16133 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16134 			 * the capability resetting request has been sent
16135 			 * and the renegotiation has not been started yet;
16136 			 * nothing needs to be done in this case.
16137 			 */
16138 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
16139 			ill_capability_reset(ill, B_TRUE);
16140 			ipsq_current_finish(ipsq);
16141 			break;
16142 		default:
16143 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16144 			    "type 0x%x for DL_NOTIFY_IND\n",
16145 			    notify->dl_notification));
16146 			break;
16147 		}
16148 
16149 		/*
16150 		 * As this is an asynchronous operation, we
16151 		 * should not call ill_dlpi_done
16152 		 */
16153 		break;
16154 	}
16155 	case DL_NOTIFY_ACK: {
16156 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16157 
16158 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16159 			ill->ill_note_link = 1;
16160 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16161 		break;
16162 	}
16163 	case DL_PHYS_ADDR_ACK: {
16164 		/*
16165 		 * As part of plumbing the interface via SIOCSLIFNAME,
16166 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16167 		 * whose answers we receive here.  As each answer is received,
16168 		 * we call ill_dlpi_done() to dispatch the next request as
16169 		 * we're processing the current one.  Once all answers have
16170 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16171 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16172 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16173 		 * available, but we know the ioctl is pending on ill_wq.)
16174 		 */
16175 		uint_t	paddrlen, paddroff;
16176 
16177 		paddrreq = ill->ill_phys_addr_pend;
16178 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16179 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16180 
16181 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16182 		if (paddrreq == DL_IPV6_TOKEN) {
16183 			/*
16184 			 * bcopy to low-order bits of ill_token
16185 			 *
16186 			 * XXX Temporary hack - currently, all known tokens
16187 			 * are 64 bits, so I'll cheat for the moment.
16188 			 */
16189 			bcopy(mp->b_rptr + paddroff,
16190 			    &ill->ill_token.s6_addr32[2], paddrlen);
16191 			ill->ill_token_length = paddrlen;
16192 			break;
16193 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16194 			ASSERT(ill->ill_nd_lla_mp == NULL);
16195 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16196 			mp = NULL;
16197 			break;
16198 		}
16199 
16200 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16201 		ASSERT(ill->ill_phys_addr_mp == NULL);
16202 		if (!ill->ill_ifname_pending)
16203 			break;
16204 		ill->ill_ifname_pending = 0;
16205 		if (!ioctl_aborted)
16206 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16207 		if (mp1 != NULL) {
16208 			ASSERT(connp == NULL);
16209 			q = ill->ill_wq;
16210 		}
16211 		/*
16212 		 * If any error acks received during the plumbing sequence,
16213 		 * ill_ifname_pending_err will be set. Break out and send up
16214 		 * the error to the pending ioctl.
16215 		 */
16216 		if (ill->ill_ifname_pending_err != 0) {
16217 			err = ill->ill_ifname_pending_err;
16218 			ill->ill_ifname_pending_err = 0;
16219 			break;
16220 		}
16221 
16222 		ill->ill_phys_addr_mp = mp;
16223 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16224 		mp = NULL;
16225 
16226 		/*
16227 		 * If paddrlen is zero, the DLPI provider doesn't support
16228 		 * physical addresses.  The other two tests were historical
16229 		 * workarounds for bugs in our former PPP implementation, but
16230 		 * now other things have grown dependencies on them -- e.g.,
16231 		 * the tun module specifies a dl_addr_length of zero in its
16232 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16233 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16234 		 * but only after careful testing ensures that all dependent
16235 		 * broken DLPI providers have been fixed.
16236 		 */
16237 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16238 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16239 			ill->ill_phys_addr = NULL;
16240 		} else if (paddrlen != ill->ill_phys_addr_length) {
16241 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16242 			    paddrlen, ill->ill_phys_addr_length));
16243 			err = EINVAL;
16244 			break;
16245 		}
16246 
16247 		if (ill->ill_nd_lla_mp == NULL) {
16248 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16249 				err = ENOMEM;
16250 				break;
16251 			}
16252 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16253 		}
16254 
16255 		/*
16256 		 * Set the interface token.  If the zeroth interface address
16257 		 * is unspecified, then set it to the link local address.
16258 		 */
16259 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16260 			(void) ill_setdefaulttoken(ill);
16261 
16262 		ASSERT(ill->ill_ipif->ipif_id == 0);
16263 		if (ipif != NULL &&
16264 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16265 			(void) ipif_setlinklocal(ipif);
16266 		}
16267 		break;
16268 	}
16269 	case DL_OK_ACK:
16270 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16271 		    dl_primstr((int)dloa->dl_correct_primitive),
16272 		    dloa->dl_correct_primitive));
16273 		switch (dloa->dl_correct_primitive) {
16274 		case DL_ENABMULTI_REQ:
16275 		case DL_DISABMULTI_REQ:
16276 			if (!ill->ill_isv6)
16277 				ipsq_current_finish(ipsq);
16278 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16279 			break;
16280 		case DL_PROMISCON_REQ:
16281 		case DL_PROMISCOFF_REQ:
16282 		case DL_UNBIND_REQ:
16283 		case DL_ATTACH_REQ:
16284 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16285 			break;
16286 		}
16287 		break;
16288 	default:
16289 		break;
16290 	}
16291 
16292 	freemsg(mp);
16293 	if (mp1 == NULL)
16294 		return;
16295 
16296 	/*
16297 	 * The operation must complete without EINPROGRESS since
16298 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
16299 	 * the operation will be stuck forever inside the IPSQ.
16300 	 */
16301 	ASSERT(err != EINPROGRESS);
16302 
16303 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
16304 	case 0:
16305 		ipsq_current_finish(ipsq);
16306 		break;
16307 
16308 	case SIOCSLIFNAME:
16309 	case IF_UNITSEL: {
16310 		ill_t *ill_other = ILL_OTHER(ill);
16311 
16312 		/*
16313 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
16314 		 * ill has a peer which is in an IPMP group, then place ill
16315 		 * into the same group.  One catch: although ifconfig plumbs
16316 		 * the appropriate IPMP meta-interface prior to plumbing this
16317 		 * ill, it is possible for multiple ifconfig applications to
16318 		 * race (or for another application to adjust plumbing), in
16319 		 * which case the IPMP meta-interface we need will be missing.
16320 		 * If so, kick the phyint out of the group.
16321 		 */
16322 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
16323 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
16324 			ipmp_illgrp_t	*illg;
16325 
16326 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
16327 			if (illg == NULL)
16328 				ipmp_phyint_leave_grp(ill->ill_phyint);
16329 			else
16330 				ipmp_ill_join_illgrp(ill, illg);
16331 		}
16332 
16333 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
16334 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16335 		else
16336 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16337 		break;
16338 	}
16339 	case SIOCLIFADDIF:
16340 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16341 		break;
16342 
16343 	default:
16344 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16345 		break;
16346 	}
16347 }
16348 
16349 /*
16350  * ip_rput_other is called by ip_rput to handle messages modifying the global
16351  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16352  */
16353 /* ARGSUSED */
16354 void
16355 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16356 {
16357 	ill_t		*ill = q->q_ptr;
16358 	struct iocblk	*iocp;
16359 	mblk_t		*mp1;
16360 	conn_t		*connp = NULL;
16361 
16362 	ip1dbg(("ip_rput_other "));
16363 	if (ipsq != NULL) {
16364 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16365 		ASSERT(ipsq->ipsq_xop ==
16366 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
16367 	}
16368 
16369 	switch (mp->b_datap->db_type) {
16370 	case M_ERROR:
16371 	case M_HANGUP:
16372 		/*
16373 		 * The device has a problem.  We force the ILL down.  It can
16374 		 * be brought up again manually using SIOCSIFFLAGS (via
16375 		 * ifconfig or equivalent).
16376 		 */
16377 		ASSERT(ipsq != NULL);
16378 		if (mp->b_rptr < mp->b_wptr)
16379 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16380 		if (ill->ill_error == 0)
16381 			ill->ill_error = ENXIO;
16382 		if (!ill_down_start(q, mp))
16383 			return;
16384 		ipif_all_down_tail(ipsq, q, mp, NULL);
16385 		break;
16386 	case M_IOCACK:
16387 		iocp = (struct iocblk *)mp->b_rptr;
16388 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16389 		switch (iocp->ioc_cmd) {
16390 		case SIOCSTUNPARAM:
16391 		case OSIOCSTUNPARAM:
16392 			ASSERT(ipsq != NULL);
16393 			/*
16394 			 * Finish socket ioctl passed through to tun.
16395 			 * We should have an IOCTL waiting on this.
16396 			 */
16397 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16398 			if (ill->ill_isv6) {
16399 				struct iftun_req *ta;
16400 
16401 				/*
16402 				 * if a source or destination is
16403 				 * being set, try and set the link
16404 				 * local address for the tunnel
16405 				 */
16406 				ta = (struct iftun_req *)mp->b_cont->
16407 				    b_cont->b_rptr;
16408 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16409 					ipif_set_tun_llink(ill, ta);
16410 				}
16411 
16412 			}
16413 			if (mp1 != NULL) {
16414 				/*
16415 				 * Now copy back the b_next/b_prev used by
16416 				 * mi code for the mi_copy* functions.
16417 				 * See ip_sioctl_tunparam() for the reason.
16418 				 * Also protect against missing b_cont.
16419 				 */
16420 				if (mp->b_cont != NULL) {
16421 					mp->b_cont->b_next =
16422 					    mp1->b_cont->b_next;
16423 					mp->b_cont->b_prev =
16424 					    mp1->b_cont->b_prev;
16425 				}
16426 				inet_freemsg(mp1);
16427 				ASSERT(connp != NULL);
16428 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16429 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16430 			} else {
16431 				ASSERT(connp == NULL);
16432 				putnext(q, mp);
16433 			}
16434 			break;
16435 		case SIOCGTUNPARAM:
16436 		case OSIOCGTUNPARAM:
16437 			/*
16438 			 * This is really M_IOCDATA from the tunnel driver.
16439 			 * convert back and complete the ioctl.
16440 			 * We should have an IOCTL waiting on this.
16441 			 */
16442 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16443 			if (mp1) {
16444 				/*
16445 				 * Now copy back the b_next/b_prev used by
16446 				 * mi code for the mi_copy* functions.
16447 				 * See ip_sioctl_tunparam() for the reason.
16448 				 * Also protect against missing b_cont.
16449 				 */
16450 				if (mp->b_cont != NULL) {
16451 					mp->b_cont->b_next =
16452 					    mp1->b_cont->b_next;
16453 					mp->b_cont->b_prev =
16454 					    mp1->b_cont->b_prev;
16455 				}
16456 				inet_freemsg(mp1);
16457 				if (iocp->ioc_error == 0)
16458 					mp->b_datap->db_type = M_IOCDATA;
16459 				ASSERT(connp != NULL);
16460 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16461 				    iocp->ioc_error, COPYOUT, NULL);
16462 			} else {
16463 				ASSERT(connp == NULL);
16464 				putnext(q, mp);
16465 			}
16466 			break;
16467 		default:
16468 			break;
16469 		}
16470 		break;
16471 	case M_IOCNAK:
16472 		iocp = (struct iocblk *)mp->b_rptr;
16473 
16474 		switch (iocp->ioc_cmd) {
16475 			int mode;
16476 
16477 		case DL_IOC_HDR_INFO:
16478 			/*
16479 			 * If this was the first attempt, turn off the
16480 			 * fastpath probing.
16481 			 */
16482 			mutex_enter(&ill->ill_lock);
16483 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16484 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16485 				mutex_exit(&ill->ill_lock);
16486 				ill_fastpath_nack(ill);
16487 				ip1dbg(("ip_rput: DLPI fastpath off on "
16488 				    "interface %s\n",
16489 				    ill->ill_name));
16490 			} else {
16491 				mutex_exit(&ill->ill_lock);
16492 			}
16493 			freemsg(mp);
16494 			break;
16495 			case SIOCSTUNPARAM:
16496 		case OSIOCSTUNPARAM:
16497 			ASSERT(ipsq != NULL);
16498 			/*
16499 			 * Finish socket ioctl passed through to tun
16500 			 * We should have an IOCTL waiting on this.
16501 			 */
16502 			/* FALLTHRU */
16503 		case SIOCGTUNPARAM:
16504 		case OSIOCGTUNPARAM:
16505 			/*
16506 			 * This is really M_IOCDATA from the tunnel driver.
16507 			 * convert back and complete the ioctl.
16508 			 * We should have an IOCTL waiting on this.
16509 			 */
16510 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16511 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16512 				mp1 = ill_pending_mp_get(ill, &connp,
16513 				    iocp->ioc_id);
16514 				mode = COPYOUT;
16515 				ipsq = NULL;
16516 			} else {
16517 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16518 				mode = NO_COPYOUT;
16519 			}
16520 			if (mp1 != NULL) {
16521 				/*
16522 				 * Now copy back the b_next/b_prev used by
16523 				 * mi code for the mi_copy* functions.
16524 				 * See ip_sioctl_tunparam() for the reason.
16525 				 * Also protect against missing b_cont.
16526 				 */
16527 				if (mp->b_cont != NULL) {
16528 					mp->b_cont->b_next =
16529 					    mp1->b_cont->b_next;
16530 					mp->b_cont->b_prev =
16531 					    mp1->b_cont->b_prev;
16532 				}
16533 				inet_freemsg(mp1);
16534 				if (iocp->ioc_error == 0)
16535 					iocp->ioc_error = EINVAL;
16536 				ASSERT(connp != NULL);
16537 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16538 				    iocp->ioc_error, mode, ipsq);
16539 			} else {
16540 				ASSERT(connp == NULL);
16541 				putnext(q, mp);
16542 			}
16543 			break;
16544 		default:
16545 			break;
16546 		}
16547 	default:
16548 		break;
16549 	}
16550 }
16551 
16552 /*
16553  * NOTE : This function does not ire_refrele the ire argument passed in.
16554  *
16555  * IPQoS notes
16556  * IP policy is invoked twice for a forwarded packet, once on the read side
16557  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16558  * enabled. An additional parameter, in_ill, has been added for this purpose.
16559  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16560  * because ip_mroute drops this information.
16561  *
16562  */
16563 void
16564 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16565 {
16566 	uint32_t	old_pkt_len;
16567 	uint32_t	pkt_len;
16568 	queue_t	*q;
16569 	uint32_t	sum;
16570 #define	rptr	((uchar_t *)ipha)
16571 	uint32_t	max_frag;
16572 	uint32_t	ill_index;
16573 	ill_t		*out_ill;
16574 	mib2_ipIfStatsEntry_t *mibptr;
16575 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16576 
16577 	/* Get the ill_index of the incoming ILL */
16578 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16579 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16580 
16581 	/* Initiate Read side IPPF processing */
16582 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16583 		ip_process(IPP_FWD_IN, &mp, ill_index);
16584 		if (mp == NULL) {
16585 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16586 			    "during IPPF processing\n"));
16587 			return;
16588 		}
16589 	}
16590 
16591 	/* Adjust the checksum to reflect the ttl decrement. */
16592 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16593 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16594 
16595 	if (ipha->ipha_ttl-- <= 1) {
16596 		if (ip_csum_hdr(ipha)) {
16597 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16598 			goto drop_pkt;
16599 		}
16600 		/*
16601 		 * Note: ire_stq this will be NULL for multicast
16602 		 * datagrams using the long path through arp (the IRE
16603 		 * is not an IRE_CACHE). This should not cause
16604 		 * problems since we don't generate ICMP errors for
16605 		 * multicast packets.
16606 		 */
16607 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16608 		q = ire->ire_stq;
16609 		if (q != NULL) {
16610 			/* Sent by forwarding path, and router is global zone */
16611 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16612 			    GLOBAL_ZONEID, ipst);
16613 		} else
16614 			freemsg(mp);
16615 		return;
16616 	}
16617 
16618 	/*
16619 	 * Don't forward if the interface is down
16620 	 */
16621 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16622 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16623 		ip2dbg(("ip_rput_forward:interface is down\n"));
16624 		goto drop_pkt;
16625 	}
16626 
16627 	/* Get the ill_index of the outgoing ILL */
16628 	out_ill = ire_to_ill(ire);
16629 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16630 
16631 	DTRACE_PROBE4(ip4__forwarding__start,
16632 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16633 
16634 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16635 	    ipst->ips_ipv4firewall_forwarding,
16636 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16637 
16638 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16639 
16640 	if (mp == NULL)
16641 		return;
16642 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16643 
16644 	if (is_system_labeled()) {
16645 		mblk_t *mp1;
16646 
16647 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16648 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16649 			goto drop_pkt;
16650 		}
16651 		/* Size may have changed */
16652 		mp = mp1;
16653 		ipha = (ipha_t *)mp->b_rptr;
16654 		pkt_len = ntohs(ipha->ipha_length);
16655 	}
16656 
16657 	/* Check if there are options to update */
16658 	if (!IS_SIMPLE_IPH(ipha)) {
16659 		if (ip_csum_hdr(ipha)) {
16660 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16661 			goto drop_pkt;
16662 		}
16663 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16664 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16665 			return;
16666 		}
16667 
16668 		ipha->ipha_hdr_checksum = 0;
16669 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16670 	}
16671 	max_frag = ire->ire_max_frag;
16672 	if (pkt_len > max_frag) {
16673 		/*
16674 		 * It needs fragging on its way out.  We haven't
16675 		 * verified the header checksum yet.  Since we
16676 		 * are going to put a surely good checksum in the
16677 		 * outgoing header, we have to make sure that it
16678 		 * was good coming in.
16679 		 */
16680 		if (ip_csum_hdr(ipha)) {
16681 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16682 			goto drop_pkt;
16683 		}
16684 		/* Initiate Write side IPPF processing */
16685 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16686 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16687 			if (mp == NULL) {
16688 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16689 				    " during IPPF processing\n"));
16690 				return;
16691 			}
16692 		}
16693 		/*
16694 		 * Handle labeled packet resizing.
16695 		 *
16696 		 * If we have added a label, inform ip_wput_frag() of its
16697 		 * effect on the MTU for ICMP messages.
16698 		 */
16699 		if (pkt_len > old_pkt_len) {
16700 			uint32_t secopt_size;
16701 
16702 			secopt_size = pkt_len - old_pkt_len;
16703 			if (secopt_size < max_frag)
16704 				max_frag -= secopt_size;
16705 		}
16706 
16707 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0,
16708 		    GLOBAL_ZONEID, ipst, NULL);
16709 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16710 		return;
16711 	}
16712 
16713 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16714 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16715 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16716 	    ipst->ips_ipv4firewall_physical_out,
16717 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16718 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16719 	if (mp == NULL)
16720 		return;
16721 
16722 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16723 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16724 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE, NULL);
16725 	/* ip_xmit_v4 always consumes the packet */
16726 	return;
16727 
16728 drop_pkt:;
16729 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16730 	freemsg(mp);
16731 #undef	rptr
16732 }
16733 
16734 void
16735 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16736 {
16737 	ire_t	*ire;
16738 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16739 
16740 	ASSERT(!ipif->ipif_isv6);
16741 	/*
16742 	 * Find an IRE which matches the destination and the outgoing
16743 	 * queue in the cache table. All we need is an IRE_CACHE which
16744 	 * is pointing at ipif->ipif_ill.
16745 	 */
16746 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16747 		dst = ipif->ipif_pp_dst_addr;
16748 
16749 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16750 	    MATCH_IRE_ILL | MATCH_IRE_SECATTR, ipst);
16751 	if (ire == NULL) {
16752 		/*
16753 		 * Mark this packet to make it be delivered to
16754 		 * ip_rput_forward after the new ire has been
16755 		 * created.
16756 		 */
16757 		mp->b_prev = NULL;
16758 		mp->b_next = mp;
16759 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16760 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16761 	} else {
16762 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16763 		IRE_REFRELE(ire);
16764 	}
16765 }
16766 
16767 /* Update any source route, record route or timestamp options */
16768 static int
16769 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16770 {
16771 	ipoptp_t	opts;
16772 	uchar_t		*opt;
16773 	uint8_t		optval;
16774 	uint8_t		optlen;
16775 	ipaddr_t	dst;
16776 	uint32_t	ts;
16777 	ire_t		*dst_ire = NULL;
16778 	ire_t		*tmp_ire = NULL;
16779 	timestruc_t	now;
16780 
16781 	ip2dbg(("ip_rput_forward_options\n"));
16782 	dst = ipha->ipha_dst;
16783 	for (optval = ipoptp_first(&opts, ipha);
16784 	    optval != IPOPT_EOL;
16785 	    optval = ipoptp_next(&opts)) {
16786 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16787 		opt = opts.ipoptp_cur;
16788 		optlen = opts.ipoptp_len;
16789 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16790 		    optval, opts.ipoptp_len));
16791 		switch (optval) {
16792 			uint32_t off;
16793 		case IPOPT_SSRR:
16794 		case IPOPT_LSRR:
16795 			/* Check if adminstratively disabled */
16796 			if (!ipst->ips_ip_forward_src_routed) {
16797 				if (ire->ire_stq != NULL) {
16798 					/*
16799 					 * Sent by forwarding path, and router
16800 					 * is global zone
16801 					 */
16802 					icmp_unreachable(ire->ire_stq, mp,
16803 					    ICMP_SOURCE_ROUTE_FAILED,
16804 					    GLOBAL_ZONEID, ipst);
16805 				} else {
16806 					ip0dbg(("ip_rput_forward_options: "
16807 					    "unable to send unreach\n"));
16808 					freemsg(mp);
16809 				}
16810 				return (-1);
16811 			}
16812 
16813 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16814 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16815 			if (dst_ire == NULL) {
16816 				/*
16817 				 * Must be partial since ip_rput_options
16818 				 * checked for strict.
16819 				 */
16820 				break;
16821 			}
16822 			off = opt[IPOPT_OFFSET];
16823 			off--;
16824 		redo_srr:
16825 			if (optlen < IP_ADDR_LEN ||
16826 			    off > optlen - IP_ADDR_LEN) {
16827 				/* End of source route */
16828 				ip1dbg((
16829 				    "ip_rput_forward_options: end of SR\n"));
16830 				ire_refrele(dst_ire);
16831 				break;
16832 			}
16833 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16834 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16835 			    IP_ADDR_LEN);
16836 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16837 			    ntohl(dst)));
16838 
16839 			/*
16840 			 * Check if our address is present more than
16841 			 * once as consecutive hops in source route.
16842 			 */
16843 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16844 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16845 			if (tmp_ire != NULL) {
16846 				ire_refrele(tmp_ire);
16847 				off += IP_ADDR_LEN;
16848 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16849 				goto redo_srr;
16850 			}
16851 			ipha->ipha_dst = dst;
16852 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16853 			ire_refrele(dst_ire);
16854 			break;
16855 		case IPOPT_RR:
16856 			off = opt[IPOPT_OFFSET];
16857 			off--;
16858 			if (optlen < IP_ADDR_LEN ||
16859 			    off > optlen - IP_ADDR_LEN) {
16860 				/* No more room - ignore */
16861 				ip1dbg((
16862 				    "ip_rput_forward_options: end of RR\n"));
16863 				break;
16864 			}
16865 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16866 			    IP_ADDR_LEN);
16867 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16868 			break;
16869 		case IPOPT_TS:
16870 			/* Insert timestamp if there is room */
16871 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16872 			case IPOPT_TS_TSONLY:
16873 				off = IPOPT_TS_TIMELEN;
16874 				break;
16875 			case IPOPT_TS_PRESPEC:
16876 			case IPOPT_TS_PRESPEC_RFC791:
16877 				/* Verify that the address matched */
16878 				off = opt[IPOPT_OFFSET] - 1;
16879 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16880 				dst_ire = ire_ctable_lookup(dst, 0,
16881 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16882 				    MATCH_IRE_TYPE, ipst);
16883 				if (dst_ire == NULL) {
16884 					/* Not for us */
16885 					break;
16886 				}
16887 				ire_refrele(dst_ire);
16888 				/* FALLTHRU */
16889 			case IPOPT_TS_TSANDADDR:
16890 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16891 				break;
16892 			default:
16893 				/*
16894 				 * ip_*put_options should have already
16895 				 * dropped this packet.
16896 				 */
16897 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16898 				    "unknown IT - bug in ip_rput_options?\n");
16899 				return (0);	/* Keep "lint" happy */
16900 			}
16901 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16902 				/* Increase overflow counter */
16903 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16904 				opt[IPOPT_POS_OV_FLG] =
16905 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16906 				    (off << 4));
16907 				break;
16908 			}
16909 			off = opt[IPOPT_OFFSET] - 1;
16910 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16911 			case IPOPT_TS_PRESPEC:
16912 			case IPOPT_TS_PRESPEC_RFC791:
16913 			case IPOPT_TS_TSANDADDR:
16914 				bcopy(&ire->ire_src_addr,
16915 				    (char *)opt + off, IP_ADDR_LEN);
16916 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16917 				/* FALLTHRU */
16918 			case IPOPT_TS_TSONLY:
16919 				off = opt[IPOPT_OFFSET] - 1;
16920 				/* Compute # of milliseconds since midnight */
16921 				gethrestime(&now);
16922 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16923 				    now.tv_nsec / (NANOSEC / MILLISEC);
16924 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16925 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16926 				break;
16927 			}
16928 			break;
16929 		}
16930 	}
16931 	return (0);
16932 }
16933 
16934 /*
16935  * This is called after processing at least one of AH/ESP headers.
16936  *
16937  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16938  * the actual, physical interface on which the packet was received,
16939  * but, when ip_strict_dst_multihoming is set to 1, could be the
16940  * interface which had the ipha_dst configured when the packet went
16941  * through ip_rput. The ill_index corresponding to the recv_ill
16942  * is saved in ipsec_in_rill_index
16943  *
16944  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16945  * cannot assume "ire" points to valid data for any IPv6 cases.
16946  */
16947 void
16948 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16949 {
16950 	mblk_t *mp;
16951 	ipaddr_t dst;
16952 	in6_addr_t *v6dstp;
16953 	ipha_t *ipha;
16954 	ip6_t *ip6h;
16955 	ipsec_in_t *ii;
16956 	boolean_t ill_need_rele = B_FALSE;
16957 	boolean_t rill_need_rele = B_FALSE;
16958 	boolean_t ire_need_rele = B_FALSE;
16959 	netstack_t	*ns;
16960 	ip_stack_t	*ipst;
16961 
16962 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16963 	ASSERT(ii->ipsec_in_ill_index != 0);
16964 	ns = ii->ipsec_in_ns;
16965 	ASSERT(ii->ipsec_in_ns != NULL);
16966 	ipst = ns->netstack_ip;
16967 
16968 	mp = ipsec_mp->b_cont;
16969 	ASSERT(mp != NULL);
16970 
16971 
16972 	if (ill == NULL) {
16973 		ASSERT(recv_ill == NULL);
16974 		/*
16975 		 * We need to get the original queue on which ip_rput_local
16976 		 * or ip_rput_data_v6 was called.
16977 		 */
16978 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16979 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16980 		ill_need_rele = B_TRUE;
16981 
16982 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16983 			recv_ill = ill_lookup_on_ifindex(
16984 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16985 			    NULL, NULL, NULL, NULL, ipst);
16986 			rill_need_rele = B_TRUE;
16987 		} else {
16988 			recv_ill = ill;
16989 		}
16990 
16991 		if ((ill == NULL) || (recv_ill == NULL)) {
16992 			ip0dbg(("ip_fanout_proto_again: interface "
16993 			    "disappeared\n"));
16994 			if (ill != NULL)
16995 				ill_refrele(ill);
16996 			if (recv_ill != NULL)
16997 				ill_refrele(recv_ill);
16998 			freemsg(ipsec_mp);
16999 			return;
17000 		}
17001 	}
17002 
17003 	ASSERT(ill != NULL && recv_ill != NULL);
17004 
17005 	if (mp->b_datap->db_type == M_CTL) {
17006 		/*
17007 		 * AH/ESP is returning the ICMP message after
17008 		 * removing their headers. Fanout again till
17009 		 * it gets to the right protocol.
17010 		 */
17011 		if (ii->ipsec_in_v4) {
17012 			icmph_t *icmph;
17013 			int iph_hdr_length;
17014 			int hdr_length;
17015 
17016 			ipha = (ipha_t *)mp->b_rptr;
17017 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17018 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17019 			ipha = (ipha_t *)&icmph[1];
17020 			hdr_length = IPH_HDR_LENGTH(ipha);
17021 			/*
17022 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17023 			 * Reset the type to M_DATA.
17024 			 */
17025 			mp->b_datap->db_type = M_DATA;
17026 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17027 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17028 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17029 		} else {
17030 			icmp6_t *icmp6;
17031 			int hdr_length;
17032 
17033 			ip6h = (ip6_t *)mp->b_rptr;
17034 			/* Don't call hdr_length_v6() unless you have to. */
17035 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17036 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17037 			else
17038 				hdr_length = IPV6_HDR_LEN;
17039 
17040 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17041 			/*
17042 			 * icmp_inbound_error_fanout_v6 may need to do
17043 			 * pullupmsg.  Reset the type to M_DATA.
17044 			 */
17045 			mp->b_datap->db_type = M_DATA;
17046 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17047 			    ip6h, icmp6, ill, recv_ill, B_TRUE,
17048 			    ii->ipsec_in_zoneid);
17049 		}
17050 		if (ill_need_rele)
17051 			ill_refrele(ill);
17052 		if (rill_need_rele)
17053 			ill_refrele(recv_ill);
17054 		return;
17055 	}
17056 
17057 	if (ii->ipsec_in_v4) {
17058 		ipha = (ipha_t *)mp->b_rptr;
17059 		dst = ipha->ipha_dst;
17060 		if (CLASSD(dst)) {
17061 			/*
17062 			 * Multicast has to be delivered to all streams.
17063 			 */
17064 			dst = INADDR_BROADCAST;
17065 		}
17066 
17067 		if (ire == NULL) {
17068 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17069 			    MBLK_GETLABEL(mp), ipst);
17070 			if (ire == NULL) {
17071 				if (ill_need_rele)
17072 					ill_refrele(ill);
17073 				if (rill_need_rele)
17074 					ill_refrele(recv_ill);
17075 				ip1dbg(("ip_fanout_proto_again: "
17076 				    "IRE not found"));
17077 				freemsg(ipsec_mp);
17078 				return;
17079 			}
17080 			ire_need_rele = B_TRUE;
17081 		}
17082 
17083 		switch (ipha->ipha_protocol) {
17084 		case IPPROTO_UDP:
17085 			ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17086 			    recv_ill);
17087 			if (ire_need_rele)
17088 				ire_refrele(ire);
17089 			break;
17090 		case IPPROTO_TCP:
17091 			if (!ire_need_rele)
17092 				IRE_REFHOLD(ire);
17093 			mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17094 			    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17095 			IRE_REFRELE(ire);
17096 			if (mp != NULL) {
17097 				SQUEUE_ENTER(GET_SQUEUE(mp), mp,
17098 				    mp, 1, SQ_PROCESS,
17099 				    SQTAG_IP_PROTO_AGAIN);
17100 			}
17101 			break;
17102 		case IPPROTO_SCTP:
17103 			if (!ire_need_rele)
17104 				IRE_REFHOLD(ire);
17105 			ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17106 			    ipsec_mp, 0, ill->ill_rq, dst);
17107 			break;
17108 		default:
17109 			ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17110 			    recv_ill, 0);
17111 			if (ire_need_rele)
17112 				ire_refrele(ire);
17113 			break;
17114 		}
17115 	} else {
17116 		uint32_t rput_flags = 0;
17117 
17118 		ip6h = (ip6_t *)mp->b_rptr;
17119 		v6dstp = &ip6h->ip6_dst;
17120 		/*
17121 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17122 		 * address.
17123 		 *
17124 		 * Currently, we don't store that state in the IPSEC_IN
17125 		 * message, and we may need to.
17126 		 */
17127 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17128 		    IP6_IN_LLMCAST : 0);
17129 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17130 		    NULL, NULL);
17131 	}
17132 	if (ill_need_rele)
17133 		ill_refrele(ill);
17134 	if (rill_need_rele)
17135 		ill_refrele(recv_ill);
17136 }
17137 
17138 /*
17139  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17140  * returns 'true' if there are still fragments left on the queue, in
17141  * which case we restart the timer.
17142  */
17143 void
17144 ill_frag_timer(void *arg)
17145 {
17146 	ill_t	*ill = (ill_t *)arg;
17147 	boolean_t frag_pending;
17148 	ip_stack_t	*ipst = ill->ill_ipst;
17149 
17150 	mutex_enter(&ill->ill_lock);
17151 	ASSERT(!ill->ill_fragtimer_executing);
17152 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17153 		ill->ill_frag_timer_id = 0;
17154 		mutex_exit(&ill->ill_lock);
17155 		return;
17156 	}
17157 	ill->ill_fragtimer_executing = 1;
17158 	mutex_exit(&ill->ill_lock);
17159 
17160 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17161 
17162 	/*
17163 	 * Restart the timer, if we have fragments pending or if someone
17164 	 * wanted us to be scheduled again.
17165 	 */
17166 	mutex_enter(&ill->ill_lock);
17167 	ill->ill_fragtimer_executing = 0;
17168 	ill->ill_frag_timer_id = 0;
17169 	if (frag_pending || ill->ill_fragtimer_needrestart)
17170 		ill_frag_timer_start(ill);
17171 	mutex_exit(&ill->ill_lock);
17172 }
17173 
17174 void
17175 ill_frag_timer_start(ill_t *ill)
17176 {
17177 	ip_stack_t	*ipst = ill->ill_ipst;
17178 
17179 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17180 
17181 	/* If the ill is closing or opening don't proceed */
17182 	if (ill->ill_state_flags & ILL_CONDEMNED)
17183 		return;
17184 
17185 	if (ill->ill_fragtimer_executing) {
17186 		/*
17187 		 * ill_frag_timer is currently executing. Just record the
17188 		 * the fact that we want the timer to be restarted.
17189 		 * ill_frag_timer will post a timeout before it returns,
17190 		 * ensuring it will be called again.
17191 		 */
17192 		ill->ill_fragtimer_needrestart = 1;
17193 		return;
17194 	}
17195 
17196 	if (ill->ill_frag_timer_id == 0) {
17197 		/*
17198 		 * The timer is neither running nor is the timeout handler
17199 		 * executing. Post a timeout so that ill_frag_timer will be
17200 		 * called
17201 		 */
17202 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17203 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17204 		ill->ill_fragtimer_needrestart = 0;
17205 	}
17206 }
17207 
17208 /*
17209  * This routine is needed for loopback when forwarding multicasts.
17210  *
17211  * IPQoS Notes:
17212  * IPPF processing is done in fanout routines.
17213  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17214  * processing for IPsec packets is done when it comes back in clear.
17215  * NOTE : The callers of this function need to do the ire_refrele for the
17216  *	  ire that is being passed in.
17217  */
17218 void
17219 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17220     ill_t *recv_ill, uint32_t esp_udp_ports)
17221 {
17222 	boolean_t esp_in_udp_packet = (esp_udp_ports != 0);
17223 	ill_t	*ill = (ill_t *)q->q_ptr;
17224 	uint32_t	sum;
17225 	uint32_t	u1;
17226 	uint32_t	u2;
17227 	int		hdr_length;
17228 	boolean_t	mctl_present;
17229 	mblk_t		*first_mp = mp;
17230 	mblk_t		*hada_mp = NULL;
17231 	ipha_t		*inner_ipha;
17232 	ip_stack_t	*ipst;
17233 
17234 	ASSERT(recv_ill != NULL);
17235 	ipst = recv_ill->ill_ipst;
17236 
17237 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17238 	    "ip_rput_locl_start: q %p", q);
17239 
17240 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17241 	ASSERT(ill != NULL);
17242 
17243 
17244 #define	rptr	((uchar_t *)ipha)
17245 #define	iphs	((uint16_t *)ipha)
17246 
17247 	/*
17248 	 * no UDP or TCP packet should come here anymore.
17249 	 */
17250 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17251 	    ipha->ipha_protocol != IPPROTO_UDP);
17252 
17253 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17254 	if (mctl_present &&
17255 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17256 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17257 
17258 		/*
17259 		 * It's an IPsec accelerated packet.
17260 		 * Keep a pointer to the data attributes around until
17261 		 * we allocate the ipsec_info_t.
17262 		 */
17263 		IPSECHW_DEBUG(IPSECHW_PKT,
17264 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17265 		hada_mp = first_mp;
17266 		hada_mp->b_cont = NULL;
17267 		/*
17268 		 * Since it is accelerated, it comes directly from
17269 		 * the ill and the data attributes is followed by
17270 		 * the packet data.
17271 		 */
17272 		ASSERT(mp->b_datap->db_type != M_CTL);
17273 		first_mp = mp;
17274 		mctl_present = B_FALSE;
17275 	}
17276 
17277 	/*
17278 	 * IF M_CTL is not present, then ipsec_in_is_secure
17279 	 * should return B_TRUE. There is a case where loopback
17280 	 * packets has an M_CTL in the front with all the
17281 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17282 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17283 	 * packets never comes here, it is safe to ASSERT the
17284 	 * following.
17285 	 */
17286 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17287 
17288 	/*
17289 	 * Also, we should never have an mctl_present if this is an
17290 	 * ESP-in-UDP packet.
17291 	 */
17292 	ASSERT(!mctl_present || !esp_in_udp_packet);
17293 
17294 
17295 	/* u1 is # words of IP options */
17296 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17297 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17298 
17299 	/*
17300 	 * Don't verify header checksum if we just removed UDP header or
17301 	 * packet is coming back from AH/ESP.
17302 	 */
17303 	if (!esp_in_udp_packet && !mctl_present) {
17304 		if (u1) {
17305 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17306 				if (hada_mp != NULL)
17307 					freemsg(hada_mp);
17308 				return;
17309 			}
17310 		} else {
17311 			/* Check the IP header checksum.  */
17312 #define	uph	((uint16_t *)ipha)
17313 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17314 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17315 #undef  uph
17316 			/* finish doing IP checksum */
17317 			sum = (sum & 0xFFFF) + (sum >> 16);
17318 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17319 			if (sum && sum != 0xFFFF) {
17320 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17321 				goto drop_pkt;
17322 			}
17323 		}
17324 	}
17325 
17326 	/*
17327 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17328 	 * might be called more than once for secure packets, count only
17329 	 * the first time.
17330 	 */
17331 	if (!mctl_present) {
17332 		UPDATE_IB_PKT_COUNT(ire);
17333 		ire->ire_last_used_time = lbolt;
17334 	}
17335 
17336 	/* Check for fragmentation offset. */
17337 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17338 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17339 	if (u1) {
17340 		/*
17341 		 * We re-assemble fragments before we do the AH/ESP
17342 		 * processing. Thus, M_CTL should not be present
17343 		 * while we are re-assembling.
17344 		 */
17345 		ASSERT(!mctl_present);
17346 		ASSERT(first_mp == mp);
17347 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
17348 			return;
17349 
17350 		/*
17351 		 * Make sure that first_mp points back to mp as
17352 		 * the mp we came in with could have changed in
17353 		 * ip_rput_fragment().
17354 		 */
17355 		ipha = (ipha_t *)mp->b_rptr;
17356 		first_mp = mp;
17357 	}
17358 
17359 	/*
17360 	 * Clear hardware checksumming flag as it is currently only
17361 	 * used by TCP and UDP.
17362 	 */
17363 	DB_CKSUMFLAGS(mp) = 0;
17364 
17365 	/* Now we have a complete datagram, destined for this machine. */
17366 	u1 = IPH_HDR_LENGTH(ipha);
17367 	switch (ipha->ipha_protocol) {
17368 	case IPPROTO_ICMP: {
17369 		ire_t		*ire_zone;
17370 		ilm_t		*ilm;
17371 		mblk_t		*mp1;
17372 		zoneid_t	last_zoneid;
17373 		ilm_walker_t	ilw;
17374 
17375 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17376 			ASSERT(ire->ire_type == IRE_BROADCAST);
17377 
17378 			/*
17379 			 * In the multicast case, applications may have joined
17380 			 * the group from different zones, so we need to deliver
17381 			 * the packet to each of them. Loop through the
17382 			 * multicast memberships structures (ilm) on the receive
17383 			 * ill and send a copy of the packet up each matching
17384 			 * one. However, we don't do this for multicasts sent on
17385 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17386 			 * they must stay in the sender's zone.
17387 			 *
17388 			 * ilm_add_v6() ensures that ilms in the same zone are
17389 			 * contiguous in the ill_ilm list. We use this property
17390 			 * to avoid sending duplicates needed when two
17391 			 * applications in the same zone join the same group on
17392 			 * different logical interfaces: we ignore the ilm if
17393 			 * its zoneid is the same as the last matching one.
17394 			 * In addition, the sending of the packet for
17395 			 * ire_zoneid is delayed until all of the other ilms
17396 			 * have been exhausted.
17397 			 */
17398 			last_zoneid = -1;
17399 			ilm = ilm_walker_start(&ilw, recv_ill);
17400 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
17401 				if (ipha->ipha_dst != ilm->ilm_addr ||
17402 				    ilm->ilm_zoneid == last_zoneid ||
17403 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17404 				    ilm->ilm_zoneid == ALL_ZONES ||
17405 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17406 					continue;
17407 				mp1 = ip_copymsg(first_mp);
17408 				if (mp1 == NULL)
17409 					continue;
17410 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
17411 				    0, sum, mctl_present, B_TRUE,
17412 				    recv_ill, ilm->ilm_zoneid);
17413 				last_zoneid = ilm->ilm_zoneid;
17414 			}
17415 			ilm_walker_finish(&ilw);
17416 		} else if (ire->ire_type == IRE_BROADCAST) {
17417 			/*
17418 			 * In the broadcast case, there may be many zones
17419 			 * which need a copy of the packet delivered to them.
17420 			 * There is one IRE_BROADCAST per broadcast address
17421 			 * and per zone; we walk those using a helper function.
17422 			 * In addition, the sending of the packet for ire is
17423 			 * delayed until all of the other ires have been
17424 			 * processed.
17425 			 */
17426 			IRB_REFHOLD(ire->ire_bucket);
17427 			ire_zone = NULL;
17428 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17429 			    ire)) != NULL) {
17430 				mp1 = ip_copymsg(first_mp);
17431 				if (mp1 == NULL)
17432 					continue;
17433 
17434 				UPDATE_IB_PKT_COUNT(ire_zone);
17435 				ire_zone->ire_last_used_time = lbolt;
17436 				icmp_inbound(q, mp1, B_TRUE, ill,
17437 				    0, sum, mctl_present, B_TRUE,
17438 				    recv_ill, ire_zone->ire_zoneid);
17439 			}
17440 			IRB_REFRELE(ire->ire_bucket);
17441 		}
17442 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17443 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17444 		    ire->ire_zoneid);
17445 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17446 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17447 		return;
17448 	}
17449 	case IPPROTO_IGMP:
17450 		/*
17451 		 * If we are not willing to accept IGMP packets in clear,
17452 		 * then check with global policy.
17453 		 */
17454 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17455 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17456 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17457 			if (first_mp == NULL)
17458 				return;
17459 		}
17460 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17461 			freemsg(first_mp);
17462 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17463 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17464 			return;
17465 		}
17466 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17467 			/* Bad packet - discarded by igmp_input */
17468 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17469 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17470 			if (mctl_present)
17471 				freeb(first_mp);
17472 			return;
17473 		}
17474 		/*
17475 		 * igmp_input() may have returned the pulled up message.
17476 		 * So first_mp and ipha need to be reinitialized.
17477 		 */
17478 		ipha = (ipha_t *)mp->b_rptr;
17479 		if (mctl_present)
17480 			first_mp->b_cont = mp;
17481 		else
17482 			first_mp = mp;
17483 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17484 		    connf_head != NULL) {
17485 			/* No user-level listener for IGMP packets */
17486 			goto drop_pkt;
17487 		}
17488 		/* deliver to local raw users */
17489 		break;
17490 	case IPPROTO_PIM:
17491 		/*
17492 		 * If we are not willing to accept PIM packets in clear,
17493 		 * then check with global policy.
17494 		 */
17495 		if (ipst->ips_pim_accept_clear_messages == 0) {
17496 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17497 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17498 			if (first_mp == NULL)
17499 				return;
17500 		}
17501 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17502 			freemsg(first_mp);
17503 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17504 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17505 			return;
17506 		}
17507 		if (pim_input(q, mp, ill) != 0) {
17508 			/* Bad packet - discarded by pim_input */
17509 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17510 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17511 			if (mctl_present)
17512 				freeb(first_mp);
17513 			return;
17514 		}
17515 
17516 		/*
17517 		 * pim_input() may have pulled up the message so ipha needs to
17518 		 * be reinitialized.
17519 		 */
17520 		ipha = (ipha_t *)mp->b_rptr;
17521 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17522 		    connf_head != NULL) {
17523 			/* No user-level listener for PIM packets */
17524 			goto drop_pkt;
17525 		}
17526 		/* deliver to local raw users */
17527 		break;
17528 	case IPPROTO_ENCAP:
17529 		/*
17530 		 * Handle self-encapsulated packets (IP-in-IP where
17531 		 * the inner addresses == the outer addresses).
17532 		 */
17533 		hdr_length = IPH_HDR_LENGTH(ipha);
17534 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17535 		    mp->b_wptr) {
17536 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17537 			    sizeof (ipha_t) - mp->b_rptr)) {
17538 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17539 				freemsg(first_mp);
17540 				return;
17541 			}
17542 			ipha = (ipha_t *)mp->b_rptr;
17543 		}
17544 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17545 		/*
17546 		 * Check the sanity of the inner IP header.
17547 		 */
17548 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17549 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17550 			freemsg(first_mp);
17551 			return;
17552 		}
17553 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17554 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17555 			freemsg(first_mp);
17556 			return;
17557 		}
17558 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17559 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17560 			ipsec_in_t *ii;
17561 
17562 			/*
17563 			 * Self-encapsulated tunnel packet. Remove
17564 			 * the outer IP header and fanout again.
17565 			 * We also need to make sure that the inner
17566 			 * header is pulled up until options.
17567 			 */
17568 			mp->b_rptr = (uchar_t *)inner_ipha;
17569 			ipha = inner_ipha;
17570 			hdr_length = IPH_HDR_LENGTH(ipha);
17571 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17572 				if (!pullupmsg(mp, (uchar_t *)ipha +
17573 				    + hdr_length - mp->b_rptr)) {
17574 					freemsg(first_mp);
17575 					return;
17576 				}
17577 				ipha = (ipha_t *)mp->b_rptr;
17578 			}
17579 			if (hdr_length > sizeof (ipha_t)) {
17580 				/* We got options on the inner packet. */
17581 				ipaddr_t dst = ipha->ipha_dst;
17582 
17583 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17584 				    -1) {
17585 					/* Bad options! */
17586 					return;
17587 				}
17588 				if (dst != ipha->ipha_dst) {
17589 					/*
17590 					 * Someone put a source-route in
17591 					 * the inside header of a self-
17592 					 * encapsulated packet.  Drop it
17593 					 * with extreme prejudice and let
17594 					 * the sender know.
17595 					 */
17596 					icmp_unreachable(q, first_mp,
17597 					    ICMP_SOURCE_ROUTE_FAILED,
17598 					    recv_ill->ill_zoneid, ipst);
17599 					return;
17600 				}
17601 			}
17602 			if (!mctl_present) {
17603 				ASSERT(first_mp == mp);
17604 				/*
17605 				 * This means that somebody is sending
17606 				 * Self-encapsualted packets without AH/ESP.
17607 				 * If AH/ESP was present, we would have already
17608 				 * allocated the first_mp.
17609 				 *
17610 				 * Send this packet to find a tunnel endpoint.
17611 				 * if I can't find one, an ICMP
17612 				 * PROTOCOL_UNREACHABLE will get sent.
17613 				 */
17614 				goto fanout;
17615 			}
17616 			/*
17617 			 * We generally store the ill_index if we need to
17618 			 * do IPsec processing as we lose the ill queue when
17619 			 * we come back. But in this case, we never should
17620 			 * have to store the ill_index here as it should have
17621 			 * been stored previously when we processed the
17622 			 * AH/ESP header in this routine or for non-ipsec
17623 			 * cases, we still have the queue. But for some bad
17624 			 * packets from the wire, we can get to IPsec after
17625 			 * this and we better store the index for that case.
17626 			 */
17627 			ill = (ill_t *)q->q_ptr;
17628 			ii = (ipsec_in_t *)first_mp->b_rptr;
17629 			ii->ipsec_in_ill_index =
17630 			    ill->ill_phyint->phyint_ifindex;
17631 			ii->ipsec_in_rill_index =
17632 			    recv_ill->ill_phyint->phyint_ifindex;
17633 			if (ii->ipsec_in_decaps) {
17634 				/*
17635 				 * This packet is self-encapsulated multiple
17636 				 * times. We don't want to recurse infinitely.
17637 				 * To keep it simple, drop the packet.
17638 				 */
17639 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17640 				freemsg(first_mp);
17641 				return;
17642 			}
17643 			ii->ipsec_in_decaps = B_TRUE;
17644 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17645 			    ire);
17646 			return;
17647 		}
17648 		break;
17649 	case IPPROTO_AH:
17650 	case IPPROTO_ESP: {
17651 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17652 
17653 		/*
17654 		 * Fast path for AH/ESP. If this is the first time
17655 		 * we are sending a datagram to AH/ESP, allocate
17656 		 * a IPSEC_IN message and prepend it. Otherwise,
17657 		 * just fanout.
17658 		 */
17659 
17660 		int ipsec_rc;
17661 		ipsec_in_t *ii;
17662 		netstack_t *ns = ipst->ips_netstack;
17663 
17664 		IP_STAT(ipst, ipsec_proto_ahesp);
17665 		if (!mctl_present) {
17666 			ASSERT(first_mp == mp);
17667 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17668 			if (first_mp == NULL) {
17669 				ip1dbg(("ip_proto_input: IPSEC_IN "
17670 				    "allocation failure.\n"));
17671 				freemsg(hada_mp); /* okay ifnull */
17672 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17673 				freemsg(mp);
17674 				return;
17675 			}
17676 			/*
17677 			 * Store the ill_index so that when we come back
17678 			 * from IPsec we ride on the same queue.
17679 			 */
17680 			ill = (ill_t *)q->q_ptr;
17681 			ii = (ipsec_in_t *)first_mp->b_rptr;
17682 			ii->ipsec_in_ill_index =
17683 			    ill->ill_phyint->phyint_ifindex;
17684 			ii->ipsec_in_rill_index =
17685 			    recv_ill->ill_phyint->phyint_ifindex;
17686 			first_mp->b_cont = mp;
17687 			/*
17688 			 * Cache hardware acceleration info.
17689 			 */
17690 			if (hada_mp != NULL) {
17691 				IPSECHW_DEBUG(IPSECHW_PKT,
17692 				    ("ip_rput_local: caching data attr.\n"));
17693 				ii->ipsec_in_accelerated = B_TRUE;
17694 				ii->ipsec_in_da = hada_mp;
17695 				hada_mp = NULL;
17696 			}
17697 		} else {
17698 			ii = (ipsec_in_t *)first_mp->b_rptr;
17699 		}
17700 
17701 		ii->ipsec_in_esp_udp_ports = esp_udp_ports;
17702 
17703 		if (!ipsec_loaded(ipss)) {
17704 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17705 			    ire->ire_zoneid, ipst);
17706 			return;
17707 		}
17708 
17709 		ns = ipst->ips_netstack;
17710 		/* select inbound SA and have IPsec process the pkt */
17711 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17712 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17713 			boolean_t esp_in_udp_sa;
17714 			if (esph == NULL)
17715 				return;
17716 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17717 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17718 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17719 			    IPSA_F_NATT) != 0);
17720 			/*
17721 			 * The following is a fancy, but quick, way of saying:
17722 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17723 			 *    OR
17724 			 * ESP SA and ESP-in-UDP packet --> drop
17725 			 */
17726 			if (esp_in_udp_sa != esp_in_udp_packet) {
17727 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17728 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17729 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17730 				    &ns->netstack_ipsec->ipsec_dropper);
17731 				return;
17732 			}
17733 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17734 			    first_mp, esph);
17735 		} else {
17736 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17737 			if (ah == NULL)
17738 				return;
17739 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17740 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17741 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17742 			    first_mp, ah);
17743 		}
17744 
17745 		switch (ipsec_rc) {
17746 		case IPSEC_STATUS_SUCCESS:
17747 			break;
17748 		case IPSEC_STATUS_FAILED:
17749 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17750 			/* FALLTHRU */
17751 		case IPSEC_STATUS_PENDING:
17752 			return;
17753 		}
17754 		/* we're done with IPsec processing, send it up */
17755 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17756 		return;
17757 	}
17758 	default:
17759 		break;
17760 	}
17761 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17762 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17763 		    ire->ire_zoneid));
17764 		goto drop_pkt;
17765 	}
17766 	/*
17767 	 * Handle protocols with which IP is less intimate.  There
17768 	 * can be more than one stream bound to a particular
17769 	 * protocol.  When this is the case, each one gets a copy
17770 	 * of any incoming packets.
17771 	 */
17772 fanout:
17773 	ip_fanout_proto(q, first_mp, ill, ipha,
17774 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17775 	    B_TRUE, recv_ill, ire->ire_zoneid);
17776 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17777 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17778 	return;
17779 
17780 drop_pkt:
17781 	freemsg(first_mp);
17782 	if (hada_mp != NULL)
17783 		freeb(hada_mp);
17784 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17785 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17786 #undef	rptr
17787 #undef  iphs
17788 
17789 }
17790 
17791 /*
17792  * Update any source route, record route or timestamp options.
17793  * Check that we are at end of strict source route.
17794  * The options have already been checked for sanity in ip_rput_options().
17795  */
17796 static boolean_t
17797 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17798     ip_stack_t *ipst)
17799 {
17800 	ipoptp_t	opts;
17801 	uchar_t		*opt;
17802 	uint8_t		optval;
17803 	uint8_t		optlen;
17804 	ipaddr_t	dst;
17805 	uint32_t	ts;
17806 	ire_t		*dst_ire;
17807 	timestruc_t	now;
17808 	zoneid_t	zoneid;
17809 	ill_t		*ill;
17810 
17811 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17812 
17813 	ip2dbg(("ip_rput_local_options\n"));
17814 
17815 	for (optval = ipoptp_first(&opts, ipha);
17816 	    optval != IPOPT_EOL;
17817 	    optval = ipoptp_next(&opts)) {
17818 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17819 		opt = opts.ipoptp_cur;
17820 		optlen = opts.ipoptp_len;
17821 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17822 		    optval, optlen));
17823 		switch (optval) {
17824 			uint32_t off;
17825 		case IPOPT_SSRR:
17826 		case IPOPT_LSRR:
17827 			off = opt[IPOPT_OFFSET];
17828 			off--;
17829 			if (optlen < IP_ADDR_LEN ||
17830 			    off > optlen - IP_ADDR_LEN) {
17831 				/* End of source route */
17832 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17833 				break;
17834 			}
17835 			/*
17836 			 * This will only happen if two consecutive entries
17837 			 * in the source route contains our address or if
17838 			 * it is a packet with a loose source route which
17839 			 * reaches us before consuming the whole source route
17840 			 */
17841 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17842 			if (optval == IPOPT_SSRR) {
17843 				goto bad_src_route;
17844 			}
17845 			/*
17846 			 * Hack: instead of dropping the packet truncate the
17847 			 * source route to what has been used by filling the
17848 			 * rest with IPOPT_NOP.
17849 			 */
17850 			opt[IPOPT_OLEN] = (uint8_t)off;
17851 			while (off < optlen) {
17852 				opt[off++] = IPOPT_NOP;
17853 			}
17854 			break;
17855 		case IPOPT_RR:
17856 			off = opt[IPOPT_OFFSET];
17857 			off--;
17858 			if (optlen < IP_ADDR_LEN ||
17859 			    off > optlen - IP_ADDR_LEN) {
17860 				/* No more room - ignore */
17861 				ip1dbg((
17862 				    "ip_rput_local_options: end of RR\n"));
17863 				break;
17864 			}
17865 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17866 			    IP_ADDR_LEN);
17867 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17868 			break;
17869 		case IPOPT_TS:
17870 			/* Insert timestamp if there is romm */
17871 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17872 			case IPOPT_TS_TSONLY:
17873 				off = IPOPT_TS_TIMELEN;
17874 				break;
17875 			case IPOPT_TS_PRESPEC:
17876 			case IPOPT_TS_PRESPEC_RFC791:
17877 				/* Verify that the address matched */
17878 				off = opt[IPOPT_OFFSET] - 1;
17879 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17880 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17881 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17882 				    ipst);
17883 				if (dst_ire == NULL) {
17884 					/* Not for us */
17885 					break;
17886 				}
17887 				ire_refrele(dst_ire);
17888 				/* FALLTHRU */
17889 			case IPOPT_TS_TSANDADDR:
17890 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17891 				break;
17892 			default:
17893 				/*
17894 				 * ip_*put_options should have already
17895 				 * dropped this packet.
17896 				 */
17897 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17898 				    "unknown IT - bug in ip_rput_options?\n");
17899 				return (B_TRUE);	/* Keep "lint" happy */
17900 			}
17901 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17902 				/* Increase overflow counter */
17903 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17904 				opt[IPOPT_POS_OV_FLG] =
17905 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17906 				    (off << 4));
17907 				break;
17908 			}
17909 			off = opt[IPOPT_OFFSET] - 1;
17910 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17911 			case IPOPT_TS_PRESPEC:
17912 			case IPOPT_TS_PRESPEC_RFC791:
17913 			case IPOPT_TS_TSANDADDR:
17914 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17915 				    IP_ADDR_LEN);
17916 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17917 				/* FALLTHRU */
17918 			case IPOPT_TS_TSONLY:
17919 				off = opt[IPOPT_OFFSET] - 1;
17920 				/* Compute # of milliseconds since midnight */
17921 				gethrestime(&now);
17922 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17923 				    now.tv_nsec / (NANOSEC / MILLISEC);
17924 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17925 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17926 				break;
17927 			}
17928 			break;
17929 		}
17930 	}
17931 	return (B_TRUE);
17932 
17933 bad_src_route:
17934 	q = WR(q);
17935 	if (q->q_next != NULL)
17936 		ill = q->q_ptr;
17937 	else
17938 		ill = NULL;
17939 
17940 	/* make sure we clear any indication of a hardware checksum */
17941 	DB_CKSUMFLAGS(mp) = 0;
17942 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17943 	if (zoneid == ALL_ZONES)
17944 		freemsg(mp);
17945 	else
17946 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17947 	return (B_FALSE);
17948 
17949 }
17950 
17951 /*
17952  * Process IP options in an inbound packet.  If an option affects the
17953  * effective destination address, return the next hop address via dstp.
17954  * Returns -1 if something fails in which case an ICMP error has been sent
17955  * and mp freed.
17956  */
17957 static int
17958 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17959     ip_stack_t *ipst)
17960 {
17961 	ipoptp_t	opts;
17962 	uchar_t		*opt;
17963 	uint8_t		optval;
17964 	uint8_t		optlen;
17965 	ipaddr_t	dst;
17966 	intptr_t	code = 0;
17967 	ire_t		*ire = NULL;
17968 	zoneid_t	zoneid;
17969 	ill_t		*ill;
17970 
17971 	ip2dbg(("ip_rput_options\n"));
17972 	dst = ipha->ipha_dst;
17973 	for (optval = ipoptp_first(&opts, ipha);
17974 	    optval != IPOPT_EOL;
17975 	    optval = ipoptp_next(&opts)) {
17976 		opt = opts.ipoptp_cur;
17977 		optlen = opts.ipoptp_len;
17978 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17979 		    optval, optlen));
17980 		/*
17981 		 * Note: we need to verify the checksum before we
17982 		 * modify anything thus this routine only extracts the next
17983 		 * hop dst from any source route.
17984 		 */
17985 		switch (optval) {
17986 			uint32_t off;
17987 		case IPOPT_SSRR:
17988 		case IPOPT_LSRR:
17989 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17990 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17991 			if (ire == NULL) {
17992 				if (optval == IPOPT_SSRR) {
17993 					ip1dbg(("ip_rput_options: not next"
17994 					    " strict source route 0x%x\n",
17995 					    ntohl(dst)));
17996 					code = (char *)&ipha->ipha_dst -
17997 					    (char *)ipha;
17998 					goto param_prob; /* RouterReq's */
17999 				}
18000 				ip2dbg(("ip_rput_options: "
18001 				    "not next source route 0x%x\n",
18002 				    ntohl(dst)));
18003 				break;
18004 			}
18005 			ire_refrele(ire);
18006 
18007 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18008 				ip1dbg((
18009 				    "ip_rput_options: bad option offset\n"));
18010 				code = (char *)&opt[IPOPT_OLEN] -
18011 				    (char *)ipha;
18012 				goto param_prob;
18013 			}
18014 			off = opt[IPOPT_OFFSET];
18015 			off--;
18016 		redo_srr:
18017 			if (optlen < IP_ADDR_LEN ||
18018 			    off > optlen - IP_ADDR_LEN) {
18019 				/* End of source route */
18020 				ip1dbg(("ip_rput_options: end of SR\n"));
18021 				break;
18022 			}
18023 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18024 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18025 			    ntohl(dst)));
18026 
18027 			/*
18028 			 * Check if our address is present more than
18029 			 * once as consecutive hops in source route.
18030 			 * XXX verify per-interface ip_forwarding
18031 			 * for source route?
18032 			 */
18033 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18034 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18035 
18036 			if (ire != NULL) {
18037 				ire_refrele(ire);
18038 				off += IP_ADDR_LEN;
18039 				goto redo_srr;
18040 			}
18041 
18042 			if (dst == htonl(INADDR_LOOPBACK)) {
18043 				ip1dbg(("ip_rput_options: loopback addr in "
18044 				    "source route!\n"));
18045 				goto bad_src_route;
18046 			}
18047 			/*
18048 			 * For strict: verify that dst is directly
18049 			 * reachable.
18050 			 */
18051 			if (optval == IPOPT_SSRR) {
18052 				ire = ire_ftable_lookup(dst, 0, 0,
18053 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18054 				    MBLK_GETLABEL(mp),
18055 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18056 				if (ire == NULL) {
18057 					ip1dbg(("ip_rput_options: SSRR not "
18058 					    "directly reachable: 0x%x\n",
18059 					    ntohl(dst)));
18060 					goto bad_src_route;
18061 				}
18062 				ire_refrele(ire);
18063 			}
18064 			/*
18065 			 * Defer update of the offset and the record route
18066 			 * until the packet is forwarded.
18067 			 */
18068 			break;
18069 		case IPOPT_RR:
18070 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18071 				ip1dbg((
18072 				    "ip_rput_options: bad option offset\n"));
18073 				code = (char *)&opt[IPOPT_OLEN] -
18074 				    (char *)ipha;
18075 				goto param_prob;
18076 			}
18077 			break;
18078 		case IPOPT_TS:
18079 			/*
18080 			 * Verify that length >= 5 and that there is either
18081 			 * room for another timestamp or that the overflow
18082 			 * counter is not maxed out.
18083 			 */
18084 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18085 			if (optlen < IPOPT_MINLEN_IT) {
18086 				goto param_prob;
18087 			}
18088 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18089 				ip1dbg((
18090 				    "ip_rput_options: bad option offset\n"));
18091 				code = (char *)&opt[IPOPT_OFFSET] -
18092 				    (char *)ipha;
18093 				goto param_prob;
18094 			}
18095 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18096 			case IPOPT_TS_TSONLY:
18097 				off = IPOPT_TS_TIMELEN;
18098 				break;
18099 			case IPOPT_TS_TSANDADDR:
18100 			case IPOPT_TS_PRESPEC:
18101 			case IPOPT_TS_PRESPEC_RFC791:
18102 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18103 				break;
18104 			default:
18105 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18106 				    (char *)ipha;
18107 				goto param_prob;
18108 			}
18109 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18110 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18111 				/*
18112 				 * No room and the overflow counter is 15
18113 				 * already.
18114 				 */
18115 				goto param_prob;
18116 			}
18117 			break;
18118 		}
18119 	}
18120 
18121 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18122 		*dstp = dst;
18123 		return (0);
18124 	}
18125 
18126 	ip1dbg(("ip_rput_options: error processing IP options."));
18127 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18128 
18129 param_prob:
18130 	q = WR(q);
18131 	if (q->q_next != NULL)
18132 		ill = q->q_ptr;
18133 	else
18134 		ill = NULL;
18135 
18136 	/* make sure we clear any indication of a hardware checksum */
18137 	DB_CKSUMFLAGS(mp) = 0;
18138 	/* Don't know whether this is for non-global or global/forwarding */
18139 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18140 	if (zoneid == ALL_ZONES)
18141 		freemsg(mp);
18142 	else
18143 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18144 	return (-1);
18145 
18146 bad_src_route:
18147 	q = WR(q);
18148 	if (q->q_next != NULL)
18149 		ill = q->q_ptr;
18150 	else
18151 		ill = NULL;
18152 
18153 	/* make sure we clear any indication of a hardware checksum */
18154 	DB_CKSUMFLAGS(mp) = 0;
18155 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18156 	if (zoneid == ALL_ZONES)
18157 		freemsg(mp);
18158 	else
18159 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18160 	return (-1);
18161 }
18162 
18163 /*
18164  * IP & ICMP info in >=14 msg's ...
18165  *  - ip fixed part (mib2_ip_t)
18166  *  - icmp fixed part (mib2_icmp_t)
18167  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18168  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18169  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18170  *  - ipRouteAttributeTable (ip 102)	labeled routes
18171  *  - ip multicast membership (ip_member_t)
18172  *  - ip multicast source filtering (ip_grpsrc_t)
18173  *  - igmp fixed part (struct igmpstat)
18174  *  - multicast routing stats (struct mrtstat)
18175  *  - multicast routing vifs (array of struct vifctl)
18176  *  - multicast routing routes (array of struct mfcctl)
18177  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18178  *					One per ill plus one generic
18179  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18180  *					One per ill plus one generic
18181  *  - ipv6RouteEntry			all IPv6 IREs
18182  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18183  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18184  *  - ipv6AddrEntry			all IPv6 ipifs
18185  *  - ipv6 multicast membership (ipv6_member_t)
18186  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18187  *
18188  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18189  *
18190  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18191  * already filled in by the caller.
18192  * Return value of 0 indicates that no messages were sent and caller
18193  * should free mpctl.
18194  */
18195 int
18196 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18197 {
18198 	ip_stack_t *ipst;
18199 	sctp_stack_t *sctps;
18200 
18201 	if (q->q_next != NULL) {
18202 		ipst = ILLQ_TO_IPST(q);
18203 	} else {
18204 		ipst = CONNQ_TO_IPST(q);
18205 	}
18206 	ASSERT(ipst != NULL);
18207 	sctps = ipst->ips_netstack->netstack_sctp;
18208 
18209 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18210 		return (0);
18211 	}
18212 
18213 	/*
18214 	 * For the purposes of the (broken) packet shell use
18215 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18216 	 * to make TCP and UDP appear first in the list of mib items.
18217 	 * TBD: We could expand this and use it in netstat so that
18218 	 * the kernel doesn't have to produce large tables (connections,
18219 	 * routes, etc) when netstat only wants the statistics or a particular
18220 	 * table.
18221 	 */
18222 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18223 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18224 			return (1);
18225 		}
18226 	}
18227 
18228 	if (level != MIB2_TCP) {
18229 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18230 			return (1);
18231 		}
18232 	}
18233 
18234 	if (level != MIB2_UDP) {
18235 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18236 			return (1);
18237 		}
18238 	}
18239 
18240 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18241 	    ipst)) == NULL) {
18242 		return (1);
18243 	}
18244 
18245 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18246 		return (1);
18247 	}
18248 
18249 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18250 		return (1);
18251 	}
18252 
18253 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18254 		return (1);
18255 	}
18256 
18257 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18258 		return (1);
18259 	}
18260 
18261 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18262 		return (1);
18263 	}
18264 
18265 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18266 		return (1);
18267 	}
18268 
18269 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18270 		return (1);
18271 	}
18272 
18273 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18274 		return (1);
18275 	}
18276 
18277 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18278 		return (1);
18279 	}
18280 
18281 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18282 		return (1);
18283 	}
18284 
18285 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18286 		return (1);
18287 	}
18288 
18289 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18290 		return (1);
18291 	}
18292 
18293 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18294 		return (1);
18295 	}
18296 
18297 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
18298 	if (mpctl == NULL)
18299 		return (1);
18300 
18301 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
18302 	if (mpctl == NULL)
18303 		return (1);
18304 
18305 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18306 		return (1);
18307 	}
18308 	freemsg(mpctl);
18309 	return (1);
18310 }
18311 
18312 
18313 /* Get global (legacy) IPv4 statistics */
18314 static mblk_t *
18315 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18316     ip_stack_t *ipst)
18317 {
18318 	mib2_ip_t		old_ip_mib;
18319 	struct opthdr		*optp;
18320 	mblk_t			*mp2ctl;
18321 
18322 	/*
18323 	 * make a copy of the original message
18324 	 */
18325 	mp2ctl = copymsg(mpctl);
18326 
18327 	/* fixed length IP structure... */
18328 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18329 	optp->level = MIB2_IP;
18330 	optp->name = 0;
18331 	SET_MIB(old_ip_mib.ipForwarding,
18332 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18333 	SET_MIB(old_ip_mib.ipDefaultTTL,
18334 	    (uint32_t)ipst->ips_ip_def_ttl);
18335 	SET_MIB(old_ip_mib.ipReasmTimeout,
18336 	    ipst->ips_ip_g_frag_timeout);
18337 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18338 	    sizeof (mib2_ipAddrEntry_t));
18339 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18340 	    sizeof (mib2_ipRouteEntry_t));
18341 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18342 	    sizeof (mib2_ipNetToMediaEntry_t));
18343 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18344 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18345 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18346 	    sizeof (mib2_ipAttributeEntry_t));
18347 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18348 
18349 	/*
18350 	 * Grab the statistics from the new IP MIB
18351 	 */
18352 	SET_MIB(old_ip_mib.ipInReceives,
18353 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18354 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18355 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18356 	SET_MIB(old_ip_mib.ipForwDatagrams,
18357 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18358 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18359 	    ipmib->ipIfStatsInUnknownProtos);
18360 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18361 	SET_MIB(old_ip_mib.ipInDelivers,
18362 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18363 	SET_MIB(old_ip_mib.ipOutRequests,
18364 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18365 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18366 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18367 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18368 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18369 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18370 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18371 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18372 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18373 
18374 	/* ipRoutingDiscards is not being used */
18375 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18376 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18377 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18378 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18379 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18380 	    ipmib->ipIfStatsReasmDuplicates);
18381 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18382 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18383 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18384 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18385 	SET_MIB(old_ip_mib.rawipInOverflows,
18386 	    ipmib->rawipIfStatsInOverflows);
18387 
18388 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18389 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18390 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18391 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18392 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18393 	    ipmib->ipIfStatsOutSwitchIPVersion);
18394 
18395 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18396 	    (int)sizeof (old_ip_mib))) {
18397 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18398 		    (uint_t)sizeof (old_ip_mib)));
18399 	}
18400 
18401 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18402 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18403 	    (int)optp->level, (int)optp->name, (int)optp->len));
18404 	qreply(q, mpctl);
18405 	return (mp2ctl);
18406 }
18407 
18408 /* Per interface IPv4 statistics */
18409 static mblk_t *
18410 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18411 {
18412 	struct opthdr		*optp;
18413 	mblk_t			*mp2ctl;
18414 	ill_t			*ill;
18415 	ill_walk_context_t	ctx;
18416 	mblk_t			*mp_tail = NULL;
18417 	mib2_ipIfStatsEntry_t	global_ip_mib;
18418 
18419 	/*
18420 	 * Make a copy of the original message
18421 	 */
18422 	mp2ctl = copymsg(mpctl);
18423 
18424 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18425 	optp->level = MIB2_IP;
18426 	optp->name = MIB2_IP_TRAFFIC_STATS;
18427 	/* Include "unknown interface" ip_mib */
18428 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18429 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18430 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18431 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18432 	    (ipst->ips_ip_g_forward ? 1 : 2));
18433 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18434 	    (uint32_t)ipst->ips_ip_def_ttl);
18435 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18436 	    sizeof (mib2_ipIfStatsEntry_t));
18437 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18438 	    sizeof (mib2_ipAddrEntry_t));
18439 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18440 	    sizeof (mib2_ipRouteEntry_t));
18441 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18442 	    sizeof (mib2_ipNetToMediaEntry_t));
18443 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18444 	    sizeof (ip_member_t));
18445 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18446 	    sizeof (ip_grpsrc_t));
18447 
18448 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18449 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18450 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18451 		    "failed to allocate %u bytes\n",
18452 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18453 	}
18454 
18455 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18456 
18457 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18458 	ill = ILL_START_WALK_V4(&ctx, ipst);
18459 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18460 		ill->ill_ip_mib->ipIfStatsIfIndex =
18461 		    ill->ill_phyint->phyint_ifindex;
18462 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18463 		    (ipst->ips_ip_g_forward ? 1 : 2));
18464 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18465 		    (uint32_t)ipst->ips_ip_def_ttl);
18466 
18467 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18468 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18469 		    (char *)ill->ill_ip_mib,
18470 		    (int)sizeof (*ill->ill_ip_mib))) {
18471 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18472 			    "failed to allocate %u bytes\n",
18473 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18474 		}
18475 	}
18476 	rw_exit(&ipst->ips_ill_g_lock);
18477 
18478 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18479 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18480 	    "level %d, name %d, len %d\n",
18481 	    (int)optp->level, (int)optp->name, (int)optp->len));
18482 	qreply(q, mpctl);
18483 
18484 	if (mp2ctl == NULL)
18485 		return (NULL);
18486 
18487 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18488 }
18489 
18490 /* Global IPv4 ICMP statistics */
18491 static mblk_t *
18492 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18493 {
18494 	struct opthdr		*optp;
18495 	mblk_t			*mp2ctl;
18496 
18497 	/*
18498 	 * Make a copy of the original message
18499 	 */
18500 	mp2ctl = copymsg(mpctl);
18501 
18502 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18503 	optp->level = MIB2_ICMP;
18504 	optp->name = 0;
18505 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18506 	    (int)sizeof (ipst->ips_icmp_mib))) {
18507 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18508 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18509 	}
18510 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18511 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18512 	    (int)optp->level, (int)optp->name, (int)optp->len));
18513 	qreply(q, mpctl);
18514 	return (mp2ctl);
18515 }
18516 
18517 /* Global IPv4 IGMP statistics */
18518 static mblk_t *
18519 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18520 {
18521 	struct opthdr		*optp;
18522 	mblk_t			*mp2ctl;
18523 
18524 	/*
18525 	 * make a copy of the original message
18526 	 */
18527 	mp2ctl = copymsg(mpctl);
18528 
18529 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18530 	optp->level = EXPER_IGMP;
18531 	optp->name = 0;
18532 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18533 	    (int)sizeof (ipst->ips_igmpstat))) {
18534 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18535 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18536 	}
18537 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18538 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18539 	    (int)optp->level, (int)optp->name, (int)optp->len));
18540 	qreply(q, mpctl);
18541 	return (mp2ctl);
18542 }
18543 
18544 /* Global IPv4 Multicast Routing statistics */
18545 static mblk_t *
18546 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18547 {
18548 	struct opthdr		*optp;
18549 	mblk_t			*mp2ctl;
18550 
18551 	/*
18552 	 * make a copy of the original message
18553 	 */
18554 	mp2ctl = copymsg(mpctl);
18555 
18556 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18557 	optp->level = EXPER_DVMRP;
18558 	optp->name = 0;
18559 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18560 		ip0dbg(("ip_mroute_stats: failed\n"));
18561 	}
18562 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18563 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18564 	    (int)optp->level, (int)optp->name, (int)optp->len));
18565 	qreply(q, mpctl);
18566 	return (mp2ctl);
18567 }
18568 
18569 /* IPv4 address information */
18570 static mblk_t *
18571 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18572 {
18573 	struct opthdr		*optp;
18574 	mblk_t			*mp2ctl;
18575 	mblk_t			*mp_tail = NULL;
18576 	ill_t			*ill;
18577 	ipif_t			*ipif;
18578 	uint_t			bitval;
18579 	mib2_ipAddrEntry_t	mae;
18580 	zoneid_t		zoneid;
18581 	ill_walk_context_t ctx;
18582 
18583 	/*
18584 	 * make a copy of the original message
18585 	 */
18586 	mp2ctl = copymsg(mpctl);
18587 
18588 	/* ipAddrEntryTable */
18589 
18590 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18591 	optp->level = MIB2_IP;
18592 	optp->name = MIB2_IP_ADDR;
18593 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18594 
18595 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18596 	ill = ILL_START_WALK_V4(&ctx, ipst);
18597 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18598 		for (ipif = ill->ill_ipif; ipif != NULL;
18599 		    ipif = ipif->ipif_next) {
18600 			if (ipif->ipif_zoneid != zoneid &&
18601 			    ipif->ipif_zoneid != ALL_ZONES)
18602 				continue;
18603 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18604 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18605 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18606 
18607 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18608 			    OCTET_LENGTH);
18609 			mae.ipAdEntIfIndex.o_length =
18610 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18611 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18612 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18613 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18614 			mae.ipAdEntInfo.ae_subnet_len =
18615 			    ip_mask_to_plen(ipif->ipif_net_mask);
18616 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18617 			for (bitval = 1;
18618 			    bitval &&
18619 			    !(bitval & ipif->ipif_brd_addr);
18620 			    bitval <<= 1)
18621 				noop;
18622 			mae.ipAdEntBcastAddr = bitval;
18623 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18624 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18625 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18626 			mae.ipAdEntInfo.ae_broadcast_addr =
18627 			    ipif->ipif_brd_addr;
18628 			mae.ipAdEntInfo.ae_pp_dst_addr =
18629 			    ipif->ipif_pp_dst_addr;
18630 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18631 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18632 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18633 
18634 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18635 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18636 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18637 				    "allocate %u bytes\n",
18638 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18639 			}
18640 		}
18641 	}
18642 	rw_exit(&ipst->ips_ill_g_lock);
18643 
18644 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18645 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18646 	    (int)optp->level, (int)optp->name, (int)optp->len));
18647 	qreply(q, mpctl);
18648 	return (mp2ctl);
18649 }
18650 
18651 /* IPv6 address information */
18652 static mblk_t *
18653 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18654 {
18655 	struct opthdr		*optp;
18656 	mblk_t			*mp2ctl;
18657 	mblk_t			*mp_tail = NULL;
18658 	ill_t			*ill;
18659 	ipif_t			*ipif;
18660 	mib2_ipv6AddrEntry_t	mae6;
18661 	zoneid_t		zoneid;
18662 	ill_walk_context_t	ctx;
18663 
18664 	/*
18665 	 * make a copy of the original message
18666 	 */
18667 	mp2ctl = copymsg(mpctl);
18668 
18669 	/* ipv6AddrEntryTable */
18670 
18671 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18672 	optp->level = MIB2_IP6;
18673 	optp->name = MIB2_IP6_ADDR;
18674 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18675 
18676 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18677 	ill = ILL_START_WALK_V6(&ctx, ipst);
18678 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18679 		for (ipif = ill->ill_ipif; ipif != NULL;
18680 		    ipif = ipif->ipif_next) {
18681 			if (ipif->ipif_zoneid != zoneid &&
18682 			    ipif->ipif_zoneid != ALL_ZONES)
18683 				continue;
18684 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18685 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18686 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18687 
18688 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18689 			    OCTET_LENGTH);
18690 			mae6.ipv6AddrIfIndex.o_length =
18691 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18692 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18693 			mae6.ipv6AddrPfxLength =
18694 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18695 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18696 			mae6.ipv6AddrInfo.ae_subnet_len =
18697 			    mae6.ipv6AddrPfxLength;
18698 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18699 
18700 			/* Type: stateless(1), stateful(2), unknown(3) */
18701 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18702 				mae6.ipv6AddrType = 1;
18703 			else
18704 				mae6.ipv6AddrType = 2;
18705 			/* Anycast: true(1), false(2) */
18706 			if (ipif->ipif_flags & IPIF_ANYCAST)
18707 				mae6.ipv6AddrAnycastFlag = 1;
18708 			else
18709 				mae6.ipv6AddrAnycastFlag = 2;
18710 
18711 			/*
18712 			 * Address status: preferred(1), deprecated(2),
18713 			 * invalid(3), inaccessible(4), unknown(5)
18714 			 */
18715 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18716 				mae6.ipv6AddrStatus = 3;
18717 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18718 				mae6.ipv6AddrStatus = 2;
18719 			else
18720 				mae6.ipv6AddrStatus = 1;
18721 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18722 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18723 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18724 			    ipif->ipif_v6pp_dst_addr;
18725 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18726 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18727 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18728 			mae6.ipv6AddrIdentifier = ill->ill_token;
18729 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18730 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18731 			mae6.ipv6AddrRetransmitTime =
18732 			    ill->ill_reachable_retrans_time;
18733 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18734 			    (char *)&mae6,
18735 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18736 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18737 				    "allocate %u bytes\n",
18738 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18739 			}
18740 		}
18741 	}
18742 	rw_exit(&ipst->ips_ill_g_lock);
18743 
18744 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18745 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18746 	    (int)optp->level, (int)optp->name, (int)optp->len));
18747 	qreply(q, mpctl);
18748 	return (mp2ctl);
18749 }
18750 
18751 /* IPv4 multicast group membership. */
18752 static mblk_t *
18753 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18754 {
18755 	struct opthdr		*optp;
18756 	mblk_t			*mp2ctl;
18757 	ill_t			*ill;
18758 	ipif_t			*ipif;
18759 	ilm_t			*ilm;
18760 	ip_member_t		ipm;
18761 	mblk_t			*mp_tail = NULL;
18762 	ill_walk_context_t	ctx;
18763 	zoneid_t		zoneid;
18764 	ilm_walker_t		ilw;
18765 
18766 	/*
18767 	 * make a copy of the original message
18768 	 */
18769 	mp2ctl = copymsg(mpctl);
18770 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18771 
18772 	/* ipGroupMember table */
18773 	optp = (struct opthdr *)&mpctl->b_rptr[
18774 	    sizeof (struct T_optmgmt_ack)];
18775 	optp->level = MIB2_IP;
18776 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18777 
18778 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18779 	ill = ILL_START_WALK_V4(&ctx, ipst);
18780 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18781 		if (IS_UNDER_IPMP(ill))
18782 			continue;
18783 
18784 		ilm = ilm_walker_start(&ilw, ill);
18785 		for (ipif = ill->ill_ipif; ipif != NULL;
18786 		    ipif = ipif->ipif_next) {
18787 			if (ipif->ipif_zoneid != zoneid &&
18788 			    ipif->ipif_zoneid != ALL_ZONES)
18789 				continue;	/* not this zone */
18790 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18791 			    OCTET_LENGTH);
18792 			ipm.ipGroupMemberIfIndex.o_length =
18793 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18794 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18795 				ASSERT(ilm->ilm_ipif != NULL);
18796 				ASSERT(ilm->ilm_ill == NULL);
18797 				if (ilm->ilm_ipif != ipif)
18798 					continue;
18799 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18800 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18801 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18802 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18803 				    (char *)&ipm, (int)sizeof (ipm))) {
18804 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18805 					    "failed to allocate %u bytes\n",
18806 					    (uint_t)sizeof (ipm)));
18807 				}
18808 			}
18809 		}
18810 		ilm_walker_finish(&ilw);
18811 	}
18812 	rw_exit(&ipst->ips_ill_g_lock);
18813 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18814 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18815 	    (int)optp->level, (int)optp->name, (int)optp->len));
18816 	qreply(q, mpctl);
18817 	return (mp2ctl);
18818 }
18819 
18820 /* IPv6 multicast group membership. */
18821 static mblk_t *
18822 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18823 {
18824 	struct opthdr		*optp;
18825 	mblk_t			*mp2ctl;
18826 	ill_t			*ill;
18827 	ilm_t			*ilm;
18828 	ipv6_member_t		ipm6;
18829 	mblk_t			*mp_tail = NULL;
18830 	ill_walk_context_t	ctx;
18831 	zoneid_t		zoneid;
18832 	ilm_walker_t		ilw;
18833 
18834 	/*
18835 	 * make a copy of the original message
18836 	 */
18837 	mp2ctl = copymsg(mpctl);
18838 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18839 
18840 	/* ip6GroupMember table */
18841 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18842 	optp->level = MIB2_IP6;
18843 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18844 
18845 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18846 	ill = ILL_START_WALK_V6(&ctx, ipst);
18847 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18848 		if (IS_UNDER_IPMP(ill))
18849 			continue;
18850 
18851 		ilm = ilm_walker_start(&ilw, ill);
18852 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18853 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18854 			ASSERT(ilm->ilm_ipif == NULL);
18855 			ASSERT(ilm->ilm_ill != NULL);
18856 			if (ilm->ilm_zoneid != zoneid)
18857 				continue;	/* not this zone */
18858 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18859 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18860 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18861 			if (!snmp_append_data2(mpctl->b_cont,
18862 			    &mp_tail,
18863 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18864 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18865 				    "failed to allocate %u bytes\n",
18866 				    (uint_t)sizeof (ipm6)));
18867 			}
18868 		}
18869 		ilm_walker_finish(&ilw);
18870 	}
18871 	rw_exit(&ipst->ips_ill_g_lock);
18872 
18873 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18874 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18875 	    (int)optp->level, (int)optp->name, (int)optp->len));
18876 	qreply(q, mpctl);
18877 	return (mp2ctl);
18878 }
18879 
18880 /* IP multicast filtered sources */
18881 static mblk_t *
18882 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18883 {
18884 	struct opthdr		*optp;
18885 	mblk_t			*mp2ctl;
18886 	ill_t			*ill;
18887 	ipif_t			*ipif;
18888 	ilm_t			*ilm;
18889 	ip_grpsrc_t		ips;
18890 	mblk_t			*mp_tail = NULL;
18891 	ill_walk_context_t	ctx;
18892 	zoneid_t		zoneid;
18893 	int			i;
18894 	slist_t			*sl;
18895 	ilm_walker_t		ilw;
18896 
18897 	/*
18898 	 * make a copy of the original message
18899 	 */
18900 	mp2ctl = copymsg(mpctl);
18901 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18902 
18903 	/* ipGroupSource table */
18904 	optp = (struct opthdr *)&mpctl->b_rptr[
18905 	    sizeof (struct T_optmgmt_ack)];
18906 	optp->level = MIB2_IP;
18907 	optp->name = EXPER_IP_GROUP_SOURCES;
18908 
18909 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18910 	ill = ILL_START_WALK_V4(&ctx, ipst);
18911 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18912 		if (IS_UNDER_IPMP(ill))
18913 			continue;
18914 
18915 		ilm = ilm_walker_start(&ilw, ill);
18916 		for (ipif = ill->ill_ipif; ipif != NULL;
18917 		    ipif = ipif->ipif_next) {
18918 			if (ipif->ipif_zoneid != zoneid)
18919 				continue;	/* not this zone */
18920 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18921 			    OCTET_LENGTH);
18922 			ips.ipGroupSourceIfIndex.o_length =
18923 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18924 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18925 				ASSERT(ilm->ilm_ipif != NULL);
18926 				ASSERT(ilm->ilm_ill == NULL);
18927 				sl = ilm->ilm_filter;
18928 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18929 					continue;
18930 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18931 				for (i = 0; i < sl->sl_numsrc; i++) {
18932 					if (!IN6_IS_ADDR_V4MAPPED(
18933 					    &sl->sl_addr[i]))
18934 						continue;
18935 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18936 					    ips.ipGroupSourceAddress);
18937 					if (snmp_append_data2(mpctl->b_cont,
18938 					    &mp_tail, (char *)&ips,
18939 					    (int)sizeof (ips)) == 0) {
18940 						ip1dbg(("ip_snmp_get_mib2_"
18941 						    "ip_group_src: failed to "
18942 						    "allocate %u bytes\n",
18943 						    (uint_t)sizeof (ips)));
18944 					}
18945 				}
18946 			}
18947 		}
18948 		ilm_walker_finish(&ilw);
18949 	}
18950 	rw_exit(&ipst->ips_ill_g_lock);
18951 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18952 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18953 	    (int)optp->level, (int)optp->name, (int)optp->len));
18954 	qreply(q, mpctl);
18955 	return (mp2ctl);
18956 }
18957 
18958 /* IPv6 multicast filtered sources. */
18959 static mblk_t *
18960 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18961 {
18962 	struct opthdr		*optp;
18963 	mblk_t			*mp2ctl;
18964 	ill_t			*ill;
18965 	ilm_t			*ilm;
18966 	ipv6_grpsrc_t		ips6;
18967 	mblk_t			*mp_tail = NULL;
18968 	ill_walk_context_t	ctx;
18969 	zoneid_t		zoneid;
18970 	int			i;
18971 	slist_t			*sl;
18972 	ilm_walker_t		ilw;
18973 
18974 	/*
18975 	 * make a copy of the original message
18976 	 */
18977 	mp2ctl = copymsg(mpctl);
18978 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18979 
18980 	/* ip6GroupMember table */
18981 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18982 	optp->level = MIB2_IP6;
18983 	optp->name = EXPER_IP6_GROUP_SOURCES;
18984 
18985 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18986 	ill = ILL_START_WALK_V6(&ctx, ipst);
18987 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18988 		if (IS_UNDER_IPMP(ill))
18989 			continue;
18990 
18991 		ilm = ilm_walker_start(&ilw, ill);
18992 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18993 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18994 			ASSERT(ilm->ilm_ipif == NULL);
18995 			ASSERT(ilm->ilm_ill != NULL);
18996 			sl = ilm->ilm_filter;
18997 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18998 				continue;
18999 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
19000 			for (i = 0; i < sl->sl_numsrc; i++) {
19001 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
19002 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19003 				    (char *)&ips6, (int)sizeof (ips6))) {
19004 					ip1dbg(("ip_snmp_get_mib2_ip6_"
19005 					    "group_src: failed to allocate "
19006 					    "%u bytes\n",
19007 					    (uint_t)sizeof (ips6)));
19008 				}
19009 			}
19010 		}
19011 		ilm_walker_finish(&ilw);
19012 	}
19013 	rw_exit(&ipst->ips_ill_g_lock);
19014 
19015 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19016 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19017 	    (int)optp->level, (int)optp->name, (int)optp->len));
19018 	qreply(q, mpctl);
19019 	return (mp2ctl);
19020 }
19021 
19022 /* Multicast routing virtual interface table. */
19023 static mblk_t *
19024 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19025 {
19026 	struct opthdr		*optp;
19027 	mblk_t			*mp2ctl;
19028 
19029 	/*
19030 	 * make a copy of the original message
19031 	 */
19032 	mp2ctl = copymsg(mpctl);
19033 
19034 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19035 	optp->level = EXPER_DVMRP;
19036 	optp->name = EXPER_DVMRP_VIF;
19037 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
19038 		ip0dbg(("ip_mroute_vif: failed\n"));
19039 	}
19040 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19041 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19042 	    (int)optp->level, (int)optp->name, (int)optp->len));
19043 	qreply(q, mpctl);
19044 	return (mp2ctl);
19045 }
19046 
19047 /* Multicast routing table. */
19048 static mblk_t *
19049 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19050 {
19051 	struct opthdr		*optp;
19052 	mblk_t			*mp2ctl;
19053 
19054 	/*
19055 	 * make a copy of the original message
19056 	 */
19057 	mp2ctl = copymsg(mpctl);
19058 
19059 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19060 	optp->level = EXPER_DVMRP;
19061 	optp->name = EXPER_DVMRP_MRT;
19062 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19063 		ip0dbg(("ip_mroute_mrt: failed\n"));
19064 	}
19065 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19066 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19067 	    (int)optp->level, (int)optp->name, (int)optp->len));
19068 	qreply(q, mpctl);
19069 	return (mp2ctl);
19070 }
19071 
19072 /*
19073  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19074  * in one IRE walk.
19075  */
19076 static mblk_t *
19077 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
19078     ip_stack_t *ipst)
19079 {
19080 	struct opthdr	*optp;
19081 	mblk_t		*mp2ctl;	/* Returned */
19082 	mblk_t		*mp3ctl;	/* nettomedia */
19083 	mblk_t		*mp4ctl;	/* routeattrs */
19084 	iproutedata_t	ird;
19085 	zoneid_t	zoneid;
19086 
19087 	/*
19088 	 * make copies of the original message
19089 	 *	- mp2ctl is returned unchanged to the caller for his use
19090 	 *	- mpctl is sent upstream as ipRouteEntryTable
19091 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19092 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19093 	 */
19094 	mp2ctl = copymsg(mpctl);
19095 	mp3ctl = copymsg(mpctl);
19096 	mp4ctl = copymsg(mpctl);
19097 	if (mp3ctl == NULL || mp4ctl == NULL) {
19098 		freemsg(mp4ctl);
19099 		freemsg(mp3ctl);
19100 		freemsg(mp2ctl);
19101 		freemsg(mpctl);
19102 		return (NULL);
19103 	}
19104 
19105 	bzero(&ird, sizeof (ird));
19106 
19107 	ird.ird_route.lp_head = mpctl->b_cont;
19108 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19109 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19110 	/*
19111 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19112 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19113 	 * intended a temporary solution until a proper MIB API is provided
19114 	 * that provides complete filtering/caller-opt-in.
19115 	 */
19116 	if (level == EXPER_IP_AND_TESTHIDDEN)
19117 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19118 
19119 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19120 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19121 
19122 	/* ipRouteEntryTable in mpctl */
19123 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19124 	optp->level = MIB2_IP;
19125 	optp->name = MIB2_IP_ROUTE;
19126 	optp->len = msgdsize(ird.ird_route.lp_head);
19127 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19128 	    (int)optp->level, (int)optp->name, (int)optp->len));
19129 	qreply(q, mpctl);
19130 
19131 	/* ipNetToMediaEntryTable in mp3ctl */
19132 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19133 	optp->level = MIB2_IP;
19134 	optp->name = MIB2_IP_MEDIA;
19135 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19136 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19137 	    (int)optp->level, (int)optp->name, (int)optp->len));
19138 	qreply(q, mp3ctl);
19139 
19140 	/* ipRouteAttributeTable in mp4ctl */
19141 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19142 	optp->level = MIB2_IP;
19143 	optp->name = EXPER_IP_RTATTR;
19144 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19145 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19146 	    (int)optp->level, (int)optp->name, (int)optp->len));
19147 	if (optp->len == 0)
19148 		freemsg(mp4ctl);
19149 	else
19150 		qreply(q, mp4ctl);
19151 
19152 	return (mp2ctl);
19153 }
19154 
19155 /*
19156  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19157  * ipv6NetToMediaEntryTable in an NDP walk.
19158  */
19159 static mblk_t *
19160 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
19161     ip_stack_t *ipst)
19162 {
19163 	struct opthdr	*optp;
19164 	mblk_t		*mp2ctl;	/* Returned */
19165 	mblk_t		*mp3ctl;	/* nettomedia */
19166 	mblk_t		*mp4ctl;	/* routeattrs */
19167 	iproutedata_t	ird;
19168 	zoneid_t	zoneid;
19169 
19170 	/*
19171 	 * make copies of the original message
19172 	 *	- mp2ctl is returned unchanged to the caller for his use
19173 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19174 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19175 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19176 	 */
19177 	mp2ctl = copymsg(mpctl);
19178 	mp3ctl = copymsg(mpctl);
19179 	mp4ctl = copymsg(mpctl);
19180 	if (mp3ctl == NULL || mp4ctl == NULL) {
19181 		freemsg(mp4ctl);
19182 		freemsg(mp3ctl);
19183 		freemsg(mp2ctl);
19184 		freemsg(mpctl);
19185 		return (NULL);
19186 	}
19187 
19188 	bzero(&ird, sizeof (ird));
19189 
19190 	ird.ird_route.lp_head = mpctl->b_cont;
19191 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19192 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19193 	/*
19194 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19195 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19196 	 * intended a temporary solution until a proper MIB API is provided
19197 	 * that provides complete filtering/caller-opt-in.
19198 	 */
19199 	if (level == EXPER_IP_AND_TESTHIDDEN)
19200 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19201 
19202 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19203 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19204 
19205 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19206 	optp->level = MIB2_IP6;
19207 	optp->name = MIB2_IP6_ROUTE;
19208 	optp->len = msgdsize(ird.ird_route.lp_head);
19209 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19210 	    (int)optp->level, (int)optp->name, (int)optp->len));
19211 	qreply(q, mpctl);
19212 
19213 	/* ipv6NetToMediaEntryTable in mp3ctl */
19214 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19215 
19216 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19217 	optp->level = MIB2_IP6;
19218 	optp->name = MIB2_IP6_MEDIA;
19219 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19220 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19221 	    (int)optp->level, (int)optp->name, (int)optp->len));
19222 	qreply(q, mp3ctl);
19223 
19224 	/* ipv6RouteAttributeTable in mp4ctl */
19225 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19226 	optp->level = MIB2_IP6;
19227 	optp->name = EXPER_IP_RTATTR;
19228 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19229 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19230 	    (int)optp->level, (int)optp->name, (int)optp->len));
19231 	if (optp->len == 0)
19232 		freemsg(mp4ctl);
19233 	else
19234 		qreply(q, mp4ctl);
19235 
19236 	return (mp2ctl);
19237 }
19238 
19239 /*
19240  * IPv6 mib: One per ill
19241  */
19242 static mblk_t *
19243 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19244 {
19245 	struct opthdr		*optp;
19246 	mblk_t			*mp2ctl;
19247 	ill_t			*ill;
19248 	ill_walk_context_t	ctx;
19249 	mblk_t			*mp_tail = NULL;
19250 
19251 	/*
19252 	 * Make a copy of the original message
19253 	 */
19254 	mp2ctl = copymsg(mpctl);
19255 
19256 	/* fixed length IPv6 structure ... */
19257 
19258 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19259 	optp->level = MIB2_IP6;
19260 	optp->name = 0;
19261 	/* Include "unknown interface" ip6_mib */
19262 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19263 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19264 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19265 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19266 	    ipst->ips_ipv6_forward ? 1 : 2);
19267 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19268 	    ipst->ips_ipv6_def_hops);
19269 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19270 	    sizeof (mib2_ipIfStatsEntry_t));
19271 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19272 	    sizeof (mib2_ipv6AddrEntry_t));
19273 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19274 	    sizeof (mib2_ipv6RouteEntry_t));
19275 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19276 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19277 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19278 	    sizeof (ipv6_member_t));
19279 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19280 	    sizeof (ipv6_grpsrc_t));
19281 
19282 	/*
19283 	 * Synchronize 64- and 32-bit counters
19284 	 */
19285 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19286 	    ipIfStatsHCInReceives);
19287 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19288 	    ipIfStatsHCInDelivers);
19289 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19290 	    ipIfStatsHCOutRequests);
19291 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19292 	    ipIfStatsHCOutForwDatagrams);
19293 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19294 	    ipIfStatsHCOutMcastPkts);
19295 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19296 	    ipIfStatsHCInMcastPkts);
19297 
19298 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19299 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19300 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19301 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19302 	}
19303 
19304 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19305 	ill = ILL_START_WALK_V6(&ctx, ipst);
19306 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19307 		ill->ill_ip_mib->ipIfStatsIfIndex =
19308 		    ill->ill_phyint->phyint_ifindex;
19309 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19310 		    ipst->ips_ipv6_forward ? 1 : 2);
19311 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19312 		    ill->ill_max_hops);
19313 
19314 		/*
19315 		 * Synchronize 64- and 32-bit counters
19316 		 */
19317 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19318 		    ipIfStatsHCInReceives);
19319 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19320 		    ipIfStatsHCInDelivers);
19321 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19322 		    ipIfStatsHCOutRequests);
19323 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19324 		    ipIfStatsHCOutForwDatagrams);
19325 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19326 		    ipIfStatsHCOutMcastPkts);
19327 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19328 		    ipIfStatsHCInMcastPkts);
19329 
19330 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19331 		    (char *)ill->ill_ip_mib,
19332 		    (int)sizeof (*ill->ill_ip_mib))) {
19333 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19334 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19335 		}
19336 	}
19337 	rw_exit(&ipst->ips_ill_g_lock);
19338 
19339 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19340 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19341 	    (int)optp->level, (int)optp->name, (int)optp->len));
19342 	qreply(q, mpctl);
19343 	return (mp2ctl);
19344 }
19345 
19346 /*
19347  * ICMPv6 mib: One per ill
19348  */
19349 static mblk_t *
19350 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19351 {
19352 	struct opthdr		*optp;
19353 	mblk_t			*mp2ctl;
19354 	ill_t			*ill;
19355 	ill_walk_context_t	ctx;
19356 	mblk_t			*mp_tail = NULL;
19357 	/*
19358 	 * Make a copy of the original message
19359 	 */
19360 	mp2ctl = copymsg(mpctl);
19361 
19362 	/* fixed length ICMPv6 structure ... */
19363 
19364 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19365 	optp->level = MIB2_ICMP6;
19366 	optp->name = 0;
19367 	/* Include "unknown interface" icmp6_mib */
19368 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19369 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19370 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19371 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19372 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19373 	    (char *)&ipst->ips_icmp6_mib,
19374 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19375 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19376 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19377 	}
19378 
19379 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19380 	ill = ILL_START_WALK_V6(&ctx, ipst);
19381 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19382 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19383 		    ill->ill_phyint->phyint_ifindex;
19384 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19385 		    (char *)ill->ill_icmp6_mib,
19386 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19387 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19388 			    "%u bytes\n",
19389 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19390 		}
19391 	}
19392 	rw_exit(&ipst->ips_ill_g_lock);
19393 
19394 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19395 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19396 	    (int)optp->level, (int)optp->name, (int)optp->len));
19397 	qreply(q, mpctl);
19398 	return (mp2ctl);
19399 }
19400 
19401 /*
19402  * ire_walk routine to create both ipRouteEntryTable and
19403  * ipRouteAttributeTable in one IRE walk
19404  */
19405 static void
19406 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19407 {
19408 	ill_t				*ill;
19409 	ipif_t				*ipif;
19410 	mib2_ipRouteEntry_t		*re;
19411 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19412 	ipaddr_t			gw_addr;
19413 	tsol_ire_gw_secattr_t		*attrp;
19414 	tsol_gc_t			*gc = NULL;
19415 	tsol_gcgrp_t			*gcgrp = NULL;
19416 	uint_t				sacnt = 0;
19417 	int				i;
19418 
19419 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19420 
19421 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19422 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19423 		return;
19424 	}
19425 
19426 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19427 		return;
19428 
19429 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19430 		mutex_enter(&attrp->igsa_lock);
19431 		if ((gc = attrp->igsa_gc) != NULL) {
19432 			gcgrp = gc->gc_grp;
19433 			ASSERT(gcgrp != NULL);
19434 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19435 			sacnt = 1;
19436 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19437 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19438 			gc = gcgrp->gcgrp_head;
19439 			sacnt = gcgrp->gcgrp_count;
19440 		}
19441 		mutex_exit(&attrp->igsa_lock);
19442 
19443 		/* do nothing if there's no gc to report */
19444 		if (gc == NULL) {
19445 			ASSERT(sacnt == 0);
19446 			if (gcgrp != NULL) {
19447 				/* we might as well drop the lock now */
19448 				rw_exit(&gcgrp->gcgrp_rwlock);
19449 				gcgrp = NULL;
19450 			}
19451 			attrp = NULL;
19452 		}
19453 
19454 		ASSERT(gc == NULL || (gcgrp != NULL &&
19455 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19456 	}
19457 	ASSERT(sacnt == 0 || gc != NULL);
19458 
19459 	if (sacnt != 0 &&
19460 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19461 		kmem_free(re, sizeof (*re));
19462 		rw_exit(&gcgrp->gcgrp_rwlock);
19463 		return;
19464 	}
19465 
19466 	/*
19467 	 * Return all IRE types for route table... let caller pick and choose
19468 	 */
19469 	re->ipRouteDest = ire->ire_addr;
19470 	ipif = ire->ire_ipif;
19471 	re->ipRouteIfIndex.o_length = 0;
19472 	if (ire->ire_type == IRE_CACHE) {
19473 		ill = (ill_t *)ire->ire_stq->q_ptr;
19474 		re->ipRouteIfIndex.o_length =
19475 		    ill->ill_name_length == 0 ? 0 :
19476 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19477 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19478 		    re->ipRouteIfIndex.o_length);
19479 	} else if (ipif != NULL) {
19480 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19481 		re->ipRouteIfIndex.o_length =
19482 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19483 	}
19484 	re->ipRouteMetric1 = -1;
19485 	re->ipRouteMetric2 = -1;
19486 	re->ipRouteMetric3 = -1;
19487 	re->ipRouteMetric4 = -1;
19488 
19489 	gw_addr = ire->ire_gateway_addr;
19490 
19491 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19492 		re->ipRouteNextHop = ire->ire_src_addr;
19493 	else
19494 		re->ipRouteNextHop = gw_addr;
19495 	/* indirect(4), direct(3), or invalid(2) */
19496 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19497 		re->ipRouteType = 2;
19498 	else
19499 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19500 	re->ipRouteProto = -1;
19501 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19502 	re->ipRouteMask = ire->ire_mask;
19503 	re->ipRouteMetric5 = -1;
19504 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19505 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19506 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19507 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19508 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19509 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19510 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19511 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19512 
19513 	if (ire->ire_flags & RTF_DYNAMIC) {
19514 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19515 	} else {
19516 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19517 	}
19518 
19519 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19520 	    (char *)re, (int)sizeof (*re))) {
19521 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19522 		    (uint_t)sizeof (*re)));
19523 	}
19524 
19525 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19526 		iaeptr->iae_routeidx = ird->ird_idx;
19527 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19528 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19529 	}
19530 
19531 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19532 	    (char *)iae, sacnt * sizeof (*iae))) {
19533 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19534 		    (unsigned)(sacnt * sizeof (*iae))));
19535 	}
19536 
19537 	/* bump route index for next pass */
19538 	ird->ird_idx++;
19539 
19540 	kmem_free(re, sizeof (*re));
19541 	if (sacnt != 0)
19542 		kmem_free(iae, sacnt * sizeof (*iae));
19543 
19544 	if (gcgrp != NULL)
19545 		rw_exit(&gcgrp->gcgrp_rwlock);
19546 }
19547 
19548 /*
19549  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19550  */
19551 static void
19552 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19553 {
19554 	ill_t				*ill;
19555 	ipif_t				*ipif;
19556 	mib2_ipv6RouteEntry_t		*re;
19557 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19558 	in6_addr_t			gw_addr_v6;
19559 	tsol_ire_gw_secattr_t		*attrp;
19560 	tsol_gc_t			*gc = NULL;
19561 	tsol_gcgrp_t			*gcgrp = NULL;
19562 	uint_t				sacnt = 0;
19563 	int				i;
19564 
19565 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19566 
19567 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19568 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19569 		return;
19570 	}
19571 
19572 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19573 		return;
19574 
19575 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19576 		mutex_enter(&attrp->igsa_lock);
19577 		if ((gc = attrp->igsa_gc) != NULL) {
19578 			gcgrp = gc->gc_grp;
19579 			ASSERT(gcgrp != NULL);
19580 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19581 			sacnt = 1;
19582 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19583 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19584 			gc = gcgrp->gcgrp_head;
19585 			sacnt = gcgrp->gcgrp_count;
19586 		}
19587 		mutex_exit(&attrp->igsa_lock);
19588 
19589 		/* do nothing if there's no gc to report */
19590 		if (gc == NULL) {
19591 			ASSERT(sacnt == 0);
19592 			if (gcgrp != NULL) {
19593 				/* we might as well drop the lock now */
19594 				rw_exit(&gcgrp->gcgrp_rwlock);
19595 				gcgrp = NULL;
19596 			}
19597 			attrp = NULL;
19598 		}
19599 
19600 		ASSERT(gc == NULL || (gcgrp != NULL &&
19601 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19602 	}
19603 	ASSERT(sacnt == 0 || gc != NULL);
19604 
19605 	if (sacnt != 0 &&
19606 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19607 		kmem_free(re, sizeof (*re));
19608 		rw_exit(&gcgrp->gcgrp_rwlock);
19609 		return;
19610 	}
19611 
19612 	/*
19613 	 * Return all IRE types for route table... let caller pick and choose
19614 	 */
19615 	re->ipv6RouteDest = ire->ire_addr_v6;
19616 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19617 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19618 	re->ipv6RouteIfIndex.o_length = 0;
19619 	ipif = ire->ire_ipif;
19620 	if (ire->ire_type == IRE_CACHE) {
19621 		ill = (ill_t *)ire->ire_stq->q_ptr;
19622 		re->ipv6RouteIfIndex.o_length =
19623 		    ill->ill_name_length == 0 ? 0 :
19624 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19625 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19626 		    re->ipv6RouteIfIndex.o_length);
19627 	} else if (ipif != NULL) {
19628 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19629 		re->ipv6RouteIfIndex.o_length =
19630 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19631 	}
19632 
19633 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19634 
19635 	mutex_enter(&ire->ire_lock);
19636 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19637 	mutex_exit(&ire->ire_lock);
19638 
19639 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19640 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19641 	else
19642 		re->ipv6RouteNextHop = gw_addr_v6;
19643 
19644 	/* remote(4), local(3), or discard(2) */
19645 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19646 		re->ipv6RouteType = 2;
19647 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19648 		re->ipv6RouteType = 3;
19649 	else
19650 		re->ipv6RouteType = 4;
19651 
19652 	re->ipv6RouteProtocol	= -1;
19653 	re->ipv6RoutePolicy	= 0;
19654 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19655 	re->ipv6RouteNextHopRDI	= 0;
19656 	re->ipv6RouteWeight	= 0;
19657 	re->ipv6RouteMetric	= 0;
19658 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19659 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19660 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19661 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19662 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19663 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19664 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19665 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19666 
19667 	if (ire->ire_flags & RTF_DYNAMIC) {
19668 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19669 	} else {
19670 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19671 	}
19672 
19673 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19674 	    (char *)re, (int)sizeof (*re))) {
19675 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19676 		    (uint_t)sizeof (*re)));
19677 	}
19678 
19679 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19680 		iaeptr->iae_routeidx = ird->ird_idx;
19681 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19682 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19683 	}
19684 
19685 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19686 	    (char *)iae, sacnt * sizeof (*iae))) {
19687 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19688 		    (unsigned)(sacnt * sizeof (*iae))));
19689 	}
19690 
19691 	/* bump route index for next pass */
19692 	ird->ird_idx++;
19693 
19694 	kmem_free(re, sizeof (*re));
19695 	if (sacnt != 0)
19696 		kmem_free(iae, sacnt * sizeof (*iae));
19697 
19698 	if (gcgrp != NULL)
19699 		rw_exit(&gcgrp->gcgrp_rwlock);
19700 }
19701 
19702 /*
19703  * ndp_walk routine to create ipv6NetToMediaEntryTable
19704  */
19705 static int
19706 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19707 {
19708 	ill_t				*ill;
19709 	mib2_ipv6NetToMediaEntry_t	ntme;
19710 	dl_unitdata_req_t		*dl;
19711 
19712 	ill = nce->nce_ill;
19713 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19714 		return (0);
19715 
19716 	/*
19717 	 * Neighbor cache entry attached to IRE with on-link
19718 	 * destination.
19719 	 */
19720 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19721 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19722 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19723 	    (nce->nce_res_mp != NULL)) {
19724 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19725 		ntme.ipv6NetToMediaPhysAddress.o_length =
19726 		    dl->dl_dest_addr_length;
19727 	} else {
19728 		ntme.ipv6NetToMediaPhysAddress.o_length =
19729 		    ill->ill_phys_addr_length;
19730 	}
19731 	if (nce->nce_res_mp != NULL) {
19732 		bcopy((char *)nce->nce_res_mp->b_rptr +
19733 		    NCE_LL_ADDR_OFFSET(ill),
19734 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19735 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19736 	} else {
19737 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19738 		    ill->ill_phys_addr_length);
19739 	}
19740 	/*
19741 	 * Note: Returns ND_* states. Should be:
19742 	 * reachable(1), stale(2), delay(3), probe(4),
19743 	 * invalid(5), unknown(6)
19744 	 */
19745 	ntme.ipv6NetToMediaState = nce->nce_state;
19746 	ntme.ipv6NetToMediaLastUpdated = 0;
19747 
19748 	/* other(1), dynamic(2), static(3), local(4) */
19749 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19750 		ntme.ipv6NetToMediaType = 4;
19751 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19752 		ntme.ipv6NetToMediaType = 1;
19753 	} else {
19754 		ntme.ipv6NetToMediaType = 2;
19755 	}
19756 
19757 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19758 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19759 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19760 		    (uint_t)sizeof (ntme)));
19761 	}
19762 	return (0);
19763 }
19764 
19765 /*
19766  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19767  */
19768 /* ARGSUSED */
19769 int
19770 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19771 {
19772 	switch (level) {
19773 	case MIB2_IP:
19774 	case MIB2_ICMP:
19775 		switch (name) {
19776 		default:
19777 			break;
19778 		}
19779 		return (1);
19780 	default:
19781 		return (1);
19782 	}
19783 }
19784 
19785 /*
19786  * When there exists both a 64- and 32-bit counter of a particular type
19787  * (i.e., InReceives), only the 64-bit counters are added.
19788  */
19789 void
19790 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19791 {
19792 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19793 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19794 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19795 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19796 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19797 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19798 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19799 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19800 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19801 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19802 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19803 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19804 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19805 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19806 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19807 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19808 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19809 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19810 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19811 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19812 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19813 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19814 	    o2->ipIfStatsInWrongIPVersion);
19815 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19816 	    o2->ipIfStatsInWrongIPVersion);
19817 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19818 	    o2->ipIfStatsOutSwitchIPVersion);
19819 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19820 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19821 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19822 	    o2->ipIfStatsHCInForwDatagrams);
19823 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19824 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19825 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19826 	    o2->ipIfStatsHCOutForwDatagrams);
19827 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19828 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19829 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19830 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19831 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19832 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19833 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19834 	    o2->ipIfStatsHCOutMcastOctets);
19835 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19836 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19837 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19838 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19839 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19840 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19841 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19842 }
19843 
19844 void
19845 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19846 {
19847 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19848 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19849 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19850 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19851 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19852 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19853 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19854 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19855 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19856 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19857 	    o2->ipv6IfIcmpInRouterSolicits);
19858 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19859 	    o2->ipv6IfIcmpInRouterAdvertisements);
19860 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19861 	    o2->ipv6IfIcmpInNeighborSolicits);
19862 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19863 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19864 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19865 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19866 	    o2->ipv6IfIcmpInGroupMembQueries);
19867 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19868 	    o2->ipv6IfIcmpInGroupMembResponses);
19869 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19870 	    o2->ipv6IfIcmpInGroupMembReductions);
19871 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19872 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19873 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19874 	    o2->ipv6IfIcmpOutDestUnreachs);
19875 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19876 	    o2->ipv6IfIcmpOutAdminProhibs);
19877 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19878 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19879 	    o2->ipv6IfIcmpOutParmProblems);
19880 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19881 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19882 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19883 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19884 	    o2->ipv6IfIcmpOutRouterSolicits);
19885 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19886 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19887 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19888 	    o2->ipv6IfIcmpOutNeighborSolicits);
19889 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19890 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19891 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19892 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19893 	    o2->ipv6IfIcmpOutGroupMembQueries);
19894 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19895 	    o2->ipv6IfIcmpOutGroupMembResponses);
19896 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19897 	    o2->ipv6IfIcmpOutGroupMembReductions);
19898 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19899 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19900 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19901 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19902 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19903 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19904 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19905 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19906 	    o2->ipv6IfIcmpInGroupMembTotal);
19907 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19908 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19909 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19910 	    o2->ipv6IfIcmpInGroupMembBadReports);
19911 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19912 	    o2->ipv6IfIcmpInGroupMembOurReports);
19913 }
19914 
19915 /*
19916  * Called before the options are updated to check if this packet will
19917  * be source routed from here.
19918  * This routine assumes that the options are well formed i.e. that they
19919  * have already been checked.
19920  */
19921 static boolean_t
19922 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19923 {
19924 	ipoptp_t	opts;
19925 	uchar_t		*opt;
19926 	uint8_t		optval;
19927 	uint8_t		optlen;
19928 	ipaddr_t	dst;
19929 	ire_t		*ire;
19930 
19931 	if (IS_SIMPLE_IPH(ipha)) {
19932 		ip2dbg(("not source routed\n"));
19933 		return (B_FALSE);
19934 	}
19935 	dst = ipha->ipha_dst;
19936 	for (optval = ipoptp_first(&opts, ipha);
19937 	    optval != IPOPT_EOL;
19938 	    optval = ipoptp_next(&opts)) {
19939 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19940 		opt = opts.ipoptp_cur;
19941 		optlen = opts.ipoptp_len;
19942 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19943 		    optval, optlen));
19944 		switch (optval) {
19945 			uint32_t off;
19946 		case IPOPT_SSRR:
19947 		case IPOPT_LSRR:
19948 			/*
19949 			 * If dst is one of our addresses and there are some
19950 			 * entries left in the source route return (true).
19951 			 */
19952 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19953 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19954 			if (ire == NULL) {
19955 				ip2dbg(("ip_source_routed: not next"
19956 				    " source route 0x%x\n",
19957 				    ntohl(dst)));
19958 				return (B_FALSE);
19959 			}
19960 			ire_refrele(ire);
19961 			off = opt[IPOPT_OFFSET];
19962 			off--;
19963 			if (optlen < IP_ADDR_LEN ||
19964 			    off > optlen - IP_ADDR_LEN) {
19965 				/* End of source route */
19966 				ip1dbg(("ip_source_routed: end of SR\n"));
19967 				return (B_FALSE);
19968 			}
19969 			return (B_TRUE);
19970 		}
19971 	}
19972 	ip2dbg(("not source routed\n"));
19973 	return (B_FALSE);
19974 }
19975 
19976 /*
19977  * Check if the packet contains any source route.
19978  */
19979 static boolean_t
19980 ip_source_route_included(ipha_t *ipha)
19981 {
19982 	ipoptp_t	opts;
19983 	uint8_t		optval;
19984 
19985 	if (IS_SIMPLE_IPH(ipha))
19986 		return (B_FALSE);
19987 	for (optval = ipoptp_first(&opts, ipha);
19988 	    optval != IPOPT_EOL;
19989 	    optval = ipoptp_next(&opts)) {
19990 		switch (optval) {
19991 		case IPOPT_SSRR:
19992 		case IPOPT_LSRR:
19993 			return (B_TRUE);
19994 		}
19995 	}
19996 	return (B_FALSE);
19997 }
19998 
19999 /*
20000  * Called when the IRE expiration timer fires.
20001  */
20002 void
20003 ip_trash_timer_expire(void *args)
20004 {
20005 	int			flush_flag = 0;
20006 	ire_expire_arg_t	iea;
20007 	ip_stack_t		*ipst = (ip_stack_t *)args;
20008 
20009 	iea.iea_ipst = ipst;	/* No netstack_hold */
20010 
20011 	/*
20012 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
20013 	 * This lock makes sure that a new invocation of this function
20014 	 * that occurs due to an almost immediate timer firing will not
20015 	 * progress beyond this point until the current invocation is done
20016 	 */
20017 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20018 	ipst->ips_ip_ire_expire_id = 0;
20019 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20020 
20021 	/* Periodic timer */
20022 	if (ipst->ips_ip_ire_arp_time_elapsed >=
20023 	    ipst->ips_ip_ire_arp_interval) {
20024 		/*
20025 		 * Remove all IRE_CACHE entries since they might
20026 		 * contain arp information.
20027 		 */
20028 		flush_flag |= FLUSH_ARP_TIME;
20029 		ipst->ips_ip_ire_arp_time_elapsed = 0;
20030 		IP_STAT(ipst, ip_ire_arp_timer_expired);
20031 	}
20032 	if (ipst->ips_ip_ire_rd_time_elapsed >=
20033 	    ipst->ips_ip_ire_redir_interval) {
20034 		/* Remove all redirects */
20035 		flush_flag |= FLUSH_REDIRECT_TIME;
20036 		ipst->ips_ip_ire_rd_time_elapsed = 0;
20037 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
20038 	}
20039 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
20040 	    ipst->ips_ip_ire_pathmtu_interval) {
20041 		/* Increase path mtu */
20042 		flush_flag |= FLUSH_MTU_TIME;
20043 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20044 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20045 	}
20046 
20047 	/*
20048 	 * Optimize for the case when there are no redirects in the
20049 	 * ftable, that is, no need to walk the ftable in that case.
20050 	 */
20051 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20052 		iea.iea_flush_flag = flush_flag;
20053 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20054 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20055 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20056 		    NULL, ALL_ZONES, ipst);
20057 	}
20058 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20059 	    ipst->ips_ip_redirect_cnt > 0) {
20060 		iea.iea_flush_flag = flush_flag;
20061 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20062 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20063 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20064 	}
20065 	if (flush_flag & FLUSH_MTU_TIME) {
20066 		/*
20067 		 * Walk all IPv6 IRE's and update them
20068 		 * Note that ARP and redirect timers are not
20069 		 * needed since NUD handles stale entries.
20070 		 */
20071 		flush_flag = FLUSH_MTU_TIME;
20072 		iea.iea_flush_flag = flush_flag;
20073 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20074 		    ALL_ZONES, ipst);
20075 	}
20076 
20077 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20078 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20079 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20080 
20081 	/*
20082 	 * Hold the lock to serialize timeout calls and prevent
20083 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20084 	 * for the timer to fire and a new invocation of this function
20085 	 * to start before the return value of timeout has been stored
20086 	 * in ip_ire_expire_id by the current invocation.
20087 	 */
20088 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20089 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20090 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20091 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20092 }
20093 
20094 /*
20095  * Called by the memory allocator subsystem directly, when the system
20096  * is running low on memory.
20097  */
20098 /* ARGSUSED */
20099 void
20100 ip_trash_ire_reclaim(void *args)
20101 {
20102 	netstack_handle_t nh;
20103 	netstack_t *ns;
20104 
20105 	netstack_next_init(&nh);
20106 	while ((ns = netstack_next(&nh)) != NULL) {
20107 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20108 		netstack_rele(ns);
20109 	}
20110 	netstack_next_fini(&nh);
20111 }
20112 
20113 static void
20114 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20115 {
20116 	ire_cache_count_t icc;
20117 	ire_cache_reclaim_t icr;
20118 	ncc_cache_count_t ncc;
20119 	nce_cache_reclaim_t ncr;
20120 	uint_t delete_cnt;
20121 	/*
20122 	 * Memory reclaim call back.
20123 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20124 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20125 	 * entries, determine what fraction to free for
20126 	 * each category of IRE_CACHE entries giving absolute priority
20127 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20128 	 * entry will be freed unless all offlink entries are freed).
20129 	 */
20130 	icc.icc_total = 0;
20131 	icc.icc_unused = 0;
20132 	icc.icc_offlink = 0;
20133 	icc.icc_pmtu = 0;
20134 	icc.icc_onlink = 0;
20135 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20136 
20137 	/*
20138 	 * Free NCEs for IPv6 like the onlink ires.
20139 	 */
20140 	ncc.ncc_total = 0;
20141 	ncc.ncc_host = 0;
20142 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20143 
20144 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20145 	    icc.icc_pmtu + icc.icc_onlink);
20146 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20147 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20148 	if (delete_cnt == 0)
20149 		return;
20150 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20151 	/* Always delete all unused offlink entries */
20152 	icr.icr_ipst = ipst;
20153 	icr.icr_unused = 1;
20154 	if (delete_cnt <= icc.icc_unused) {
20155 		/*
20156 		 * Only need to free unused entries.  In other words,
20157 		 * there are enough unused entries to free to meet our
20158 		 * target number of freed ire cache entries.
20159 		 */
20160 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20161 		ncr.ncr_host = 0;
20162 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20163 		/*
20164 		 * Only need to free unused entries, plus a fraction of offlink
20165 		 * entries.  It follows from the first if statement that
20166 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20167 		 */
20168 		delete_cnt -= icc.icc_unused;
20169 		/* Round up # deleted by truncating fraction */
20170 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20171 		icr.icr_pmtu = icr.icr_onlink = 0;
20172 		ncr.ncr_host = 0;
20173 	} else if (delete_cnt <=
20174 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20175 		/*
20176 		 * Free all unused and offlink entries, plus a fraction of
20177 		 * pmtu entries.  It follows from the previous if statement
20178 		 * that icc_pmtu is non-zero, and that
20179 		 * delete_cnt != icc_unused + icc_offlink.
20180 		 */
20181 		icr.icr_offlink = 1;
20182 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20183 		/* Round up # deleted by truncating fraction */
20184 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20185 		icr.icr_onlink = 0;
20186 		ncr.ncr_host = 0;
20187 	} else {
20188 		/*
20189 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20190 		 * of onlink entries.  If we're here, then we know that
20191 		 * icc_onlink is non-zero, and that
20192 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20193 		 */
20194 		icr.icr_offlink = icr.icr_pmtu = 1;
20195 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20196 		    icc.icc_pmtu;
20197 		/* Round up # deleted by truncating fraction */
20198 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20199 		/* Using the same delete fraction as for onlink IREs */
20200 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20201 	}
20202 #ifdef DEBUG
20203 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20204 	    "fractions %d/%d/%d/%d\n",
20205 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20206 	    icc.icc_unused, icc.icc_offlink,
20207 	    icc.icc_pmtu, icc.icc_onlink,
20208 	    icr.icr_unused, icr.icr_offlink,
20209 	    icr.icr_pmtu, icr.icr_onlink));
20210 #endif
20211 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20212 	if (ncr.ncr_host != 0)
20213 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20214 		    (uchar_t *)&ncr, ipst);
20215 #ifdef DEBUG
20216 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20217 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20218 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20219 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20220 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20221 	    icc.icc_pmtu, icc.icc_onlink));
20222 #endif
20223 }
20224 
20225 /*
20226  * ip_unbind is called when a copy of an unbind request is received from the
20227  * upper level protocol.  We remove this conn from any fanout hash list it is
20228  * on, and zero out the bind information.  No reply is expected up above.
20229  */
20230 void
20231 ip_unbind(conn_t *connp)
20232 {
20233 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20234 
20235 	if (is_system_labeled() && connp->conn_anon_port) {
20236 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20237 		    connp->conn_mlp_type, connp->conn_ulp,
20238 		    ntohs(connp->conn_lport), B_FALSE);
20239 		connp->conn_anon_port = 0;
20240 	}
20241 	connp->conn_mlp_type = mlptSingle;
20242 
20243 	ipcl_hash_remove(connp);
20244 
20245 }
20246 
20247 /*
20248  * Write side put procedure.  Outbound data, IOCTLs, responses from
20249  * resolvers, etc, come down through here.
20250  *
20251  * arg2 is always a queue_t *.
20252  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20253  * the zoneid.
20254  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20255  */
20256 void
20257 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20258 {
20259 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20260 }
20261 
20262 void
20263 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20264     ip_opt_info_t *infop)
20265 {
20266 	conn_t		*connp = NULL;
20267 	queue_t		*q = (queue_t *)arg2;
20268 	ipha_t		*ipha;
20269 #define	rptr	((uchar_t *)ipha)
20270 	ire_t		*ire = NULL;
20271 	ire_t		*sctp_ire = NULL;
20272 	uint32_t	v_hlen_tos_len;
20273 	ipaddr_t	dst;
20274 	mblk_t		*first_mp = NULL;
20275 	boolean_t	mctl_present;
20276 	ipsec_out_t	*io;
20277 	int		match_flags;
20278 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20279 	ipif_t		*dst_ipif;
20280 	boolean_t	multirt_need_resolve = B_FALSE;
20281 	mblk_t		*copy_mp = NULL;
20282 	int		err;
20283 	zoneid_t	zoneid;
20284 	boolean_t	need_decref = B_FALSE;
20285 	boolean_t	ignore_dontroute = B_FALSE;
20286 	boolean_t	ignore_nexthop = B_FALSE;
20287 	boolean_t	ip_nexthop = B_FALSE;
20288 	ipaddr_t	nexthop_addr;
20289 	ip_stack_t	*ipst;
20290 
20291 #ifdef	_BIG_ENDIAN
20292 #define	V_HLEN	(v_hlen_tos_len >> 24)
20293 #else
20294 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20295 #endif
20296 
20297 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20298 	    "ip_wput_start: q %p", q);
20299 
20300 	/*
20301 	 * ip_wput fast path
20302 	 */
20303 
20304 	/* is packet from ARP ? */
20305 	if (q->q_next != NULL) {
20306 		zoneid = (zoneid_t)(uintptr_t)arg;
20307 		goto qnext;
20308 	}
20309 
20310 	connp = (conn_t *)arg;
20311 	ASSERT(connp != NULL);
20312 	zoneid = connp->conn_zoneid;
20313 	ipst = connp->conn_netstack->netstack_ip;
20314 	ASSERT(ipst != NULL);
20315 
20316 	/* is queue flow controlled? */
20317 	if ((q->q_first != NULL || connp->conn_draining) &&
20318 	    (caller == IP_WPUT)) {
20319 		ASSERT(!need_decref);
20320 		ASSERT(!IP_FLOW_CONTROLLED_ULP(connp->conn_ulp));
20321 		(void) putq(q, mp);
20322 		return;
20323 	}
20324 
20325 	/* Multidata transmit? */
20326 	if (DB_TYPE(mp) == M_MULTIDATA) {
20327 		/*
20328 		 * We should never get here, since all Multidata messages
20329 		 * originating from tcp should have been directed over to
20330 		 * tcp_multisend() in the first place.
20331 		 */
20332 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20333 		freemsg(mp);
20334 		return;
20335 	} else if (DB_TYPE(mp) != M_DATA)
20336 		goto notdata;
20337 
20338 	if (mp->b_flag & MSGHASREF) {
20339 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20340 		mp->b_flag &= ~MSGHASREF;
20341 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20342 		need_decref = B_TRUE;
20343 	}
20344 	ipha = (ipha_t *)mp->b_rptr;
20345 
20346 	/* is IP header non-aligned or mblk smaller than basic IP header */
20347 #ifndef SAFETY_BEFORE_SPEED
20348 	if (!OK_32PTR(rptr) ||
20349 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20350 		goto hdrtoosmall;
20351 #endif
20352 
20353 	ASSERT(OK_32PTR(ipha));
20354 
20355 	/*
20356 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20357 	 * wrong version, we'll catch it again in ip_output_v6.
20358 	 *
20359 	 * Note that this is *only* locally-generated output here, and never
20360 	 * forwarded data, and that we need to deal only with transports that
20361 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20362 	 * label.)
20363 	 */
20364 	if (is_system_labeled() &&
20365 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20366 	    !connp->conn_ulp_labeled) {
20367 		err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20368 		    connp->conn_mac_exempt, ipst);
20369 		ipha = (ipha_t *)mp->b_rptr;
20370 		if (err != 0) {
20371 			first_mp = mp;
20372 			if (err == EINVAL)
20373 				goto icmp_parameter_problem;
20374 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20375 			goto discard_pkt;
20376 		}
20377 	}
20378 
20379 	ASSERT(infop != NULL);
20380 
20381 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20382 		/*
20383 		 * IP_PKTINFO ancillary option is present.
20384 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20385 		 * allows using address of any zone as the source address.
20386 		 */
20387 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20388 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20389 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20390 		if (ire == NULL)
20391 			goto drop_pkt;
20392 		ire_refrele(ire);
20393 		ire = NULL;
20394 	}
20395 
20396 	/*
20397 	 * IP_BOUND_IF has precedence over the ill index passed in IP_PKTINFO.
20398 	 */
20399 	if (infop->ip_opt_ill_index != 0 && connp->conn_outgoing_ill == NULL) {
20400 		xmit_ill = ill_lookup_on_ifindex(infop->ip_opt_ill_index,
20401 		    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20402 
20403 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20404 			goto drop_pkt;
20405 		/*
20406 		 * check that there is an ipif belonging
20407 		 * to our zone. IPCL_ZONEID is not used because
20408 		 * IP_ALLZONES option is valid only when the ill is
20409 		 * accessible from all zones i.e has a valid ipif in
20410 		 * all zones.
20411 		 */
20412 		if (!ipif_lookup_zoneid(xmit_ill, zoneid, 0, NULL)) {
20413 			goto drop_pkt;
20414 		}
20415 	}
20416 
20417 	/*
20418 	 * If there is a policy, try to attach an ipsec_out in
20419 	 * the front. At the end, first_mp either points to a
20420 	 * M_DATA message or IPSEC_OUT message linked to a
20421 	 * M_DATA message. We have to do it now as we might
20422 	 * lose the "conn" if we go through ip_newroute.
20423 	 */
20424 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20425 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20426 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20427 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20428 			if (need_decref)
20429 				CONN_DEC_REF(connp);
20430 			return;
20431 		} else {
20432 			ASSERT(mp->b_datap->db_type == M_CTL);
20433 			first_mp = mp;
20434 			mp = mp->b_cont;
20435 			mctl_present = B_TRUE;
20436 		}
20437 	} else {
20438 		first_mp = mp;
20439 		mctl_present = B_FALSE;
20440 	}
20441 
20442 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20443 
20444 	/* is wrong version or IP options present */
20445 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20446 		goto version_hdrlen_check;
20447 	dst = ipha->ipha_dst;
20448 
20449 	/* If IP_BOUND_IF has been set, use that ill. */
20450 	if (connp->conn_outgoing_ill != NULL) {
20451 		xmit_ill = conn_get_held_ill(connp,
20452 		    &connp->conn_outgoing_ill, &err);
20453 		if (err == ILL_LOOKUP_FAILED)
20454 			goto drop_pkt;
20455 
20456 		goto send_from_ill;
20457 	}
20458 
20459 	/* is packet multicast? */
20460 	if (CLASSD(dst))
20461 		goto multicast;
20462 
20463 	/*
20464 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20465 	 * takes precedence over conn_dontroute and conn_nexthop_set
20466 	 */
20467 	if (xmit_ill != NULL)
20468 		goto send_from_ill;
20469 
20470 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20471 		/*
20472 		 * If the destination is a broadcast, local, or loopback
20473 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20474 		 * standard path.
20475 		 */
20476 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20477 		if ((ire == NULL) || (ire->ire_type &
20478 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20479 			if (ire != NULL) {
20480 				ire_refrele(ire);
20481 				/* No more access to ire */
20482 				ire = NULL;
20483 			}
20484 			/*
20485 			 * bypass routing checks and go directly to interface.
20486 			 */
20487 			if (connp->conn_dontroute)
20488 				goto dontroute;
20489 
20490 			ASSERT(connp->conn_nexthop_set);
20491 			ip_nexthop = B_TRUE;
20492 			nexthop_addr = connp->conn_nexthop_v4;
20493 			goto send_from_ill;
20494 		}
20495 
20496 		/* Must be a broadcast, a loopback or a local ire */
20497 		ire_refrele(ire);
20498 		/* No more access to ire */
20499 		ire = NULL;
20500 	}
20501 
20502 	/*
20503 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20504 	 * this for the tcp global queue and listen end point
20505 	 * as it does not really have a real destination to
20506 	 * talk to.  This is also true for SCTP.
20507 	 */
20508 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20509 	    !connp->conn_fully_bound) {
20510 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20511 		if (ire == NULL)
20512 			goto noirefound;
20513 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20514 		    "ip_wput_end: q %p (%S)", q, "end");
20515 
20516 		/*
20517 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20518 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20519 		 */
20520 		if (ire->ire_flags & RTF_MULTIRT) {
20521 
20522 			/*
20523 			 * Force the TTL of multirouted packets if required.
20524 			 * The TTL of such packets is bounded by the
20525 			 * ip_multirt_ttl ndd variable.
20526 			 */
20527 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20528 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20529 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20530 				    "(was %d), dst 0x%08x\n",
20531 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20532 				    ntohl(ire->ire_addr)));
20533 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20534 			}
20535 			/*
20536 			 * We look at this point if there are pending
20537 			 * unresolved routes. ire_multirt_resolvable()
20538 			 * checks in O(n) that all IRE_OFFSUBNET ire
20539 			 * entries for the packet's destination and
20540 			 * flagged RTF_MULTIRT are currently resolved.
20541 			 * If some remain unresolved, we make a copy
20542 			 * of the current message. It will be used
20543 			 * to initiate additional route resolutions.
20544 			 */
20545 			multirt_need_resolve =
20546 			    ire_multirt_need_resolve(ire->ire_addr,
20547 			    MBLK_GETLABEL(first_mp), ipst);
20548 			ip2dbg(("ip_wput[TCP]: ire %p, "
20549 			    "multirt_need_resolve %d, first_mp %p\n",
20550 			    (void *)ire, multirt_need_resolve,
20551 			    (void *)first_mp));
20552 			if (multirt_need_resolve) {
20553 				copy_mp = copymsg(first_mp);
20554 				if (copy_mp != NULL) {
20555 					MULTIRT_DEBUG_TAG(copy_mp);
20556 				}
20557 			}
20558 		}
20559 
20560 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20561 
20562 		/*
20563 		 * Try to resolve another multiroute if
20564 		 * ire_multirt_need_resolve() deemed it necessary.
20565 		 */
20566 		if (copy_mp != NULL)
20567 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20568 		if (need_decref)
20569 			CONN_DEC_REF(connp);
20570 		return;
20571 	}
20572 
20573 	/*
20574 	 * Access to conn_ire_cache. (protected by conn_lock)
20575 	 *
20576 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20577 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20578 	 * send a packet or two with the IRE_CACHE that is going away.
20579 	 * Access to the ire requires an ire refhold on the ire prior to
20580 	 * its use since an interface unplumb thread may delete the cached
20581 	 * ire and release the refhold at any time.
20582 	 *
20583 	 * Caching an ire in the conn_ire_cache
20584 	 *
20585 	 * o Caching an ire pointer in the conn requires a strict check for
20586 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20587 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20588 	 * in the conn is done after making sure under the bucket lock that the
20589 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20590 	 * caching an ire after the unplumb thread has cleaned up the conn.
20591 	 * If the conn does not send a packet subsequently the unplumb thread
20592 	 * will be hanging waiting for the ire count to drop to zero.
20593 	 *
20594 	 * o We also need to atomically test for a null conn_ire_cache and
20595 	 * set the conn_ire_cache under the the protection of the conn_lock
20596 	 * to avoid races among concurrent threads trying to simultaneously
20597 	 * cache an ire in the conn_ire_cache.
20598 	 */
20599 	mutex_enter(&connp->conn_lock);
20600 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20601 
20602 	if (ire != NULL && ire->ire_addr == dst &&
20603 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20604 
20605 		IRE_REFHOLD(ire);
20606 		mutex_exit(&connp->conn_lock);
20607 
20608 	} else {
20609 		boolean_t cached = B_FALSE;
20610 		connp->conn_ire_cache = NULL;
20611 		mutex_exit(&connp->conn_lock);
20612 		/* Release the old ire */
20613 		if (ire != NULL && sctp_ire == NULL)
20614 			IRE_REFRELE_NOTR(ire);
20615 
20616 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20617 		if (ire == NULL)
20618 			goto noirefound;
20619 		IRE_REFHOLD_NOTR(ire);
20620 
20621 		mutex_enter(&connp->conn_lock);
20622 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20623 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20624 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20625 				if (connp->conn_ulp == IPPROTO_TCP)
20626 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20627 				connp->conn_ire_cache = ire;
20628 				cached = B_TRUE;
20629 			}
20630 			rw_exit(&ire->ire_bucket->irb_lock);
20631 		}
20632 		mutex_exit(&connp->conn_lock);
20633 
20634 		/*
20635 		 * We can continue to use the ire but since it was
20636 		 * not cached, we should drop the extra reference.
20637 		 */
20638 		if (!cached)
20639 			IRE_REFRELE_NOTR(ire);
20640 	}
20641 
20642 
20643 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20644 	    "ip_wput_end: q %p (%S)", q, "end");
20645 
20646 	/*
20647 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20648 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20649 	 */
20650 	if (ire->ire_flags & RTF_MULTIRT) {
20651 
20652 		/*
20653 		 * Force the TTL of multirouted packets if required.
20654 		 * The TTL of such packets is bounded by the
20655 		 * ip_multirt_ttl ndd variable.
20656 		 */
20657 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20658 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20659 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20660 			    "(was %d), dst 0x%08x\n",
20661 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20662 			    ntohl(ire->ire_addr)));
20663 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20664 		}
20665 
20666 		/*
20667 		 * At this point, we check to see if there are any pending
20668 		 * unresolved routes. ire_multirt_resolvable()
20669 		 * checks in O(n) that all IRE_OFFSUBNET ire
20670 		 * entries for the packet's destination and
20671 		 * flagged RTF_MULTIRT are currently resolved.
20672 		 * If some remain unresolved, we make a copy
20673 		 * of the current message. It will be used
20674 		 * to initiate additional route resolutions.
20675 		 */
20676 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20677 		    MBLK_GETLABEL(first_mp), ipst);
20678 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20679 		    "multirt_need_resolve %d, first_mp %p\n",
20680 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20681 		if (multirt_need_resolve) {
20682 			copy_mp = copymsg(first_mp);
20683 			if (copy_mp != NULL) {
20684 				MULTIRT_DEBUG_TAG(copy_mp);
20685 			}
20686 		}
20687 	}
20688 
20689 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20690 
20691 	/*
20692 	 * Try to resolve another multiroute if
20693 	 * ire_multirt_resolvable() deemed it necessary
20694 	 */
20695 	if (copy_mp != NULL)
20696 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20697 	if (need_decref)
20698 		CONN_DEC_REF(connp);
20699 	return;
20700 
20701 qnext:
20702 	/*
20703 	 * Upper Level Protocols pass down complete IP datagrams
20704 	 * as M_DATA messages.	Everything else is a sideshow.
20705 	 *
20706 	 * 1) We could be re-entering ip_wput because of ip_neworute
20707 	 *    in which case we could have a IPSEC_OUT message. We
20708 	 *    need to pass through ip_wput like other datagrams and
20709 	 *    hence cannot branch to ip_wput_nondata.
20710 	 *
20711 	 * 2) ARP, AH, ESP, and other clients who are on the module
20712 	 *    instance of IP stream, give us something to deal with.
20713 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20714 	 *
20715 	 * 3) ICMP replies also could come here.
20716 	 */
20717 	ipst = ILLQ_TO_IPST(q);
20718 
20719 	if (DB_TYPE(mp) != M_DATA) {
20720 notdata:
20721 		if (DB_TYPE(mp) == M_CTL) {
20722 			/*
20723 			 * M_CTL messages are used by ARP, AH and ESP to
20724 			 * communicate with IP. We deal with IPSEC_IN and
20725 			 * IPSEC_OUT here. ip_wput_nondata handles other
20726 			 * cases.
20727 			 */
20728 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20729 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20730 				first_mp = mp->b_cont;
20731 				first_mp->b_flag &= ~MSGHASREF;
20732 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20733 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20734 				CONN_DEC_REF(connp);
20735 				connp = NULL;
20736 			}
20737 			if (ii->ipsec_info_type == IPSEC_IN) {
20738 				/*
20739 				 * Either this message goes back to
20740 				 * IPsec for further processing or to
20741 				 * ULP after policy checks.
20742 				 */
20743 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20744 				return;
20745 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20746 				io = (ipsec_out_t *)ii;
20747 				if (io->ipsec_out_proc_begin) {
20748 					/*
20749 					 * IPsec processing has already started.
20750 					 * Complete it.
20751 					 * IPQoS notes: We don't care what is
20752 					 * in ipsec_out_ill_index since this
20753 					 * won't be processed for IPQoS policies
20754 					 * in ipsec_out_process.
20755 					 */
20756 					ipsec_out_process(q, mp, NULL,
20757 					    io->ipsec_out_ill_index);
20758 					return;
20759 				} else {
20760 					connp = (q->q_next != NULL) ?
20761 					    NULL : Q_TO_CONN(q);
20762 					first_mp = mp;
20763 					mp = mp->b_cont;
20764 					mctl_present = B_TRUE;
20765 				}
20766 				zoneid = io->ipsec_out_zoneid;
20767 				ASSERT(zoneid != ALL_ZONES);
20768 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20769 				/*
20770 				 * It's an IPsec control message requesting
20771 				 * an SADB update to be sent to the IPsec
20772 				 * hardware acceleration capable ills.
20773 				 */
20774 				ipsec_ctl_t *ipsec_ctl =
20775 				    (ipsec_ctl_t *)mp->b_rptr;
20776 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20777 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20778 				mblk_t *cmp = mp->b_cont;
20779 
20780 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20781 				ASSERT(cmp != NULL);
20782 
20783 				freeb(mp);
20784 				ill_ipsec_capab_send_all(satype, cmp, sa,
20785 				    ipst->ips_netstack);
20786 				return;
20787 			} else {
20788 				/*
20789 				 * This must be ARP or special TSOL signaling.
20790 				 */
20791 				ip_wput_nondata(NULL, q, mp, NULL);
20792 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20793 				    "ip_wput_end: q %p (%S)", q, "nondata");
20794 				return;
20795 			}
20796 		} else {
20797 			/*
20798 			 * This must be non-(ARP/AH/ESP) messages.
20799 			 */
20800 			ASSERT(!need_decref);
20801 			ip_wput_nondata(NULL, q, mp, NULL);
20802 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20803 			    "ip_wput_end: q %p (%S)", q, "nondata");
20804 			return;
20805 		}
20806 	} else {
20807 		first_mp = mp;
20808 		mctl_present = B_FALSE;
20809 	}
20810 
20811 	ASSERT(first_mp != NULL);
20812 
20813 	if (mctl_present) {
20814 		io = (ipsec_out_t *)first_mp->b_rptr;
20815 		if (io->ipsec_out_ip_nexthop) {
20816 			/*
20817 			 * We may have lost the conn context if we are
20818 			 * coming here from ip_newroute(). Copy the
20819 			 * nexthop information.
20820 			 */
20821 			ip_nexthop = B_TRUE;
20822 			nexthop_addr = io->ipsec_out_nexthop_addr;
20823 
20824 			ipha = (ipha_t *)mp->b_rptr;
20825 			dst = ipha->ipha_dst;
20826 			goto send_from_ill;
20827 		}
20828 	}
20829 
20830 	ASSERT(xmit_ill == NULL);
20831 
20832 	/* We have a complete IP datagram heading outbound. */
20833 	ipha = (ipha_t *)mp->b_rptr;
20834 
20835 #ifndef SPEED_BEFORE_SAFETY
20836 	/*
20837 	 * Make sure we have a full-word aligned message and that at least
20838 	 * a simple IP header is accessible in the first message.  If not,
20839 	 * try a pullup.  For labeled systems we need to always take this
20840 	 * path as M_CTLs are "notdata" but have trailing data to process.
20841 	 */
20842 	if (!OK_32PTR(rptr) ||
20843 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
20844 hdrtoosmall:
20845 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20846 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20847 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20848 			if (first_mp == NULL)
20849 				first_mp = mp;
20850 			goto discard_pkt;
20851 		}
20852 
20853 		/* This function assumes that mp points to an IPv4 packet. */
20854 		if (is_system_labeled() && q->q_next == NULL &&
20855 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20856 		    !connp->conn_ulp_labeled) {
20857 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20858 			    connp->conn_mac_exempt, ipst);
20859 			ipha = (ipha_t *)mp->b_rptr;
20860 			if (first_mp != NULL)
20861 				first_mp->b_cont = mp;
20862 			if (err != 0) {
20863 				if (first_mp == NULL)
20864 					first_mp = mp;
20865 				if (err == EINVAL)
20866 					goto icmp_parameter_problem;
20867 				ip2dbg(("ip_wput: label check failed (%d)\n",
20868 				    err));
20869 				goto discard_pkt;
20870 			}
20871 		}
20872 
20873 		ipha = (ipha_t *)mp->b_rptr;
20874 		if (first_mp == NULL) {
20875 			ASSERT(xmit_ill == NULL);
20876 			/*
20877 			 * If we got here because of "goto hdrtoosmall"
20878 			 * We need to attach a IPSEC_OUT.
20879 			 */
20880 			if (connp->conn_out_enforce_policy) {
20881 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20882 				    NULL, ipha->ipha_protocol,
20883 				    ipst->ips_netstack)) == NULL)) {
20884 					BUMP_MIB(&ipst->ips_ip_mib,
20885 					    ipIfStatsOutDiscards);
20886 					if (need_decref)
20887 						CONN_DEC_REF(connp);
20888 					return;
20889 				} else {
20890 					ASSERT(mp->b_datap->db_type == M_CTL);
20891 					first_mp = mp;
20892 					mp = mp->b_cont;
20893 					mctl_present = B_TRUE;
20894 				}
20895 			} else {
20896 				first_mp = mp;
20897 				mctl_present = B_FALSE;
20898 			}
20899 		}
20900 	}
20901 #endif
20902 
20903 	/* Most of the code below is written for speed, not readability */
20904 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20905 
20906 	/*
20907 	 * If ip_newroute() fails, we're going to need a full
20908 	 * header for the icmp wraparound.
20909 	 */
20910 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20911 		uint_t	v_hlen;
20912 version_hdrlen_check:
20913 		ASSERT(first_mp != NULL);
20914 		v_hlen = V_HLEN;
20915 		/*
20916 		 * siphon off IPv6 packets coming down from transport
20917 		 * layer modules here.
20918 		 * Note: high-order bit carries NUD reachability confirmation
20919 		 */
20920 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20921 			/*
20922 			 * FIXME: assume that callers of ip_output* call
20923 			 * the right version?
20924 			 */
20925 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20926 			ASSERT(xmit_ill == NULL);
20927 			if (need_decref)
20928 				mp->b_flag |= MSGHASREF;
20929 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20930 			return;
20931 		}
20932 
20933 		if ((v_hlen >> 4) != IP_VERSION) {
20934 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20935 			    "ip_wput_end: q %p (%S)", q, "badvers");
20936 			goto discard_pkt;
20937 		}
20938 		/*
20939 		 * Is the header length at least 20 bytes?
20940 		 *
20941 		 * Are there enough bytes accessible in the header?  If
20942 		 * not, try a pullup.
20943 		 */
20944 		v_hlen &= 0xF;
20945 		v_hlen <<= 2;
20946 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20947 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20948 			    "ip_wput_end: q %p (%S)", q, "badlen");
20949 			goto discard_pkt;
20950 		}
20951 		if (v_hlen > (mp->b_wptr - rptr)) {
20952 			if (!pullupmsg(mp, v_hlen)) {
20953 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20954 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20955 				goto discard_pkt;
20956 			}
20957 			ipha = (ipha_t *)mp->b_rptr;
20958 		}
20959 		/*
20960 		 * Move first entry from any source route into ipha_dst and
20961 		 * verify the options
20962 		 */
20963 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20964 		    zoneid, ipst)) {
20965 			ASSERT(xmit_ill == NULL);
20966 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20967 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20968 			    "ip_wput_end: q %p (%S)", q, "badopts");
20969 			if (need_decref)
20970 				CONN_DEC_REF(connp);
20971 			return;
20972 		}
20973 	}
20974 	dst = ipha->ipha_dst;
20975 
20976 	/*
20977 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20978 	 * we have to run the packet through ip_newroute which will take
20979 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20980 	 * a resolver, or assigning a default gateway, etc.
20981 	 */
20982 	if (CLASSD(dst)) {
20983 		ipif_t	*ipif;
20984 		uint32_t setsrc = 0;
20985 
20986 multicast:
20987 		ASSERT(first_mp != NULL);
20988 		ip2dbg(("ip_wput: CLASSD\n"));
20989 		if (connp == NULL) {
20990 			/*
20991 			 * Use the first good ipif on the ill.
20992 			 * XXX Should this ever happen? (Appears
20993 			 * to show up with just ppp and no ethernet due
20994 			 * to in.rdisc.)
20995 			 * However, ire_send should be able to
20996 			 * call ip_wput_ire directly.
20997 			 *
20998 			 * XXX Also, this can happen for ICMP and other packets
20999 			 * with multicast source addresses.  Perhaps we should
21000 			 * fix things so that we drop the packet in question,
21001 			 * but for now, just run with it.
21002 			 */
21003 			ill_t *ill = (ill_t *)q->q_ptr;
21004 
21005 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21006 			if (ipif == NULL) {
21007 				if (need_decref)
21008 					CONN_DEC_REF(connp);
21009 				freemsg(first_mp);
21010 				return;
21011 			}
21012 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21013 			    ntohl(dst), ill->ill_name));
21014 		} else {
21015 			/*
21016 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
21017 			 * and IP_MULTICAST_IF.  The block comment above this
21018 			 * function explains the locking mechanism used here.
21019 			 */
21020 			if (xmit_ill == NULL) {
21021 				xmit_ill = conn_get_held_ill(connp,
21022 				    &connp->conn_outgoing_ill, &err);
21023 				if (err == ILL_LOOKUP_FAILED) {
21024 					ip1dbg(("ip_wput: No ill for "
21025 					    "IP_BOUND_IF\n"));
21026 					BUMP_MIB(&ipst->ips_ip_mib,
21027 					    ipIfStatsOutNoRoutes);
21028 					goto drop_pkt;
21029 				}
21030 			}
21031 
21032 			if (xmit_ill == NULL) {
21033 				ipif = conn_get_held_ipif(connp,
21034 				    &connp->conn_multicast_ipif, &err);
21035 				if (err == IPIF_LOOKUP_FAILED) {
21036 					ip1dbg(("ip_wput: No ipif for "
21037 					    "multicast\n"));
21038 					BUMP_MIB(&ipst->ips_ip_mib,
21039 					    ipIfStatsOutNoRoutes);
21040 					goto drop_pkt;
21041 				}
21042 			}
21043 			if (xmit_ill != NULL) {
21044 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21045 				if (ipif == NULL) {
21046 					ip1dbg(("ip_wput: No ipif for "
21047 					    "xmit_ill\n"));
21048 					BUMP_MIB(&ipst->ips_ip_mib,
21049 					    ipIfStatsOutNoRoutes);
21050 					goto drop_pkt;
21051 				}
21052 			} else if (ipif == NULL || ipif->ipif_isv6) {
21053 				/*
21054 				 * We must do this ipif determination here
21055 				 * else we could pass through ip_newroute
21056 				 * and come back here without the conn context.
21057 				 *
21058 				 * Note: we do late binding i.e. we bind to
21059 				 * the interface when the first packet is sent.
21060 				 * For performance reasons we do not rebind on
21061 				 * each packet but keep the binding until the
21062 				 * next IP_MULTICAST_IF option.
21063 				 *
21064 				 * conn_multicast_{ipif,ill} are shared between
21065 				 * IPv4 and IPv6 and AF_INET6 sockets can
21066 				 * send both IPv4 and IPv6 packets. Hence
21067 				 * we have to check that "isv6" matches above.
21068 				 */
21069 				if (ipif != NULL)
21070 					ipif_refrele(ipif);
21071 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21072 				if (ipif == NULL) {
21073 					ip1dbg(("ip_wput: No ipif for "
21074 					    "multicast\n"));
21075 					BUMP_MIB(&ipst->ips_ip_mib,
21076 					    ipIfStatsOutNoRoutes);
21077 					goto drop_pkt;
21078 				}
21079 				err = conn_set_held_ipif(connp,
21080 				    &connp->conn_multicast_ipif, ipif);
21081 				if (err == IPIF_LOOKUP_FAILED) {
21082 					ipif_refrele(ipif);
21083 					ip1dbg(("ip_wput: No ipif for "
21084 					    "multicast\n"));
21085 					BUMP_MIB(&ipst->ips_ip_mib,
21086 					    ipIfStatsOutNoRoutes);
21087 					goto drop_pkt;
21088 				}
21089 			}
21090 		}
21091 		ASSERT(!ipif->ipif_isv6);
21092 		/*
21093 		 * As we may lose the conn by the time we reach ip_wput_ire,
21094 		 * we copy conn_multicast_loop and conn_dontroute on to an
21095 		 * ipsec_out. In case if this datagram goes out secure,
21096 		 * we need the ill_index also. Copy that also into the
21097 		 * ipsec_out.
21098 		 */
21099 		if (mctl_present) {
21100 			io = (ipsec_out_t *)first_mp->b_rptr;
21101 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21102 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21103 		} else {
21104 			ASSERT(mp == first_mp);
21105 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21106 			    BPRI_HI)) == NULL) {
21107 				ipif_refrele(ipif);
21108 				first_mp = mp;
21109 				goto discard_pkt;
21110 			}
21111 			first_mp->b_datap->db_type = M_CTL;
21112 			first_mp->b_wptr += sizeof (ipsec_info_t);
21113 			/* ipsec_out_secure is B_FALSE now */
21114 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21115 			io = (ipsec_out_t *)first_mp->b_rptr;
21116 			io->ipsec_out_type = IPSEC_OUT;
21117 			io->ipsec_out_len = sizeof (ipsec_out_t);
21118 			io->ipsec_out_use_global_policy = B_TRUE;
21119 			io->ipsec_out_ns = ipst->ips_netstack;
21120 			first_mp->b_cont = mp;
21121 			mctl_present = B_TRUE;
21122 		}
21123 
21124 		match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21125 		io->ipsec_out_ill_index =
21126 		    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21127 
21128 		if (connp != NULL) {
21129 			io->ipsec_out_multicast_loop =
21130 			    connp->conn_multicast_loop;
21131 			io->ipsec_out_dontroute = connp->conn_dontroute;
21132 			io->ipsec_out_zoneid = connp->conn_zoneid;
21133 		}
21134 		/*
21135 		 * If the application uses IP_MULTICAST_IF with
21136 		 * different logical addresses of the same ILL, we
21137 		 * need to make sure that the soruce address of
21138 		 * the packet matches the logical IP address used
21139 		 * in the option. We do it by initializing ipha_src
21140 		 * here. This should keep IPsec also happy as
21141 		 * when we return from IPsec processing, we don't
21142 		 * have to worry about getting the right address on
21143 		 * the packet. Thus it is sufficient to look for
21144 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21145 		 * MATCH_IRE_IPIF.
21146 		 *
21147 		 * NOTE : We need to do it for non-secure case also as
21148 		 * this might go out secure if there is a global policy
21149 		 * match in ip_wput_ire.
21150 		 *
21151 		 * As we do not have the ire yet, it is possible that
21152 		 * we set the source address here and then later discover
21153 		 * that the ire implies the source address to be assigned
21154 		 * through the RTF_SETSRC flag.
21155 		 * In that case, the setsrc variable will remind us
21156 		 * that overwritting the source address by the one
21157 		 * of the RTF_SETSRC-flagged ire is allowed.
21158 		 */
21159 		if (ipha->ipha_src == INADDR_ANY &&
21160 		    (connp == NULL || !connp->conn_unspec_src)) {
21161 			ipha->ipha_src = ipif->ipif_src_addr;
21162 			setsrc = RTF_SETSRC;
21163 		}
21164 		/*
21165 		 * Find an IRE which matches the destination and the outgoing
21166 		 * queue (i.e. the outgoing interface.)
21167 		 * For loopback use a unicast IP address for
21168 		 * the ire lookup.
21169 		 */
21170 		if (IS_LOOPBACK(ipif->ipif_ill))
21171 			dst = ipif->ipif_lcl_addr;
21172 
21173 		/*
21174 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21175 		 * We don't need to lookup ire in ctable as the packet
21176 		 * needs to be sent to the destination through the specified
21177 		 * ill irrespective of ires in the cache table.
21178 		 */
21179 		ire = NULL;
21180 		if (xmit_ill == NULL) {
21181 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21182 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21183 		}
21184 
21185 		if (ire == NULL) {
21186 			/*
21187 			 * Multicast loopback and multicast forwarding is
21188 			 * done in ip_wput_ire.
21189 			 *
21190 			 * Mark this packet to make it be delivered to
21191 			 * ip_wput_ire after the new ire has been
21192 			 * created.
21193 			 *
21194 			 * The call to ip_newroute_ipif takes into account
21195 			 * the setsrc reminder. In any case, we take care
21196 			 * of the RTF_MULTIRT flag.
21197 			 */
21198 			mp->b_prev = mp->b_next = NULL;
21199 			if (xmit_ill == NULL ||
21200 			    xmit_ill->ill_ipif_up_count > 0) {
21201 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21202 				    setsrc | RTF_MULTIRT, zoneid, infop);
21203 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21204 				    "ip_wput_end: q %p (%S)", q, "noire");
21205 			} else {
21206 				freemsg(first_mp);
21207 			}
21208 			ipif_refrele(ipif);
21209 			if (xmit_ill != NULL)
21210 				ill_refrele(xmit_ill);
21211 			if (need_decref)
21212 				CONN_DEC_REF(connp);
21213 			return;
21214 		}
21215 
21216 		ipif_refrele(ipif);
21217 		ipif = NULL;
21218 		ASSERT(xmit_ill == NULL);
21219 
21220 		/*
21221 		 * Honor the RTF_SETSRC flag for multicast packets,
21222 		 * if allowed by the setsrc reminder.
21223 		 */
21224 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21225 			ipha->ipha_src = ire->ire_src_addr;
21226 		}
21227 
21228 		/*
21229 		 * Unconditionally force the TTL to 1 for
21230 		 * multirouted multicast packets:
21231 		 * multirouted multicast should not cross
21232 		 * multicast routers.
21233 		 */
21234 		if (ire->ire_flags & RTF_MULTIRT) {
21235 			if (ipha->ipha_ttl > 1) {
21236 				ip2dbg(("ip_wput: forcing multicast "
21237 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21238 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21239 				ipha->ipha_ttl = 1;
21240 			}
21241 		}
21242 	} else {
21243 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21244 		if ((ire != NULL) && (ire->ire_type &
21245 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21246 			ignore_dontroute = B_TRUE;
21247 			ignore_nexthop = B_TRUE;
21248 		}
21249 		if (ire != NULL) {
21250 			ire_refrele(ire);
21251 			ire = NULL;
21252 		}
21253 		/*
21254 		 * Guard against coming in from arp in which case conn is NULL.
21255 		 * Also guard against non M_DATA with dontroute set but
21256 		 * destined to local, loopback or broadcast addresses.
21257 		 */
21258 		if (connp != NULL && connp->conn_dontroute &&
21259 		    !ignore_dontroute) {
21260 dontroute:
21261 			/*
21262 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21263 			 * routing protocols from seeing false direct
21264 			 * connectivity.
21265 			 */
21266 			ipha->ipha_ttl = 1;
21267 			/* If suitable ipif not found, drop packet */
21268 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21269 			if (dst_ipif == NULL) {
21270 noroute:
21271 				ip1dbg(("ip_wput: no route for dst using"
21272 				    " SO_DONTROUTE\n"));
21273 				BUMP_MIB(&ipst->ips_ip_mib,
21274 				    ipIfStatsOutNoRoutes);
21275 				mp->b_prev = mp->b_next = NULL;
21276 				if (first_mp == NULL)
21277 					first_mp = mp;
21278 				goto drop_pkt;
21279 			} else {
21280 				/*
21281 				 * If suitable ipif has been found, set
21282 				 * xmit_ill to the corresponding
21283 				 * ipif_ill because we'll be using the
21284 				 * send_from_ill logic below.
21285 				 */
21286 				ASSERT(xmit_ill == NULL);
21287 				xmit_ill = dst_ipif->ipif_ill;
21288 				mutex_enter(&xmit_ill->ill_lock);
21289 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21290 					mutex_exit(&xmit_ill->ill_lock);
21291 					xmit_ill = NULL;
21292 					ipif_refrele(dst_ipif);
21293 					goto noroute;
21294 				}
21295 				ill_refhold_locked(xmit_ill);
21296 				mutex_exit(&xmit_ill->ill_lock);
21297 				ipif_refrele(dst_ipif);
21298 			}
21299 		}
21300 
21301 send_from_ill:
21302 		if (xmit_ill != NULL) {
21303 			ipif_t *ipif;
21304 
21305 			/*
21306 			 * Mark this packet as originated locally
21307 			 */
21308 			mp->b_prev = mp->b_next = NULL;
21309 
21310 			/*
21311 			 * Could be SO_DONTROUTE case also.
21312 			 * Verify that at least one ipif is up on the ill.
21313 			 */
21314 			if (xmit_ill->ill_ipif_up_count == 0) {
21315 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21316 				    xmit_ill->ill_name));
21317 				goto drop_pkt;
21318 			}
21319 
21320 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21321 			if (ipif == NULL) {
21322 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21323 				    xmit_ill->ill_name));
21324 				goto drop_pkt;
21325 			}
21326 
21327 			match_flags = 0;
21328 			if (IS_UNDER_IPMP(xmit_ill))
21329 				match_flags |= MATCH_IRE_MARK_TESTHIDDEN;
21330 
21331 			/*
21332 			 * Look for a ire that is part of the group,
21333 			 * if found use it else call ip_newroute_ipif.
21334 			 * IPCL_ZONEID is not used for matching because
21335 			 * IP_ALLZONES option is valid only when the
21336 			 * ill is accessible from all zones i.e has a
21337 			 * valid ipif in all zones.
21338 			 */
21339 			match_flags |= MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21340 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21341 			    MBLK_GETLABEL(mp), match_flags, ipst);
21342 			/*
21343 			 * If an ire exists use it or else create
21344 			 * an ire but don't add it to the cache.
21345 			 * Adding an ire may cause issues with
21346 			 * asymmetric routing.
21347 			 * In case of multiroute always act as if
21348 			 * ire does not exist.
21349 			 */
21350 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21351 				if (ire != NULL)
21352 					ire_refrele(ire);
21353 				ip_newroute_ipif(q, first_mp, ipif,
21354 				    dst, connp, 0, zoneid, infop);
21355 				ipif_refrele(ipif);
21356 				ip1dbg(("ip_output: xmit_ill via %s\n",
21357 				    xmit_ill->ill_name));
21358 				ill_refrele(xmit_ill);
21359 				if (need_decref)
21360 					CONN_DEC_REF(connp);
21361 				return;
21362 			}
21363 			ipif_refrele(ipif);
21364 		} else if (ip_nexthop || (connp != NULL &&
21365 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21366 			if (!ip_nexthop) {
21367 				ip_nexthop = B_TRUE;
21368 				nexthop_addr = connp->conn_nexthop_v4;
21369 			}
21370 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21371 			    MATCH_IRE_GW;
21372 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21373 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21374 		} else {
21375 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21376 			    ipst);
21377 		}
21378 		if (!ire) {
21379 			if (ip_nexthop && !ignore_nexthop) {
21380 				if (mctl_present) {
21381 					io = (ipsec_out_t *)first_mp->b_rptr;
21382 					ASSERT(first_mp->b_datap->db_type ==
21383 					    M_CTL);
21384 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21385 				} else {
21386 					ASSERT(mp == first_mp);
21387 					first_mp = allocb(
21388 					    sizeof (ipsec_info_t), BPRI_HI);
21389 					if (first_mp == NULL) {
21390 						first_mp = mp;
21391 						goto discard_pkt;
21392 					}
21393 					first_mp->b_datap->db_type = M_CTL;
21394 					first_mp->b_wptr +=
21395 					    sizeof (ipsec_info_t);
21396 					/* ipsec_out_secure is B_FALSE now */
21397 					bzero(first_mp->b_rptr,
21398 					    sizeof (ipsec_info_t));
21399 					io = (ipsec_out_t *)first_mp->b_rptr;
21400 					io->ipsec_out_type = IPSEC_OUT;
21401 					io->ipsec_out_len =
21402 					    sizeof (ipsec_out_t);
21403 					io->ipsec_out_use_global_policy =
21404 					    B_TRUE;
21405 					io->ipsec_out_ns = ipst->ips_netstack;
21406 					first_mp->b_cont = mp;
21407 					mctl_present = B_TRUE;
21408 				}
21409 				io->ipsec_out_ip_nexthop = ip_nexthop;
21410 				io->ipsec_out_nexthop_addr = nexthop_addr;
21411 			}
21412 noirefound:
21413 			/*
21414 			 * Mark this packet as having originated on
21415 			 * this machine.  This will be noted in
21416 			 * ire_add_then_send, which needs to know
21417 			 * whether to run it back through ip_wput or
21418 			 * ip_rput following successful resolution.
21419 			 */
21420 			mp->b_prev = NULL;
21421 			mp->b_next = NULL;
21422 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21423 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21424 			    "ip_wput_end: q %p (%S)", q, "newroute");
21425 			if (xmit_ill != NULL)
21426 				ill_refrele(xmit_ill);
21427 			if (need_decref)
21428 				CONN_DEC_REF(connp);
21429 			return;
21430 		}
21431 	}
21432 
21433 	/* We now know where we are going with it. */
21434 
21435 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21436 	    "ip_wput_end: q %p (%S)", q, "end");
21437 
21438 	/*
21439 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21440 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21441 	 */
21442 	if (ire->ire_flags & RTF_MULTIRT) {
21443 		/*
21444 		 * Force the TTL of multirouted packets if required.
21445 		 * The TTL of such packets is bounded by the
21446 		 * ip_multirt_ttl ndd variable.
21447 		 */
21448 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21449 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21450 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21451 			    "(was %d), dst 0x%08x\n",
21452 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21453 			    ntohl(ire->ire_addr)));
21454 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21455 		}
21456 		/*
21457 		 * At this point, we check to see if there are any pending
21458 		 * unresolved routes. ire_multirt_resolvable()
21459 		 * checks in O(n) that all IRE_OFFSUBNET ire
21460 		 * entries for the packet's destination and
21461 		 * flagged RTF_MULTIRT are currently resolved.
21462 		 * If some remain unresolved, we make a copy
21463 		 * of the current message. It will be used
21464 		 * to initiate additional route resolutions.
21465 		 */
21466 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21467 		    MBLK_GETLABEL(first_mp), ipst);
21468 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21469 		    "multirt_need_resolve %d, first_mp %p\n",
21470 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21471 		if (multirt_need_resolve) {
21472 			copy_mp = copymsg(first_mp);
21473 			if (copy_mp != NULL) {
21474 				MULTIRT_DEBUG_TAG(copy_mp);
21475 			}
21476 		}
21477 	}
21478 
21479 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21480 	/*
21481 	 * Try to resolve another multiroute if
21482 	 * ire_multirt_resolvable() deemed it necessary.
21483 	 * At this point, we need to distinguish
21484 	 * multicasts from other packets. For multicasts,
21485 	 * we call ip_newroute_ipif() and request that both
21486 	 * multirouting and setsrc flags are checked.
21487 	 */
21488 	if (copy_mp != NULL) {
21489 		if (CLASSD(dst)) {
21490 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21491 			if (ipif) {
21492 				ASSERT(infop->ip_opt_ill_index == 0);
21493 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21494 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21495 				ipif_refrele(ipif);
21496 			} else {
21497 				MULTIRT_DEBUG_UNTAG(copy_mp);
21498 				freemsg(copy_mp);
21499 				copy_mp = NULL;
21500 			}
21501 		} else {
21502 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21503 		}
21504 	}
21505 	if (xmit_ill != NULL)
21506 		ill_refrele(xmit_ill);
21507 	if (need_decref)
21508 		CONN_DEC_REF(connp);
21509 	return;
21510 
21511 icmp_parameter_problem:
21512 	/* could not have originated externally */
21513 	ASSERT(mp->b_prev == NULL);
21514 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21515 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21516 		/* it's the IP header length that's in trouble */
21517 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21518 		first_mp = NULL;
21519 	}
21520 
21521 discard_pkt:
21522 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21523 drop_pkt:
21524 	ip1dbg(("ip_wput: dropped packet\n"));
21525 	if (ire != NULL)
21526 		ire_refrele(ire);
21527 	if (need_decref)
21528 		CONN_DEC_REF(connp);
21529 	freemsg(first_mp);
21530 	if (xmit_ill != NULL)
21531 		ill_refrele(xmit_ill);
21532 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21533 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21534 }
21535 
21536 /*
21537  * If this is a conn_t queue, then we pass in the conn. This includes the
21538  * zoneid.
21539  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21540  * in which case we use the global zoneid since those are all part of
21541  * the global zone.
21542  */
21543 void
21544 ip_wput(queue_t *q, mblk_t *mp)
21545 {
21546 	if (CONN_Q(q))
21547 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21548 	else
21549 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21550 }
21551 
21552 /*
21553  *
21554  * The following rules must be observed when accessing any ipif or ill
21555  * that has been cached in the conn. Typically conn_outgoing_ill,
21556  * conn_multicast_ipif and conn_multicast_ill.
21557  *
21558  * Access: The ipif or ill pointed to from the conn can be accessed under
21559  * the protection of the conn_lock or after it has been refheld under the
21560  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21561  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21562  * The reason for this is that a concurrent unplumb could actually be
21563  * cleaning up these cached pointers by walking the conns and might have
21564  * finished cleaning up the conn in question. The macros check that an
21565  * unplumb has not yet started on the ipif or ill.
21566  *
21567  * Caching: An ipif or ill pointer may be cached in the conn only after
21568  * making sure that an unplumb has not started. So the caching is done
21569  * while holding both the conn_lock and the ill_lock and after using the
21570  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21571  * flag before starting the cleanup of conns.
21572  *
21573  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21574  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21575  * or a reference to the ipif or a reference to an ire that references the
21576  * ipif. An ipif only changes its ill when migrating from an underlying ill
21577  * to an IPMP ill in ipif_up().
21578  */
21579 ipif_t *
21580 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21581 {
21582 	ipif_t	*ipif;
21583 	ill_t	*ill;
21584 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21585 
21586 	*err = 0;
21587 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21588 	mutex_enter(&connp->conn_lock);
21589 	ipif = *ipifp;
21590 	if (ipif != NULL) {
21591 		ill = ipif->ipif_ill;
21592 		mutex_enter(&ill->ill_lock);
21593 		if (IPIF_CAN_LOOKUP(ipif)) {
21594 			ipif_refhold_locked(ipif);
21595 			mutex_exit(&ill->ill_lock);
21596 			mutex_exit(&connp->conn_lock);
21597 			rw_exit(&ipst->ips_ill_g_lock);
21598 			return (ipif);
21599 		} else {
21600 			*err = IPIF_LOOKUP_FAILED;
21601 		}
21602 		mutex_exit(&ill->ill_lock);
21603 	}
21604 	mutex_exit(&connp->conn_lock);
21605 	rw_exit(&ipst->ips_ill_g_lock);
21606 	return (NULL);
21607 }
21608 
21609 ill_t *
21610 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21611 {
21612 	ill_t	*ill;
21613 
21614 	*err = 0;
21615 	mutex_enter(&connp->conn_lock);
21616 	ill = *illp;
21617 	if (ill != NULL) {
21618 		mutex_enter(&ill->ill_lock);
21619 		if (ILL_CAN_LOOKUP(ill)) {
21620 			ill_refhold_locked(ill);
21621 			mutex_exit(&ill->ill_lock);
21622 			mutex_exit(&connp->conn_lock);
21623 			return (ill);
21624 		} else {
21625 			*err = ILL_LOOKUP_FAILED;
21626 		}
21627 		mutex_exit(&ill->ill_lock);
21628 	}
21629 	mutex_exit(&connp->conn_lock);
21630 	return (NULL);
21631 }
21632 
21633 static int
21634 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21635 {
21636 	ill_t	*ill;
21637 
21638 	ill = ipif->ipif_ill;
21639 	mutex_enter(&connp->conn_lock);
21640 	mutex_enter(&ill->ill_lock);
21641 	if (IPIF_CAN_LOOKUP(ipif)) {
21642 		*ipifp = ipif;
21643 		mutex_exit(&ill->ill_lock);
21644 		mutex_exit(&connp->conn_lock);
21645 		return (0);
21646 	}
21647 	mutex_exit(&ill->ill_lock);
21648 	mutex_exit(&connp->conn_lock);
21649 	return (IPIF_LOOKUP_FAILED);
21650 }
21651 
21652 /*
21653  * This is called if the outbound datagram needs fragmentation.
21654  *
21655  * NOTE : This function does not ire_refrele the ire argument passed in.
21656  */
21657 static void
21658 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21659     ip_stack_t *ipst, conn_t *connp)
21660 {
21661 	ipha_t		*ipha;
21662 	mblk_t		*mp;
21663 	uint32_t	v_hlen_tos_len;
21664 	uint32_t	max_frag;
21665 	uint32_t	frag_flag;
21666 	boolean_t	dont_use;
21667 
21668 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21669 		mp = ipsec_mp->b_cont;
21670 	} else {
21671 		mp = ipsec_mp;
21672 	}
21673 
21674 	ipha = (ipha_t *)mp->b_rptr;
21675 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21676 
21677 #ifdef	_BIG_ENDIAN
21678 #define	V_HLEN	(v_hlen_tos_len >> 24)
21679 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21680 #else
21681 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21682 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21683 #endif
21684 
21685 #ifndef SPEED_BEFORE_SAFETY
21686 	/*
21687 	 * Check that ipha_length is consistent with
21688 	 * the mblk length
21689 	 */
21690 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21691 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21692 		    LENGTH, msgdsize(mp)));
21693 		freemsg(ipsec_mp);
21694 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21695 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21696 		    "packet length mismatch");
21697 		return;
21698 	}
21699 #endif
21700 	/*
21701 	 * Don't use frag_flag if pre-built packet or source
21702 	 * routed or if multicast (since multicast packets do not solicit
21703 	 * ICMP "packet too big" messages). Get the values of
21704 	 * max_frag and frag_flag atomically by acquiring the
21705 	 * ire_lock.
21706 	 */
21707 	mutex_enter(&ire->ire_lock);
21708 	max_frag = ire->ire_max_frag;
21709 	frag_flag = ire->ire_frag_flag;
21710 	mutex_exit(&ire->ire_lock);
21711 
21712 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21713 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21714 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21715 
21716 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21717 	    (dont_use ? 0 : frag_flag), zoneid, ipst, connp);
21718 }
21719 
21720 /*
21721  * Used for deciding the MSS size for the upper layer. Thus
21722  * we need to check the outbound policy values in the conn.
21723  */
21724 int
21725 conn_ipsec_length(conn_t *connp)
21726 {
21727 	ipsec_latch_t *ipl;
21728 
21729 	ipl = connp->conn_latch;
21730 	if (ipl == NULL)
21731 		return (0);
21732 
21733 	if (ipl->ipl_out_policy == NULL)
21734 		return (0);
21735 
21736 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21737 }
21738 
21739 /*
21740  * Returns an estimate of the IPsec headers size. This is used if
21741  * we don't want to call into IPsec to get the exact size.
21742  */
21743 int
21744 ipsec_out_extra_length(mblk_t *ipsec_mp)
21745 {
21746 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21747 	ipsec_action_t *a;
21748 
21749 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21750 	if (!io->ipsec_out_secure)
21751 		return (0);
21752 
21753 	a = io->ipsec_out_act;
21754 
21755 	if (a == NULL) {
21756 		ASSERT(io->ipsec_out_policy != NULL);
21757 		a = io->ipsec_out_policy->ipsp_act;
21758 	}
21759 	ASSERT(a != NULL);
21760 
21761 	return (a->ipa_ovhd);
21762 }
21763 
21764 /*
21765  * Returns an estimate of the IPsec headers size. This is used if
21766  * we don't want to call into IPsec to get the exact size.
21767  */
21768 int
21769 ipsec_in_extra_length(mblk_t *ipsec_mp)
21770 {
21771 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21772 	ipsec_action_t *a;
21773 
21774 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21775 
21776 	a = ii->ipsec_in_action;
21777 	return (a == NULL ? 0 : a->ipa_ovhd);
21778 }
21779 
21780 /*
21781  * If there are any source route options, return the true final
21782  * destination. Otherwise, return the destination.
21783  */
21784 ipaddr_t
21785 ip_get_dst(ipha_t *ipha)
21786 {
21787 	ipoptp_t	opts;
21788 	uchar_t		*opt;
21789 	uint8_t		optval;
21790 	uint8_t		optlen;
21791 	ipaddr_t	dst;
21792 	uint32_t off;
21793 
21794 	dst = ipha->ipha_dst;
21795 
21796 	if (IS_SIMPLE_IPH(ipha))
21797 		return (dst);
21798 
21799 	for (optval = ipoptp_first(&opts, ipha);
21800 	    optval != IPOPT_EOL;
21801 	    optval = ipoptp_next(&opts)) {
21802 		opt = opts.ipoptp_cur;
21803 		optlen = opts.ipoptp_len;
21804 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21805 		switch (optval) {
21806 		case IPOPT_SSRR:
21807 		case IPOPT_LSRR:
21808 			off = opt[IPOPT_OFFSET];
21809 			/*
21810 			 * If one of the conditions is true, it means
21811 			 * end of options and dst already has the right
21812 			 * value.
21813 			 */
21814 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21815 				off = optlen - IP_ADDR_LEN;
21816 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21817 			}
21818 			return (dst);
21819 		default:
21820 			break;
21821 		}
21822 	}
21823 
21824 	return (dst);
21825 }
21826 
21827 mblk_t *
21828 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21829     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21830 {
21831 	ipsec_out_t	*io;
21832 	mblk_t		*first_mp;
21833 	boolean_t policy_present;
21834 	ip_stack_t	*ipst;
21835 	ipsec_stack_t	*ipss;
21836 
21837 	ASSERT(ire != NULL);
21838 	ipst = ire->ire_ipst;
21839 	ipss = ipst->ips_netstack->netstack_ipsec;
21840 
21841 	first_mp = mp;
21842 	if (mp->b_datap->db_type == M_CTL) {
21843 		io = (ipsec_out_t *)first_mp->b_rptr;
21844 		/*
21845 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21846 		 *
21847 		 * 1) There is per-socket policy (including cached global
21848 		 *    policy) or a policy on the IP-in-IP tunnel.
21849 		 * 2) There is no per-socket policy, but it is
21850 		 *    a multicast packet that needs to go out
21851 		 *    on a specific interface. This is the case
21852 		 *    where (ip_wput and ip_wput_multicast) attaches
21853 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21854 		 *
21855 		 * In case (2) we check with global policy to
21856 		 * see if there is a match and set the ill_index
21857 		 * appropriately so that we can lookup the ire
21858 		 * properly in ip_wput_ipsec_out.
21859 		 */
21860 
21861 		/*
21862 		 * ipsec_out_use_global_policy is set to B_FALSE
21863 		 * in ipsec_in_to_out(). Refer to that function for
21864 		 * details.
21865 		 */
21866 		if ((io->ipsec_out_latch == NULL) &&
21867 		    (io->ipsec_out_use_global_policy)) {
21868 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21869 			    ire, connp, unspec_src, zoneid));
21870 		}
21871 		if (!io->ipsec_out_secure) {
21872 			/*
21873 			 * If this is not a secure packet, drop
21874 			 * the IPSEC_OUT mp and treat it as a clear
21875 			 * packet. This happens when we are sending
21876 			 * a ICMP reply back to a clear packet. See
21877 			 * ipsec_in_to_out() for details.
21878 			 */
21879 			mp = first_mp->b_cont;
21880 			freeb(first_mp);
21881 		}
21882 		return (mp);
21883 	}
21884 	/*
21885 	 * See whether we need to attach a global policy here. We
21886 	 * don't depend on the conn (as it could be null) for deciding
21887 	 * what policy this datagram should go through because it
21888 	 * should have happened in ip_wput if there was some
21889 	 * policy. This normally happens for connections which are not
21890 	 * fully bound preventing us from caching policies in
21891 	 * ip_bind. Packets coming from the TCP listener/global queue
21892 	 * - which are non-hard_bound - could also be affected by
21893 	 * applying policy here.
21894 	 *
21895 	 * If this packet is coming from tcp global queue or listener,
21896 	 * we will be applying policy here.  This may not be *right*
21897 	 * if these packets are coming from the detached connection as
21898 	 * it could have gone in clear before. This happens only if a
21899 	 * TCP connection started when there is no policy and somebody
21900 	 * added policy before it became detached. Thus packets of the
21901 	 * detached connection could go out secure and the other end
21902 	 * would drop it because it will be expecting in clear. The
21903 	 * converse is not true i.e if somebody starts a TCP
21904 	 * connection and deletes the policy, all the packets will
21905 	 * still go out with the policy that existed before deleting
21906 	 * because ip_unbind sends up policy information which is used
21907 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21908 	 * TCP to attach a dummy IPSEC_OUT and set
21909 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21910 	 * affect performance for normal cases, we are not doing it.
21911 	 * Thus, set policy before starting any TCP connections.
21912 	 *
21913 	 * NOTE - We might apply policy even for a hard bound connection
21914 	 * - for which we cached policy in ip_bind - if somebody added
21915 	 * global policy after we inherited the policy in ip_bind.
21916 	 * This means that the packets that were going out in clear
21917 	 * previously would start going secure and hence get dropped
21918 	 * on the other side. To fix this, TCP attaches a dummy
21919 	 * ipsec_out and make sure that we don't apply global policy.
21920 	 */
21921 	if (ipha != NULL)
21922 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21923 	else
21924 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21925 	if (!policy_present)
21926 		return (mp);
21927 
21928 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21929 	    zoneid));
21930 }
21931 
21932 /*
21933  * This function does the ire_refrele of the ire passed in as the
21934  * argument. As this function looks up more ires i.e broadcast ires,
21935  * it needs to REFRELE them. Currently, for simplicity we don't
21936  * differentiate the one passed in and looked up here. We always
21937  * REFRELE.
21938  * IPQoS Notes:
21939  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21940  * IPsec packets are done in ipsec_out_process.
21941  */
21942 void
21943 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21944     zoneid_t zoneid)
21945 {
21946 	ipha_t		*ipha;
21947 #define	rptr	((uchar_t *)ipha)
21948 	queue_t		*stq;
21949 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21950 	uint32_t	v_hlen_tos_len;
21951 	uint32_t	ttl_protocol;
21952 	ipaddr_t	src;
21953 	ipaddr_t	dst;
21954 	uint32_t	cksum;
21955 	ipaddr_t	orig_src;
21956 	ire_t		*ire1;
21957 	mblk_t		*next_mp;
21958 	uint_t		hlen;
21959 	uint16_t	*up;
21960 	uint32_t	max_frag = ire->ire_max_frag;
21961 	ill_t		*ill = ire_to_ill(ire);
21962 	int		clusterwide;
21963 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21964 	int		ipsec_len;
21965 	mblk_t		*first_mp;
21966 	ipsec_out_t	*io;
21967 	boolean_t	conn_dontroute;		/* conn value for multicast */
21968 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21969 	boolean_t	multicast_forward;	/* Should we forward ? */
21970 	boolean_t	unspec_src;
21971 	ill_t		*conn_outgoing_ill = NULL;
21972 	ill_t		*ire_ill;
21973 	ill_t		*ire1_ill;
21974 	ill_t		*out_ill;
21975 	uint32_t 	ill_index = 0;
21976 	boolean_t	multirt_send = B_FALSE;
21977 	int		err;
21978 	ipxmit_state_t	pktxmit_state;
21979 	ip_stack_t	*ipst = ire->ire_ipst;
21980 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
21981 
21982 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
21983 	    "ip_wput_ire_start: q %p", q);
21984 
21985 	multicast_forward = B_FALSE;
21986 	unspec_src = (connp != NULL && connp->conn_unspec_src);
21987 
21988 	if (ire->ire_flags & RTF_MULTIRT) {
21989 		/*
21990 		 * Multirouting case. The bucket where ire is stored
21991 		 * probably holds other RTF_MULTIRT flagged ire
21992 		 * to the destination. In this call to ip_wput_ire,
21993 		 * we attempt to send the packet through all
21994 		 * those ires. Thus, we first ensure that ire is the
21995 		 * first RTF_MULTIRT ire in the bucket,
21996 		 * before walking the ire list.
21997 		 */
21998 		ire_t *first_ire;
21999 		irb_t *irb = ire->ire_bucket;
22000 		ASSERT(irb != NULL);
22001 
22002 		/* Make sure we do not omit any multiroute ire. */
22003 		IRB_REFHOLD(irb);
22004 		for (first_ire = irb->irb_ire;
22005 		    first_ire != NULL;
22006 		    first_ire = first_ire->ire_next) {
22007 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22008 			    (first_ire->ire_addr == ire->ire_addr) &&
22009 			    !(first_ire->ire_marks &
22010 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
22011 				break;
22012 		}
22013 
22014 		if ((first_ire != NULL) && (first_ire != ire)) {
22015 			IRE_REFHOLD(first_ire);
22016 			ire_refrele(ire);
22017 			ire = first_ire;
22018 			ill = ire_to_ill(ire);
22019 		}
22020 		IRB_REFRELE(irb);
22021 	}
22022 
22023 	/*
22024 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22025 	 * for performance we don't grab the mutexs in the fastpath
22026 	 */
22027 	if (ire->ire_type == IRE_BROADCAST && connp != NULL &&
22028 	    connp->conn_outgoing_ill != NULL) {
22029 		conn_outgoing_ill = conn_get_held_ill(connp,
22030 		    &connp->conn_outgoing_ill, &err);
22031 		if (err == ILL_LOOKUP_FAILED) {
22032 			ire_refrele(ire);
22033 			freemsg(mp);
22034 			return;
22035 		}
22036 	}
22037 
22038 	if (mp->b_datap->db_type != M_CTL) {
22039 		ipha = (ipha_t *)mp->b_rptr;
22040 	} else {
22041 		io = (ipsec_out_t *)mp->b_rptr;
22042 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22043 		ASSERT(zoneid == io->ipsec_out_zoneid);
22044 		ASSERT(zoneid != ALL_ZONES);
22045 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22046 		dst = ipha->ipha_dst;
22047 		/*
22048 		 * For the multicast case, ipsec_out carries conn_dontroute and
22049 		 * conn_multicast_loop as conn may not be available here. We
22050 		 * need this for multicast loopback and forwarding which is done
22051 		 * later in the code.
22052 		 */
22053 		if (CLASSD(dst)) {
22054 			conn_dontroute = io->ipsec_out_dontroute;
22055 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22056 			/*
22057 			 * If conn_dontroute is not set or conn_multicast_loop
22058 			 * is set, we need to do forwarding/loopback. For
22059 			 * datagrams from ip_wput_multicast, conn_dontroute is
22060 			 * set to B_TRUE and conn_multicast_loop is set to
22061 			 * B_FALSE so that we neither do forwarding nor
22062 			 * loopback.
22063 			 */
22064 			if (!conn_dontroute || conn_multicast_loop)
22065 				multicast_forward = B_TRUE;
22066 		}
22067 	}
22068 
22069 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22070 	    ire->ire_zoneid != ALL_ZONES) {
22071 		/*
22072 		 * When a zone sends a packet to another zone, we try to deliver
22073 		 * the packet under the same conditions as if the destination
22074 		 * was a real node on the network. To do so, we look for a
22075 		 * matching route in the forwarding table.
22076 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22077 		 * ip_newroute() does.
22078 		 * Note that IRE_LOCAL are special, since they are used
22079 		 * when the zoneid doesn't match in some cases. This means that
22080 		 * we need to handle ipha_src differently since ire_src_addr
22081 		 * belongs to the receiving zone instead of the sending zone.
22082 		 * When ip_restrict_interzone_loopback is set, then
22083 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22084 		 * for loopback between zones when the logical "Ethernet" would
22085 		 * have looped them back.
22086 		 */
22087 		ire_t *src_ire;
22088 
22089 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22090 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22091 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22092 		if (src_ire != NULL &&
22093 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22094 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22095 		    ire_local_same_lan(ire, src_ire))) {
22096 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22097 				ipha->ipha_src = src_ire->ire_src_addr;
22098 			ire_refrele(src_ire);
22099 		} else {
22100 			ire_refrele(ire);
22101 			if (conn_outgoing_ill != NULL)
22102 				ill_refrele(conn_outgoing_ill);
22103 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22104 			if (src_ire != NULL) {
22105 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22106 					ire_refrele(src_ire);
22107 					freemsg(mp);
22108 					return;
22109 				}
22110 				ire_refrele(src_ire);
22111 			}
22112 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22113 				/* Failed */
22114 				freemsg(mp);
22115 				return;
22116 			}
22117 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22118 			    ipst);
22119 			return;
22120 		}
22121 	}
22122 
22123 	if (mp->b_datap->db_type == M_CTL ||
22124 	    ipss->ipsec_outbound_v4_policy_present) {
22125 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22126 		    unspec_src, zoneid);
22127 		if (mp == NULL) {
22128 			ire_refrele(ire);
22129 			if (conn_outgoing_ill != NULL)
22130 				ill_refrele(conn_outgoing_ill);
22131 			return;
22132 		}
22133 		/*
22134 		 * Trusted Extensions supports all-zones interfaces, so
22135 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22136 		 * the global zone.
22137 		 */
22138 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22139 			io = (ipsec_out_t *)mp->b_rptr;
22140 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22141 			zoneid = io->ipsec_out_zoneid;
22142 		}
22143 	}
22144 
22145 	first_mp = mp;
22146 	ipsec_len = 0;
22147 
22148 	if (first_mp->b_datap->db_type == M_CTL) {
22149 		io = (ipsec_out_t *)first_mp->b_rptr;
22150 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22151 		mp = first_mp->b_cont;
22152 		ipsec_len = ipsec_out_extra_length(first_mp);
22153 		ASSERT(ipsec_len >= 0);
22154 		/* We already picked up the zoneid from the M_CTL above */
22155 		ASSERT(zoneid == io->ipsec_out_zoneid);
22156 		ASSERT(zoneid != ALL_ZONES);
22157 
22158 		/*
22159 		 * Drop M_CTL here if IPsec processing is not needed.
22160 		 * (Non-IPsec use of M_CTL extracted any information it
22161 		 * needed above).
22162 		 */
22163 		if (ipsec_len == 0) {
22164 			freeb(first_mp);
22165 			first_mp = mp;
22166 		}
22167 	}
22168 
22169 	/*
22170 	 * Fast path for ip_wput_ire
22171 	 */
22172 
22173 	ipha = (ipha_t *)mp->b_rptr;
22174 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22175 	dst = ipha->ipha_dst;
22176 
22177 	/*
22178 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22179 	 * if the socket is a SOCK_RAW type. The transport checksum should
22180 	 * be provided in the pre-built packet, so we don't need to compute it.
22181 	 * Also, other application set flags, like DF, should not be altered.
22182 	 * Other transport MUST pass down zero.
22183 	 */
22184 	ip_hdr_included = ipha->ipha_ident;
22185 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22186 
22187 	if (CLASSD(dst)) {
22188 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22189 		    ntohl(dst),
22190 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22191 		    ntohl(ire->ire_addr)));
22192 	}
22193 
22194 /* Macros to extract header fields from data already in registers */
22195 #ifdef	_BIG_ENDIAN
22196 #define	V_HLEN	(v_hlen_tos_len >> 24)
22197 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22198 #define	PROTO	(ttl_protocol & 0xFF)
22199 #else
22200 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22201 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22202 #define	PROTO	(ttl_protocol >> 8)
22203 #endif
22204 
22205 
22206 	orig_src = src = ipha->ipha_src;
22207 	/* (The loop back to "another" is explained down below.) */
22208 another:;
22209 	/*
22210 	 * Assign an ident value for this packet.  We assign idents on
22211 	 * a per destination basis out of the IRE.  There could be
22212 	 * other threads targeting the same destination, so we have to
22213 	 * arrange for a atomic increment.  Note that we use a 32-bit
22214 	 * atomic add because it has better performance than its
22215 	 * 16-bit sibling.
22216 	 *
22217 	 * If running in cluster mode and if the source address
22218 	 * belongs to a replicated service then vector through
22219 	 * cl_inet_ipident vector to allocate ip identifier
22220 	 * NOTE: This is a contract private interface with the
22221 	 * clustering group.
22222 	 */
22223 	clusterwide = 0;
22224 	if (cl_inet_ipident) {
22225 		ASSERT(cl_inet_isclusterwide);
22226 		netstackid_t stack_id = ipst->ips_netstack->netstack_stackid;
22227 
22228 		if ((*cl_inet_isclusterwide)(stack_id, IPPROTO_IP,
22229 		    AF_INET, (uint8_t *)(uintptr_t)src, NULL)) {
22230 			ipha->ipha_ident = (*cl_inet_ipident)(stack_id,
22231 			    IPPROTO_IP, AF_INET, (uint8_t *)(uintptr_t)src,
22232 			    (uint8_t *)(uintptr_t)dst, NULL);
22233 			clusterwide = 1;
22234 		}
22235 	}
22236 	if (!clusterwide) {
22237 		ipha->ipha_ident =
22238 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22239 	}
22240 
22241 #ifndef _BIG_ENDIAN
22242 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22243 #endif
22244 
22245 	/*
22246 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22247 	 * This is needed to obey conn_unspec_src when packets go through
22248 	 * ip_newroute + arp.
22249 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22250 	 */
22251 	if (src == INADDR_ANY && !unspec_src) {
22252 		/*
22253 		 * Assign the appropriate source address from the IRE if none
22254 		 * was specified.
22255 		 */
22256 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22257 
22258 		src = ire->ire_src_addr;
22259 		if (connp == NULL) {
22260 			ip1dbg(("ip_wput_ire: no connp and no src "
22261 			    "address for dst 0x%x, using src 0x%x\n",
22262 			    ntohl(dst),
22263 			    ntohl(src)));
22264 		}
22265 		ipha->ipha_src = src;
22266 	}
22267 	stq = ire->ire_stq;
22268 
22269 	/*
22270 	 * We only allow ire chains for broadcasts since there will
22271 	 * be multiple IRE_CACHE entries for the same multicast
22272 	 * address (one per ipif).
22273 	 */
22274 	next_mp = NULL;
22275 
22276 	/* broadcast packet */
22277 	if (ire->ire_type == IRE_BROADCAST)
22278 		goto broadcast;
22279 
22280 	/* loopback ? */
22281 	if (stq == NULL)
22282 		goto nullstq;
22283 
22284 	/* The ill_index for outbound ILL */
22285 	ill_index = Q_TO_INDEX(stq);
22286 
22287 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22288 	ttl_protocol = ((uint16_t *)ipha)[4];
22289 
22290 	/* pseudo checksum (do it in parts for IP header checksum) */
22291 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22292 
22293 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22294 		queue_t *dev_q = stq->q_next;
22295 
22296 		/* flow controlled */
22297 		if (DEV_Q_FLOW_BLOCKED(dev_q))
22298 			goto blocked;
22299 
22300 		if ((PROTO == IPPROTO_UDP) &&
22301 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22302 			hlen = (V_HLEN & 0xF) << 2;
22303 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22304 			if (*up != 0) {
22305 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22306 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22307 				/* Software checksum? */
22308 				if (DB_CKSUMFLAGS(mp) == 0) {
22309 					IP_STAT(ipst, ip_out_sw_cksum);
22310 					IP_STAT_UPDATE(ipst,
22311 					    ip_udp_out_sw_cksum_bytes,
22312 					    LENGTH - hlen);
22313 				}
22314 			}
22315 		}
22316 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22317 		hlen = (V_HLEN & 0xF) << 2;
22318 		if (PROTO == IPPROTO_TCP) {
22319 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22320 			/*
22321 			 * The packet header is processed once and for all, even
22322 			 * in the multirouting case. We disable hardware
22323 			 * checksum if the packet is multirouted, as it will be
22324 			 * replicated via several interfaces, and not all of
22325 			 * them may have this capability.
22326 			 */
22327 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22328 			    LENGTH, max_frag, ipsec_len, cksum);
22329 			/* Software checksum? */
22330 			if (DB_CKSUMFLAGS(mp) == 0) {
22331 				IP_STAT(ipst, ip_out_sw_cksum);
22332 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22333 				    LENGTH - hlen);
22334 			}
22335 		} else {
22336 			sctp_hdr_t	*sctph;
22337 
22338 			ASSERT(PROTO == IPPROTO_SCTP);
22339 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22340 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22341 			/*
22342 			 * Zero out the checksum field to ensure proper
22343 			 * checksum calculation.
22344 			 */
22345 			sctph->sh_chksum = 0;
22346 #ifdef	DEBUG
22347 			if (!skip_sctp_cksum)
22348 #endif
22349 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22350 		}
22351 	}
22352 
22353 	/*
22354 	 * If this is a multicast packet and originated from ip_wput
22355 	 * we need to do loopback and forwarding checks. If it comes
22356 	 * from ip_wput_multicast, we SHOULD not do this.
22357 	 */
22358 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22359 
22360 	/* checksum */
22361 	cksum += ttl_protocol;
22362 
22363 	/* fragment the packet */
22364 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22365 		goto fragmentit;
22366 	/*
22367 	 * Don't use frag_flag if packet is pre-built or source
22368 	 * routed or if multicast (since multicast packets do
22369 	 * not solicit ICMP "packet too big" messages).
22370 	 */
22371 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22372 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22373 	    !ip_source_route_included(ipha)) &&
22374 	    !CLASSD(ipha->ipha_dst))
22375 		ipha->ipha_fragment_offset_and_flags |=
22376 		    htons(ire->ire_frag_flag);
22377 
22378 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22379 		/* calculate IP header checksum */
22380 		cksum += ipha->ipha_ident;
22381 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22382 		cksum += ipha->ipha_fragment_offset_and_flags;
22383 
22384 		/* IP options present */
22385 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22386 		if (hlen)
22387 			goto checksumoptions;
22388 
22389 		/* calculate hdr checksum */
22390 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22391 		cksum = ~(cksum + (cksum >> 16));
22392 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22393 	}
22394 	if (ipsec_len != 0) {
22395 		/*
22396 		 * We will do the rest of the processing after
22397 		 * we come back from IPsec in ip_wput_ipsec_out().
22398 		 */
22399 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22400 
22401 		io = (ipsec_out_t *)first_mp->b_rptr;
22402 		io->ipsec_out_ill_index =
22403 		    ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
22404 		ipsec_out_process(q, first_mp, ire, 0);
22405 		ire_refrele(ire);
22406 		if (conn_outgoing_ill != NULL)
22407 			ill_refrele(conn_outgoing_ill);
22408 		return;
22409 	}
22410 
22411 	/*
22412 	 * In most cases, the emission loop below is entered only
22413 	 * once. Only in the case where the ire holds the
22414 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22415 	 * flagged ires in the bucket, and send the packet
22416 	 * through all crossed RTF_MULTIRT routes.
22417 	 */
22418 	if (ire->ire_flags & RTF_MULTIRT) {
22419 		multirt_send = B_TRUE;
22420 	}
22421 	do {
22422 		if (multirt_send) {
22423 			irb_t *irb;
22424 			/*
22425 			 * We are in a multiple send case, need to get
22426 			 * the next ire and make a duplicate of the packet.
22427 			 * ire1 holds here the next ire to process in the
22428 			 * bucket. If multirouting is expected,
22429 			 * any non-RTF_MULTIRT ire that has the
22430 			 * right destination address is ignored.
22431 			 */
22432 			irb = ire->ire_bucket;
22433 			ASSERT(irb != NULL);
22434 
22435 			IRB_REFHOLD(irb);
22436 			for (ire1 = ire->ire_next;
22437 			    ire1 != NULL;
22438 			    ire1 = ire1->ire_next) {
22439 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22440 					continue;
22441 				if (ire1->ire_addr != ire->ire_addr)
22442 					continue;
22443 				if (ire1->ire_marks &
22444 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
22445 					continue;
22446 
22447 				/* Got one */
22448 				IRE_REFHOLD(ire1);
22449 				break;
22450 			}
22451 			IRB_REFRELE(irb);
22452 
22453 			if (ire1 != NULL) {
22454 				next_mp = copyb(mp);
22455 				if ((next_mp == NULL) ||
22456 				    ((mp->b_cont != NULL) &&
22457 				    ((next_mp->b_cont =
22458 				    dupmsg(mp->b_cont)) == NULL))) {
22459 					freemsg(next_mp);
22460 					next_mp = NULL;
22461 					ire_refrele(ire1);
22462 					ire1 = NULL;
22463 				}
22464 			}
22465 
22466 			/* Last multiroute ire; don't loop anymore. */
22467 			if (ire1 == NULL) {
22468 				multirt_send = B_FALSE;
22469 			}
22470 		}
22471 
22472 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22473 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22474 		    mblk_t *, mp);
22475 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22476 		    ipst->ips_ipv4firewall_physical_out,
22477 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22478 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22479 
22480 		if (mp == NULL)
22481 			goto release_ire_and_ill;
22482 
22483 		if (ipst->ips_ipobs_enabled) {
22484 			zoneid_t szone;
22485 
22486 			/*
22487 			 * On the outbound path the destination zone will be
22488 			 * unknown as we're sending this packet out on the
22489 			 * wire.
22490 			 */
22491 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
22492 			    ALL_ZONES);
22493 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
22494 			    ire->ire_ipif->ipif_ill, IPV4_VERSION, 0, ipst);
22495 		}
22496 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22497 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22498 
22499 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE, connp);
22500 
22501 		if ((pktxmit_state == SEND_FAILED) ||
22502 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22503 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22504 			    "- packet dropped\n"));
22505 release_ire_and_ill:
22506 			ire_refrele(ire);
22507 			if (next_mp != NULL) {
22508 				freemsg(next_mp);
22509 				ire_refrele(ire1);
22510 			}
22511 			if (conn_outgoing_ill != NULL)
22512 				ill_refrele(conn_outgoing_ill);
22513 			return;
22514 		}
22515 
22516 		if (CLASSD(dst)) {
22517 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22518 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22519 			    LENGTH);
22520 		}
22521 
22522 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22523 		    "ip_wput_ire_end: q %p (%S)",
22524 		    q, "last copy out");
22525 		IRE_REFRELE(ire);
22526 
22527 		if (multirt_send) {
22528 			ASSERT(ire1);
22529 			/*
22530 			 * Proceed with the next RTF_MULTIRT ire,
22531 			 * Also set up the send-to queue accordingly.
22532 			 */
22533 			ire = ire1;
22534 			ire1 = NULL;
22535 			stq = ire->ire_stq;
22536 			mp = next_mp;
22537 			next_mp = NULL;
22538 			ipha = (ipha_t *)mp->b_rptr;
22539 			ill_index = Q_TO_INDEX(stq);
22540 			ill = (ill_t *)stq->q_ptr;
22541 		}
22542 	} while (multirt_send);
22543 	if (conn_outgoing_ill != NULL)
22544 		ill_refrele(conn_outgoing_ill);
22545 	return;
22546 
22547 	/*
22548 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22549 	 */
22550 broadcast:
22551 	{
22552 		/*
22553 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22554 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22555 		 * can be overridden stack-wide through the ip_broadcast_ttl
22556 		 * ndd tunable, or on a per-connection basis through the
22557 		 * IP_BROADCAST_TTL socket option.
22558 		 *
22559 		 * In the event that we are replying to incoming ICMP packets,
22560 		 * connp could be NULL.
22561 		 */
22562 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22563 		if (connp != NULL) {
22564 			if (connp->conn_dontroute)
22565 				ipha->ipha_ttl = 1;
22566 			else if (connp->conn_broadcast_ttl != 0)
22567 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22568 		}
22569 
22570 		/*
22571 		 * Note that we are not doing a IRB_REFHOLD here.
22572 		 * Actually we don't care if the list changes i.e
22573 		 * if somebody deletes an IRE from the list while
22574 		 * we drop the lock, the next time we come around
22575 		 * ire_next will be NULL and hence we won't send
22576 		 * out multiple copies which is fine.
22577 		 */
22578 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22579 		ire1 = ire->ire_next;
22580 		if (conn_outgoing_ill != NULL) {
22581 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22582 				ASSERT(ire1 == ire->ire_next);
22583 				if (ire1 != NULL && ire1->ire_addr == dst) {
22584 					ire_refrele(ire);
22585 					ire = ire1;
22586 					IRE_REFHOLD(ire);
22587 					ire1 = ire->ire_next;
22588 					continue;
22589 				}
22590 				rw_exit(&ire->ire_bucket->irb_lock);
22591 				/* Did not find a matching ill */
22592 				ip1dbg(("ip_wput_ire: broadcast with no "
22593 				    "matching IP_BOUND_IF ill %s dst %x\n",
22594 				    conn_outgoing_ill->ill_name, dst));
22595 				freemsg(first_mp);
22596 				if (ire != NULL)
22597 					ire_refrele(ire);
22598 				ill_refrele(conn_outgoing_ill);
22599 				return;
22600 			}
22601 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22602 			/*
22603 			 * If the next IRE has the same address and is not one
22604 			 * of the two copies that we need to send, try to see
22605 			 * whether this copy should be sent at all. This
22606 			 * assumes that we insert loopbacks first and then
22607 			 * non-loopbacks. This is acheived by inserting the
22608 			 * loopback always before non-loopback.
22609 			 * This is used to send a single copy of a broadcast
22610 			 * packet out all physical interfaces that have an
22611 			 * matching IRE_BROADCAST while also looping
22612 			 * back one copy (to ip_wput_local) for each
22613 			 * matching physical interface. However, we avoid
22614 			 * sending packets out different logical that match by
22615 			 * having ipif_up/ipif_down supress duplicate
22616 			 * IRE_BROADCASTS.
22617 			 *
22618 			 * This feature is currently used to get broadcasts
22619 			 * sent to multiple interfaces, when the broadcast
22620 			 * address being used applies to multiple interfaces.
22621 			 * For example, a whole net broadcast will be
22622 			 * replicated on every connected subnet of
22623 			 * the target net.
22624 			 *
22625 			 * Each zone has its own set of IRE_BROADCASTs, so that
22626 			 * we're able to distribute inbound packets to multiple
22627 			 * zones who share a broadcast address. We avoid looping
22628 			 * back outbound packets in different zones but on the
22629 			 * same ill, as the application would see duplicates.
22630 			 *
22631 			 * This logic assumes that ire_add_v4() groups the
22632 			 * IRE_BROADCAST entries so that those with the same
22633 			 * ire_addr are kept together.
22634 			 */
22635 			ire_ill = ire->ire_ipif->ipif_ill;
22636 			if (ire->ire_stq != NULL || ire1->ire_stq == NULL) {
22637 				while (ire1 != NULL && ire1->ire_addr == dst) {
22638 					ire1_ill = ire1->ire_ipif->ipif_ill;
22639 					if (ire1_ill != ire_ill)
22640 						break;
22641 					ire1 = ire1->ire_next;
22642 				}
22643 			}
22644 		}
22645 		ASSERT(multirt_send == B_FALSE);
22646 		if (ire1 != NULL && ire1->ire_addr == dst) {
22647 			if ((ire->ire_flags & RTF_MULTIRT) &&
22648 			    (ire1->ire_flags & RTF_MULTIRT)) {
22649 				/*
22650 				 * We are in the multirouting case.
22651 				 * The message must be sent at least
22652 				 * on both ires. These ires have been
22653 				 * inserted AFTER the standard ones
22654 				 * in ip_rt_add(). There are thus no
22655 				 * other ire entries for the destination
22656 				 * address in the rest of the bucket
22657 				 * that do not have the RTF_MULTIRT
22658 				 * flag. We don't process a copy
22659 				 * of the message here. This will be
22660 				 * done in the final sending loop.
22661 				 */
22662 				multirt_send = B_TRUE;
22663 			} else {
22664 				next_mp = ip_copymsg(first_mp);
22665 				if (next_mp != NULL)
22666 					IRE_REFHOLD(ire1);
22667 			}
22668 		}
22669 		rw_exit(&ire->ire_bucket->irb_lock);
22670 	}
22671 
22672 	if (stq) {
22673 		/*
22674 		 * A non-NULL send-to queue means this packet is going
22675 		 * out of this machine.
22676 		 */
22677 		out_ill = (ill_t *)stq->q_ptr;
22678 
22679 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22680 		ttl_protocol = ((uint16_t *)ipha)[4];
22681 		/*
22682 		 * We accumulate the pseudo header checksum in cksum.
22683 		 * This is pretty hairy code, so watch close.  One
22684 		 * thing to keep in mind is that UDP and TCP have
22685 		 * stored their respective datagram lengths in their
22686 		 * checksum fields.  This lines things up real nice.
22687 		 */
22688 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22689 		    (src >> 16) + (src & 0xFFFF);
22690 		/*
22691 		 * We assume the udp checksum field contains the
22692 		 * length, so to compute the pseudo header checksum,
22693 		 * all we need is the protocol number and src/dst.
22694 		 */
22695 		/* Provide the checksums for UDP and TCP. */
22696 		if ((PROTO == IPPROTO_TCP) &&
22697 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22698 			/* hlen gets the number of uchar_ts in the IP header */
22699 			hlen = (V_HLEN & 0xF) << 2;
22700 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22701 			IP_STAT(ipst, ip_out_sw_cksum);
22702 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22703 			    LENGTH - hlen);
22704 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22705 		} else if (PROTO == IPPROTO_SCTP &&
22706 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22707 			sctp_hdr_t	*sctph;
22708 
22709 			hlen = (V_HLEN & 0xF) << 2;
22710 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22711 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22712 			sctph->sh_chksum = 0;
22713 #ifdef	DEBUG
22714 			if (!skip_sctp_cksum)
22715 #endif
22716 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22717 		} else {
22718 			queue_t	*dev_q = stq->q_next;
22719 
22720 			if (DEV_Q_FLOW_BLOCKED(dev_q)) {
22721 blocked:
22722 				ipha->ipha_ident = ip_hdr_included;
22723 				/*
22724 				 * If we don't have a conn to apply
22725 				 * backpressure, free the message.
22726 				 * In the ire_send path, we don't know
22727 				 * the position to requeue the packet. Rather
22728 				 * than reorder packets, we just drop this
22729 				 * packet.
22730 				 */
22731 				if (ipst->ips_ip_output_queue &&
22732 				    connp != NULL &&
22733 				    caller != IRE_SEND) {
22734 					if (caller == IP_WSRV) {
22735 						connp->conn_did_putbq = 1;
22736 						(void) putbq(connp->conn_wq,
22737 						    first_mp);
22738 						conn_drain_insert(connp);
22739 						/*
22740 						 * This is the service thread,
22741 						 * and the queue is already
22742 						 * noenabled. The check for
22743 						 * canput and the putbq is not
22744 						 * atomic. So we need to check
22745 						 * again.
22746 						 */
22747 						if (canput(stq->q_next))
22748 							connp->conn_did_putbq
22749 							    = 0;
22750 						IP_STAT(ipst, ip_conn_flputbq);
22751 					} else {
22752 						/*
22753 						 * We are not the service proc.
22754 						 * ip_wsrv will be scheduled or
22755 						 * is already running.
22756 						 */
22757 
22758 						(void) putq(connp->conn_wq,
22759 						    first_mp);
22760 					}
22761 				} else {
22762 					out_ill = (ill_t *)stq->q_ptr;
22763 					BUMP_MIB(out_ill->ill_ip_mib,
22764 					    ipIfStatsOutDiscards);
22765 					freemsg(first_mp);
22766 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22767 					    "ip_wput_ire_end: q %p (%S)",
22768 					    q, "discard");
22769 				}
22770 				ire_refrele(ire);
22771 				if (next_mp) {
22772 					ire_refrele(ire1);
22773 					freemsg(next_mp);
22774 				}
22775 				if (conn_outgoing_ill != NULL)
22776 					ill_refrele(conn_outgoing_ill);
22777 				return;
22778 			}
22779 			if ((PROTO == IPPROTO_UDP) &&
22780 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22781 				/*
22782 				 * hlen gets the number of uchar_ts in the
22783 				 * IP header
22784 				 */
22785 				hlen = (V_HLEN & 0xF) << 2;
22786 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22787 				max_frag = ire->ire_max_frag;
22788 				if (*up != 0) {
22789 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22790 					    up, PROTO, hlen, LENGTH, max_frag,
22791 					    ipsec_len, cksum);
22792 					/* Software checksum? */
22793 					if (DB_CKSUMFLAGS(mp) == 0) {
22794 						IP_STAT(ipst, ip_out_sw_cksum);
22795 						IP_STAT_UPDATE(ipst,
22796 						    ip_udp_out_sw_cksum_bytes,
22797 						    LENGTH - hlen);
22798 					}
22799 				}
22800 			}
22801 		}
22802 		/*
22803 		 * Need to do this even when fragmenting. The local
22804 		 * loopback can be done without computing checksums
22805 		 * but forwarding out other interface must be done
22806 		 * after the IP checksum (and ULP checksums) have been
22807 		 * computed.
22808 		 *
22809 		 * NOTE : multicast_forward is set only if this packet
22810 		 * originated from ip_wput. For packets originating from
22811 		 * ip_wput_multicast, it is not set.
22812 		 */
22813 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22814 multi_loopback:
22815 			ip2dbg(("ip_wput: multicast, loop %d\n",
22816 			    conn_multicast_loop));
22817 
22818 			/*  Forget header checksum offload */
22819 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22820 
22821 			/*
22822 			 * Local loopback of multicasts?  Check the
22823 			 * ill.
22824 			 *
22825 			 * Note that the loopback function will not come
22826 			 * in through ip_rput - it will only do the
22827 			 * client fanout thus we need to do an mforward
22828 			 * as well.  The is different from the BSD
22829 			 * logic.
22830 			 */
22831 			if (ill != NULL) {
22832 				if (ilm_lookup_ill(ill, ipha->ipha_dst,
22833 				    ALL_ZONES) != NULL) {
22834 					/*
22835 					 * Pass along the virtual output q.
22836 					 * ip_wput_local() will distribute the
22837 					 * packet to all the matching zones,
22838 					 * except the sending zone when
22839 					 * IP_MULTICAST_LOOP is false.
22840 					 */
22841 					ip_multicast_loopback(q, ill, first_mp,
22842 					    conn_multicast_loop ? 0 :
22843 					    IP_FF_NO_MCAST_LOOP, zoneid);
22844 				}
22845 			}
22846 			if (ipha->ipha_ttl == 0) {
22847 				/*
22848 				 * 0 => only to this host i.e. we are
22849 				 * done. We are also done if this was the
22850 				 * loopback interface since it is sufficient
22851 				 * to loopback one copy of a multicast packet.
22852 				 */
22853 				freemsg(first_mp);
22854 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22855 				    "ip_wput_ire_end: q %p (%S)",
22856 				    q, "loopback");
22857 				ire_refrele(ire);
22858 				if (conn_outgoing_ill != NULL)
22859 					ill_refrele(conn_outgoing_ill);
22860 				return;
22861 			}
22862 			/*
22863 			 * ILLF_MULTICAST is checked in ip_newroute
22864 			 * i.e. we don't need to check it here since
22865 			 * all IRE_CACHEs come from ip_newroute.
22866 			 * For multicast traffic, SO_DONTROUTE is interpreted
22867 			 * to mean only send the packet out the interface
22868 			 * (optionally specified with IP_MULTICAST_IF)
22869 			 * and do not forward it out additional interfaces.
22870 			 * RSVP and the rsvp daemon is an example of a
22871 			 * protocol and user level process that
22872 			 * handles it's own routing. Hence, it uses the
22873 			 * SO_DONTROUTE option to accomplish this.
22874 			 */
22875 
22876 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
22877 			    ill != NULL) {
22878 				/* Unconditionally redo the checksum */
22879 				ipha->ipha_hdr_checksum = 0;
22880 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22881 
22882 				/*
22883 				 * If this needs to go out secure, we need
22884 				 * to wait till we finish the IPsec
22885 				 * processing.
22886 				 */
22887 				if (ipsec_len == 0 &&
22888 				    ip_mforward(ill, ipha, mp)) {
22889 					freemsg(first_mp);
22890 					ip1dbg(("ip_wput: mforward failed\n"));
22891 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22892 					    "ip_wput_ire_end: q %p (%S)",
22893 					    q, "mforward failed");
22894 					ire_refrele(ire);
22895 					if (conn_outgoing_ill != NULL)
22896 						ill_refrele(conn_outgoing_ill);
22897 					return;
22898 				}
22899 			}
22900 		}
22901 		max_frag = ire->ire_max_frag;
22902 		cksum += ttl_protocol;
22903 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
22904 			/* No fragmentation required for this one. */
22905 			/*
22906 			 * Don't use frag_flag if packet is pre-built or source
22907 			 * routed or if multicast (since multicast packets do
22908 			 * not solicit ICMP "packet too big" messages).
22909 			 */
22910 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22911 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22912 			    !ip_source_route_included(ipha)) &&
22913 			    !CLASSD(ipha->ipha_dst))
22914 				ipha->ipha_fragment_offset_and_flags |=
22915 				    htons(ire->ire_frag_flag);
22916 
22917 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22918 				/* Complete the IP header checksum. */
22919 				cksum += ipha->ipha_ident;
22920 				cksum += (v_hlen_tos_len >> 16)+
22921 				    (v_hlen_tos_len & 0xFFFF);
22922 				cksum += ipha->ipha_fragment_offset_and_flags;
22923 				hlen = (V_HLEN & 0xF) -
22924 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22925 				if (hlen) {
22926 checksumoptions:
22927 					/*
22928 					 * Account for the IP Options in the IP
22929 					 * header checksum.
22930 					 */
22931 					up = (uint16_t *)(rptr+
22932 					    IP_SIMPLE_HDR_LENGTH);
22933 					do {
22934 						cksum += up[0];
22935 						cksum += up[1];
22936 						up += 2;
22937 					} while (--hlen);
22938 				}
22939 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22940 				cksum = ~(cksum + (cksum >> 16));
22941 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
22942 			}
22943 			if (ipsec_len != 0) {
22944 				ipsec_out_process(q, first_mp, ire, ill_index);
22945 				if (!next_mp) {
22946 					ire_refrele(ire);
22947 					if (conn_outgoing_ill != NULL)
22948 						ill_refrele(conn_outgoing_ill);
22949 					return;
22950 				}
22951 				goto next;
22952 			}
22953 
22954 			/*
22955 			 * multirt_send has already been handled
22956 			 * for broadcast, but not yet for multicast
22957 			 * or IP options.
22958 			 */
22959 			if (next_mp == NULL) {
22960 				if (ire->ire_flags & RTF_MULTIRT) {
22961 					multirt_send = B_TRUE;
22962 				}
22963 			}
22964 
22965 			/*
22966 			 * In most cases, the emission loop below is
22967 			 * entered only once. Only in the case where
22968 			 * the ire holds the RTF_MULTIRT flag, do we loop
22969 			 * to process all RTF_MULTIRT ires in the bucket,
22970 			 * and send the packet through all crossed
22971 			 * RTF_MULTIRT routes.
22972 			 */
22973 			do {
22974 				if (multirt_send) {
22975 					irb_t *irb;
22976 
22977 					irb = ire->ire_bucket;
22978 					ASSERT(irb != NULL);
22979 					/*
22980 					 * We are in a multiple send case,
22981 					 * need to get the next IRE and make
22982 					 * a duplicate of the packet.
22983 					 */
22984 					IRB_REFHOLD(irb);
22985 					for (ire1 = ire->ire_next;
22986 					    ire1 != NULL;
22987 					    ire1 = ire1->ire_next) {
22988 						if (!(ire1->ire_flags &
22989 						    RTF_MULTIRT))
22990 							continue;
22991 
22992 						if (ire1->ire_addr !=
22993 						    ire->ire_addr)
22994 							continue;
22995 
22996 						if (ire1->ire_marks &
22997 						    (IRE_MARK_CONDEMNED |
22998 						    IRE_MARK_TESTHIDDEN))
22999 							continue;
23000 
23001 						/* Got one */
23002 						IRE_REFHOLD(ire1);
23003 						break;
23004 					}
23005 					IRB_REFRELE(irb);
23006 
23007 					if (ire1 != NULL) {
23008 						next_mp = copyb(mp);
23009 						if ((next_mp == NULL) ||
23010 						    ((mp->b_cont != NULL) &&
23011 						    ((next_mp->b_cont =
23012 						    dupmsg(mp->b_cont))
23013 						    == NULL))) {
23014 							freemsg(next_mp);
23015 							next_mp = NULL;
23016 							ire_refrele(ire1);
23017 							ire1 = NULL;
23018 						}
23019 					}
23020 
23021 					/*
23022 					 * Last multiroute ire; don't loop
23023 					 * anymore. The emission is over
23024 					 * and next_mp is NULL.
23025 					 */
23026 					if (ire1 == NULL) {
23027 						multirt_send = B_FALSE;
23028 					}
23029 				}
23030 
23031 				out_ill = ire_to_ill(ire);
23032 				DTRACE_PROBE4(ip4__physical__out__start,
23033 				    ill_t *, NULL,
23034 				    ill_t *, out_ill,
23035 				    ipha_t *, ipha, mblk_t *, mp);
23036 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23037 				    ipst->ips_ipv4firewall_physical_out,
23038 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23039 				DTRACE_PROBE1(ip4__physical__out__end,
23040 				    mblk_t *, mp);
23041 				if (mp == NULL)
23042 					goto release_ire_and_ill_2;
23043 
23044 				ASSERT(ipsec_len == 0);
23045 				mp->b_prev =
23046 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23047 				DTRACE_PROBE2(ip__xmit__2,
23048 				    mblk_t *, mp, ire_t *, ire);
23049 				pktxmit_state = ip_xmit_v4(mp, ire,
23050 				    NULL, B_TRUE, connp);
23051 				if ((pktxmit_state == SEND_FAILED) ||
23052 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23053 release_ire_and_ill_2:
23054 					if (next_mp) {
23055 						freemsg(next_mp);
23056 						ire_refrele(ire1);
23057 					}
23058 					ire_refrele(ire);
23059 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23060 					    "ip_wput_ire_end: q %p (%S)",
23061 					    q, "discard MDATA");
23062 					if (conn_outgoing_ill != NULL)
23063 						ill_refrele(conn_outgoing_ill);
23064 					return;
23065 				}
23066 
23067 				if (CLASSD(dst)) {
23068 					BUMP_MIB(out_ill->ill_ip_mib,
23069 					    ipIfStatsHCOutMcastPkts);
23070 					UPDATE_MIB(out_ill->ill_ip_mib,
23071 					    ipIfStatsHCOutMcastOctets,
23072 					    LENGTH);
23073 				} else if (ire->ire_type == IRE_BROADCAST) {
23074 					BUMP_MIB(out_ill->ill_ip_mib,
23075 					    ipIfStatsHCOutBcastPkts);
23076 				}
23077 
23078 				if (multirt_send) {
23079 					/*
23080 					 * We are in a multiple send case,
23081 					 * need to re-enter the sending loop
23082 					 * using the next ire.
23083 					 */
23084 					ire_refrele(ire);
23085 					ire = ire1;
23086 					stq = ire->ire_stq;
23087 					mp = next_mp;
23088 					next_mp = NULL;
23089 					ipha = (ipha_t *)mp->b_rptr;
23090 					ill_index = Q_TO_INDEX(stq);
23091 				}
23092 			} while (multirt_send);
23093 
23094 			if (!next_mp) {
23095 				/*
23096 				 * Last copy going out (the ultra-common
23097 				 * case).  Note that we intentionally replicate
23098 				 * the putnext rather than calling it before
23099 				 * the next_mp check in hopes of a little
23100 				 * tail-call action out of the compiler.
23101 				 */
23102 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23103 				    "ip_wput_ire_end: q %p (%S)",
23104 				    q, "last copy out(1)");
23105 				ire_refrele(ire);
23106 				if (conn_outgoing_ill != NULL)
23107 					ill_refrele(conn_outgoing_ill);
23108 				return;
23109 			}
23110 			/* More copies going out below. */
23111 		} else {
23112 			int offset;
23113 fragmentit:
23114 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23115 			/*
23116 			 * If this would generate a icmp_frag_needed message,
23117 			 * we need to handle it before we do the IPsec
23118 			 * processing. Otherwise, we need to strip the IPsec
23119 			 * headers before we send up the message to the ULPs
23120 			 * which becomes messy and difficult.
23121 			 */
23122 			if (ipsec_len != 0) {
23123 				if ((max_frag < (unsigned int)(LENGTH +
23124 				    ipsec_len)) && (offset & IPH_DF)) {
23125 					out_ill = (ill_t *)stq->q_ptr;
23126 					BUMP_MIB(out_ill->ill_ip_mib,
23127 					    ipIfStatsOutFragFails);
23128 					BUMP_MIB(out_ill->ill_ip_mib,
23129 					    ipIfStatsOutFragReqds);
23130 					ipha->ipha_hdr_checksum = 0;
23131 					ipha->ipha_hdr_checksum =
23132 					    (uint16_t)ip_csum_hdr(ipha);
23133 					icmp_frag_needed(ire->ire_stq, first_mp,
23134 					    max_frag, zoneid, ipst);
23135 					if (!next_mp) {
23136 						ire_refrele(ire);
23137 						if (conn_outgoing_ill != NULL) {
23138 							ill_refrele(
23139 							    conn_outgoing_ill);
23140 						}
23141 						return;
23142 					}
23143 				} else {
23144 					/*
23145 					 * This won't cause a icmp_frag_needed
23146 					 * message. to be generated. Send it on
23147 					 * the wire. Note that this could still
23148 					 * cause fragmentation and all we
23149 					 * do is the generation of the message
23150 					 * to the ULP if needed before IPsec.
23151 					 */
23152 					if (!next_mp) {
23153 						ipsec_out_process(q, first_mp,
23154 						    ire, ill_index);
23155 						TRACE_2(TR_FAC_IP,
23156 						    TR_IP_WPUT_IRE_END,
23157 						    "ip_wput_ire_end: q %p "
23158 						    "(%S)", q,
23159 						    "last ipsec_out_process");
23160 						ire_refrele(ire);
23161 						if (conn_outgoing_ill != NULL) {
23162 							ill_refrele(
23163 							    conn_outgoing_ill);
23164 						}
23165 						return;
23166 					}
23167 					ipsec_out_process(q, first_mp,
23168 					    ire, ill_index);
23169 				}
23170 			} else {
23171 				/*
23172 				 * Initiate IPPF processing. For
23173 				 * fragmentable packets we finish
23174 				 * all QOS packet processing before
23175 				 * calling:
23176 				 * ip_wput_ire_fragmentit->ip_wput_frag
23177 				 */
23178 
23179 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23180 					ip_process(IPP_LOCAL_OUT, &mp,
23181 					    ill_index);
23182 					if (mp == NULL) {
23183 						out_ill = (ill_t *)stq->q_ptr;
23184 						BUMP_MIB(out_ill->ill_ip_mib,
23185 						    ipIfStatsOutDiscards);
23186 						if (next_mp != NULL) {
23187 							freemsg(next_mp);
23188 							ire_refrele(ire1);
23189 						}
23190 						ire_refrele(ire);
23191 						TRACE_2(TR_FAC_IP,
23192 						    TR_IP_WPUT_IRE_END,
23193 						    "ip_wput_ire: q %p (%S)",
23194 						    q, "discard MDATA");
23195 						if (conn_outgoing_ill != NULL) {
23196 							ill_refrele(
23197 							    conn_outgoing_ill);
23198 						}
23199 						return;
23200 					}
23201 				}
23202 				if (!next_mp) {
23203 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23204 					    "ip_wput_ire_end: q %p (%S)",
23205 					    q, "last fragmentation");
23206 					ip_wput_ire_fragmentit(mp, ire,
23207 					    zoneid, ipst, connp);
23208 					ire_refrele(ire);
23209 					if (conn_outgoing_ill != NULL)
23210 						ill_refrele(conn_outgoing_ill);
23211 					return;
23212 				}
23213 				ip_wput_ire_fragmentit(mp, ire,
23214 				    zoneid, ipst, connp);
23215 			}
23216 		}
23217 	} else {
23218 nullstq:
23219 		/* A NULL stq means the destination address is local. */
23220 		UPDATE_OB_PKT_COUNT(ire);
23221 		ire->ire_last_used_time = lbolt;
23222 		ASSERT(ire->ire_ipif != NULL);
23223 		if (!next_mp) {
23224 			/*
23225 			 * Is there an "in" and "out" for traffic local
23226 			 * to a host (loopback)?  The code in Solaris doesn't
23227 			 * explicitly draw a line in its code for in vs out,
23228 			 * so we've had to draw a line in the sand: ip_wput_ire
23229 			 * is considered to be the "output" side and
23230 			 * ip_wput_local to be the "input" side.
23231 			 */
23232 			out_ill = ire_to_ill(ire);
23233 
23234 			/*
23235 			 * DTrace this as ip:::send.  A blocked packet will
23236 			 * fire the send probe, but not the receive probe.
23237 			 */
23238 			DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23239 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23240 			    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23241 
23242 			DTRACE_PROBE4(ip4__loopback__out__start,
23243 			    ill_t *, NULL, ill_t *, out_ill,
23244 			    ipha_t *, ipha, mblk_t *, first_mp);
23245 
23246 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23247 			    ipst->ips_ipv4firewall_loopback_out,
23248 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23249 
23250 			DTRACE_PROBE1(ip4__loopback__out_end,
23251 			    mblk_t *, first_mp);
23252 
23253 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23254 			    "ip_wput_ire_end: q %p (%S)",
23255 			    q, "local address");
23256 
23257 			if (first_mp != NULL)
23258 				ip_wput_local(q, out_ill, ipha,
23259 				    first_mp, ire, 0, ire->ire_zoneid);
23260 			ire_refrele(ire);
23261 			if (conn_outgoing_ill != NULL)
23262 				ill_refrele(conn_outgoing_ill);
23263 			return;
23264 		}
23265 
23266 		out_ill = ire_to_ill(ire);
23267 
23268 		/*
23269 		 * DTrace this as ip:::send.  A blocked packet will fire the
23270 		 * send probe, but not the receive probe.
23271 		 */
23272 		DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23273 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23274 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23275 
23276 		DTRACE_PROBE4(ip4__loopback__out__start,
23277 		    ill_t *, NULL, ill_t *, out_ill,
23278 		    ipha_t *, ipha, mblk_t *, first_mp);
23279 
23280 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23281 		    ipst->ips_ipv4firewall_loopback_out,
23282 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23283 
23284 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23285 
23286 		if (first_mp != NULL)
23287 			ip_wput_local(q, out_ill, ipha,
23288 			    first_mp, ire, 0, ire->ire_zoneid);
23289 	}
23290 next:
23291 	/*
23292 	 * More copies going out to additional interfaces.
23293 	 * ire1 has already been held. We don't need the
23294 	 * "ire" anymore.
23295 	 */
23296 	ire_refrele(ire);
23297 	ire = ire1;
23298 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23299 	mp = next_mp;
23300 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23301 	ill = ire_to_ill(ire);
23302 	first_mp = mp;
23303 	if (ipsec_len != 0) {
23304 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23305 		mp = mp->b_cont;
23306 	}
23307 	dst = ire->ire_addr;
23308 	ipha = (ipha_t *)mp->b_rptr;
23309 	/*
23310 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23311 	 * Restore ipha_ident "no checksum" flag.
23312 	 */
23313 	src = orig_src;
23314 	ipha->ipha_ident = ip_hdr_included;
23315 	goto another;
23316 
23317 #undef	rptr
23318 #undef	Q_TO_INDEX
23319 }
23320 
23321 /*
23322  * Routine to allocate a message that is used to notify the ULP about MDT.
23323  * The caller may provide a pointer to the link-layer MDT capabilities,
23324  * or NULL if MDT is to be disabled on the stream.
23325  */
23326 mblk_t *
23327 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23328 {
23329 	mblk_t *mp;
23330 	ip_mdt_info_t *mdti;
23331 	ill_mdt_capab_t *idst;
23332 
23333 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23334 		DB_TYPE(mp) = M_CTL;
23335 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23336 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23337 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23338 		idst = &(mdti->mdt_capab);
23339 
23340 		/*
23341 		 * If the caller provides us with the capability, copy
23342 		 * it over into our notification message; otherwise
23343 		 * we zero out the capability portion.
23344 		 */
23345 		if (isrc != NULL)
23346 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23347 		else
23348 			bzero((caddr_t)idst, sizeof (*idst));
23349 	}
23350 	return (mp);
23351 }
23352 
23353 /*
23354  * Routine which determines whether MDT can be enabled on the destination
23355  * IRE and IPC combination, and if so, allocates and returns the MDT
23356  * notification mblk that may be used by ULP.  We also check if we need to
23357  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23358  * MDT usage in the past have been lifted.  This gets called during IP
23359  * and ULP binding.
23360  */
23361 mblk_t *
23362 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23363     ill_mdt_capab_t *mdt_cap)
23364 {
23365 	mblk_t *mp;
23366 	boolean_t rc = B_FALSE;
23367 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23368 
23369 	ASSERT(dst_ire != NULL);
23370 	ASSERT(connp != NULL);
23371 	ASSERT(mdt_cap != NULL);
23372 
23373 	/*
23374 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23375 	 * Multidata, which is handled in tcp_multisend().  This
23376 	 * is the reason why we do all these checks here, to ensure
23377 	 * that we don't enable Multidata for the cases which we
23378 	 * can't handle at the moment.
23379 	 */
23380 	do {
23381 		/* Only do TCP at the moment */
23382 		if (connp->conn_ulp != IPPROTO_TCP)
23383 			break;
23384 
23385 		/*
23386 		 * IPsec outbound policy present?  Note that we get here
23387 		 * after calling ipsec_conn_cache_policy() where the global
23388 		 * policy checking is performed.  conn_latch will be
23389 		 * non-NULL as long as there's a policy defined,
23390 		 * i.e. conn_out_enforce_policy may be NULL in such case
23391 		 * when the connection is non-secure, and hence we check
23392 		 * further if the latch refers to an outbound policy.
23393 		 */
23394 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23395 			break;
23396 
23397 		/* CGTP (multiroute) is enabled? */
23398 		if (dst_ire->ire_flags & RTF_MULTIRT)
23399 			break;
23400 
23401 		/* Outbound IPQoS enabled? */
23402 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23403 			/*
23404 			 * In this case, we disable MDT for this and all
23405 			 * future connections going over the interface.
23406 			 */
23407 			mdt_cap->ill_mdt_on = 0;
23408 			break;
23409 		}
23410 
23411 		/* socket option(s) present? */
23412 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23413 			break;
23414 
23415 		rc = B_TRUE;
23416 	/* CONSTCOND */
23417 	} while (0);
23418 
23419 	/* Remember the result */
23420 	connp->conn_mdt_ok = rc;
23421 
23422 	if (!rc)
23423 		return (NULL);
23424 	else if (!mdt_cap->ill_mdt_on) {
23425 		/*
23426 		 * If MDT has been previously turned off in the past, and we
23427 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23428 		 * then enable it for this interface.
23429 		 */
23430 		mdt_cap->ill_mdt_on = 1;
23431 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23432 		    "interface %s\n", ill_name));
23433 	}
23434 
23435 	/* Allocate the MDT info mblk */
23436 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23437 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23438 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23439 		return (NULL);
23440 	}
23441 	return (mp);
23442 }
23443 
23444 /*
23445  * Routine to allocate a message that is used to notify the ULP about LSO.
23446  * The caller may provide a pointer to the link-layer LSO capabilities,
23447  * or NULL if LSO is to be disabled on the stream.
23448  */
23449 mblk_t *
23450 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23451 {
23452 	mblk_t *mp;
23453 	ip_lso_info_t *lsoi;
23454 	ill_lso_capab_t *idst;
23455 
23456 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23457 		DB_TYPE(mp) = M_CTL;
23458 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23459 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23460 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23461 		idst = &(lsoi->lso_capab);
23462 
23463 		/*
23464 		 * If the caller provides us with the capability, copy
23465 		 * it over into our notification message; otherwise
23466 		 * we zero out the capability portion.
23467 		 */
23468 		if (isrc != NULL)
23469 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23470 		else
23471 			bzero((caddr_t)idst, sizeof (*idst));
23472 	}
23473 	return (mp);
23474 }
23475 
23476 /*
23477  * Routine which determines whether LSO can be enabled on the destination
23478  * IRE and IPC combination, and if so, allocates and returns the LSO
23479  * notification mblk that may be used by ULP.  We also check if we need to
23480  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23481  * LSO usage in the past have been lifted.  This gets called during IP
23482  * and ULP binding.
23483  */
23484 mblk_t *
23485 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23486     ill_lso_capab_t *lso_cap)
23487 {
23488 	mblk_t *mp;
23489 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23490 
23491 	ASSERT(dst_ire != NULL);
23492 	ASSERT(connp != NULL);
23493 	ASSERT(lso_cap != NULL);
23494 
23495 	connp->conn_lso_ok = B_TRUE;
23496 
23497 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23498 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23499 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23500 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23501 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23502 		connp->conn_lso_ok = B_FALSE;
23503 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23504 			/*
23505 			 * Disable LSO for this and all future connections going
23506 			 * over the interface.
23507 			 */
23508 			lso_cap->ill_lso_on = 0;
23509 		}
23510 	}
23511 
23512 	if (!connp->conn_lso_ok)
23513 		return (NULL);
23514 	else if (!lso_cap->ill_lso_on) {
23515 		/*
23516 		 * If LSO has been previously turned off in the past, and we
23517 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23518 		 * then enable it for this interface.
23519 		 */
23520 		lso_cap->ill_lso_on = 1;
23521 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23522 		    ill_name));
23523 	}
23524 
23525 	/* Allocate the LSO info mblk */
23526 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23527 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23528 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23529 
23530 	return (mp);
23531 }
23532 
23533 /*
23534  * Create destination address attribute, and fill it with the physical
23535  * destination address and SAP taken from the template DL_UNITDATA_REQ
23536  * message block.
23537  */
23538 boolean_t
23539 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23540 {
23541 	dl_unitdata_req_t *dlurp;
23542 	pattr_t *pa;
23543 	pattrinfo_t pa_info;
23544 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23545 	uint_t das_len, das_off;
23546 
23547 	ASSERT(dlmp != NULL);
23548 
23549 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23550 	das_len = dlurp->dl_dest_addr_length;
23551 	das_off = dlurp->dl_dest_addr_offset;
23552 
23553 	pa_info.type = PATTR_DSTADDRSAP;
23554 	pa_info.len = sizeof (**das) + das_len - 1;
23555 
23556 	/* create and associate the attribute */
23557 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23558 	if (pa != NULL) {
23559 		ASSERT(*das != NULL);
23560 		(*das)->addr_is_group = 0;
23561 		(*das)->addr_len = (uint8_t)das_len;
23562 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23563 	}
23564 
23565 	return (pa != NULL);
23566 }
23567 
23568 /*
23569  * Create hardware checksum attribute and fill it with the values passed.
23570  */
23571 boolean_t
23572 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23573     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23574 {
23575 	pattr_t *pa;
23576 	pattrinfo_t pa_info;
23577 
23578 	ASSERT(mmd != NULL);
23579 
23580 	pa_info.type = PATTR_HCKSUM;
23581 	pa_info.len = sizeof (pattr_hcksum_t);
23582 
23583 	/* create and associate the attribute */
23584 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23585 	if (pa != NULL) {
23586 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23587 
23588 		hck->hcksum_start_offset = start_offset;
23589 		hck->hcksum_stuff_offset = stuff_offset;
23590 		hck->hcksum_end_offset = end_offset;
23591 		hck->hcksum_flags = flags;
23592 	}
23593 	return (pa != NULL);
23594 }
23595 
23596 /*
23597  * Create zerocopy attribute and fill it with the specified flags
23598  */
23599 boolean_t
23600 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23601 {
23602 	pattr_t *pa;
23603 	pattrinfo_t pa_info;
23604 
23605 	ASSERT(mmd != NULL);
23606 	pa_info.type = PATTR_ZCOPY;
23607 	pa_info.len = sizeof (pattr_zcopy_t);
23608 
23609 	/* create and associate the attribute */
23610 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23611 	if (pa != NULL) {
23612 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23613 
23614 		zcopy->zcopy_flags = flags;
23615 	}
23616 	return (pa != NULL);
23617 }
23618 
23619 /*
23620  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23621  * block chain. We could rewrite to handle arbitrary message block chains but
23622  * that would make the code complicated and slow. Right now there three
23623  * restrictions:
23624  *
23625  *   1. The first message block must contain the complete IP header and
23626  *	at least 1 byte of payload data.
23627  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23628  *	so that we can use a single Multidata message.
23629  *   3. No frag must be distributed over two or more message blocks so
23630  *	that we don't need more than two packet descriptors per frag.
23631  *
23632  * The above restrictions allow us to support userland applications (which
23633  * will send down a single message block) and NFS over UDP (which will
23634  * send down a chain of at most three message blocks).
23635  *
23636  * We also don't use MDT for payloads with less than or equal to
23637  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23638  */
23639 boolean_t
23640 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23641 {
23642 	int	blocks;
23643 	ssize_t	total, missing, size;
23644 
23645 	ASSERT(mp != NULL);
23646 	ASSERT(hdr_len > 0);
23647 
23648 	size = MBLKL(mp) - hdr_len;
23649 	if (size <= 0)
23650 		return (B_FALSE);
23651 
23652 	/* The first mblk contains the header and some payload. */
23653 	blocks = 1;
23654 	total = size;
23655 	size %= len;
23656 	missing = (size == 0) ? 0 : (len - size);
23657 	mp = mp->b_cont;
23658 
23659 	while (mp != NULL) {
23660 		/*
23661 		 * Give up if we encounter a zero length message block.
23662 		 * In practice, this should rarely happen and therefore
23663 		 * not worth the trouble of freeing and re-linking the
23664 		 * mblk from the chain to handle such case.
23665 		 */
23666 		if ((size = MBLKL(mp)) == 0)
23667 			return (B_FALSE);
23668 
23669 		/* Too many payload buffers for a single Multidata message? */
23670 		if (++blocks > MULTIDATA_MAX_PBUFS)
23671 			return (B_FALSE);
23672 
23673 		total += size;
23674 		/* Is a frag distributed over two or more message blocks? */
23675 		if (missing > size)
23676 			return (B_FALSE);
23677 		size -= missing;
23678 
23679 		size %= len;
23680 		missing = (size == 0) ? 0 : (len - size);
23681 
23682 		mp = mp->b_cont;
23683 	}
23684 
23685 	return (total > ip_wput_frag_mdt_min);
23686 }
23687 
23688 /*
23689  * Outbound IPv4 fragmentation routine using MDT.
23690  */
23691 static void
23692 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23693     uint32_t frag_flag, int offset)
23694 {
23695 	ipha_t		*ipha_orig;
23696 	int		i1, ip_data_end;
23697 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23698 	mblk_t		*hdr_mp, *md_mp = NULL;
23699 	unsigned char	*hdr_ptr, *pld_ptr;
23700 	multidata_t	*mmd;
23701 	ip_pdescinfo_t	pdi;
23702 	ill_t		*ill;
23703 	ip_stack_t	*ipst = ire->ire_ipst;
23704 
23705 	ASSERT(DB_TYPE(mp) == M_DATA);
23706 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23707 
23708 	ill = ire_to_ill(ire);
23709 	ASSERT(ill != NULL);
23710 
23711 	ipha_orig = (ipha_t *)mp->b_rptr;
23712 	mp->b_rptr += sizeof (ipha_t);
23713 
23714 	/* Calculate how many packets we will send out */
23715 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23716 	pkts = (i1 + len - 1) / len;
23717 	ASSERT(pkts > 1);
23718 
23719 	/* Allocate a message block which will hold all the IP Headers. */
23720 	wroff = ipst->ips_ip_wroff_extra;
23721 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23722 
23723 	i1 = pkts * hdr_chunk_len;
23724 	/*
23725 	 * Create the header buffer, Multidata and destination address
23726 	 * and SAP attribute that should be associated with it.
23727 	 */
23728 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23729 	    ((hdr_mp->b_wptr += i1),
23730 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23731 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23732 		freemsg(mp);
23733 		if (md_mp == NULL) {
23734 			freemsg(hdr_mp);
23735 		} else {
23736 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23737 			freemsg(md_mp);
23738 		}
23739 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23740 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23741 		return;
23742 	}
23743 	IP_STAT(ipst, ip_frag_mdt_allocd);
23744 
23745 	/*
23746 	 * Add a payload buffer to the Multidata; this operation must not
23747 	 * fail, or otherwise our logic in this routine is broken.  There
23748 	 * is no memory allocation done by the routine, so any returned
23749 	 * failure simply tells us that we've done something wrong.
23750 	 *
23751 	 * A failure tells us that either we're adding the same payload
23752 	 * buffer more than once, or we're trying to add more buffers than
23753 	 * allowed.  None of the above cases should happen, and we panic
23754 	 * because either there's horrible heap corruption, and/or
23755 	 * programming mistake.
23756 	 */
23757 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23758 		goto pbuf_panic;
23759 
23760 	hdr_ptr = hdr_mp->b_rptr;
23761 	pld_ptr = mp->b_rptr;
23762 
23763 	/* Establish the ending byte offset, based on the starting offset. */
23764 	offset <<= 3;
23765 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23766 	    IP_SIMPLE_HDR_LENGTH;
23767 
23768 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23769 
23770 	while (pld_ptr < mp->b_wptr) {
23771 		ipha_t		*ipha;
23772 		uint16_t	offset_and_flags;
23773 		uint16_t	ip_len;
23774 		int		error;
23775 
23776 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23777 		ipha = (ipha_t *)(hdr_ptr + wroff);
23778 		ASSERT(OK_32PTR(ipha));
23779 		*ipha = *ipha_orig;
23780 
23781 		if (ip_data_end - offset > len) {
23782 			offset_and_flags = IPH_MF;
23783 		} else {
23784 			/*
23785 			 * Last frag. Set len to the length of this last piece.
23786 			 */
23787 			len = ip_data_end - offset;
23788 			/* A frag of a frag might have IPH_MF non-zero */
23789 			offset_and_flags =
23790 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23791 			    IPH_MF;
23792 		}
23793 		offset_and_flags |= (uint16_t)(offset >> 3);
23794 		offset_and_flags |= (uint16_t)frag_flag;
23795 		/* Store the offset and flags in the IP header. */
23796 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23797 
23798 		/* Store the length in the IP header. */
23799 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23800 		ipha->ipha_length = htons(ip_len);
23801 
23802 		/*
23803 		 * Set the IP header checksum.  Note that mp is just
23804 		 * the header, so this is easy to pass to ip_csum.
23805 		 */
23806 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23807 
23808 		DTRACE_IP7(send, mblk_t *, md_mp, conn_t *, NULL, void_ip_t *,
23809 		    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *,
23810 		    NULL, int, 0);
23811 
23812 		/*
23813 		 * Record offset and size of header and data of the next packet
23814 		 * in the multidata message.
23815 		 */
23816 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23817 		PDESC_PLD_INIT(&pdi);
23818 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23819 		ASSERT(i1 > 0);
23820 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23821 		if (i1 == len) {
23822 			pld_ptr += len;
23823 		} else {
23824 			i1 = len - i1;
23825 			mp = mp->b_cont;
23826 			ASSERT(mp != NULL);
23827 			ASSERT(MBLKL(mp) >= i1);
23828 			/*
23829 			 * Attach the next payload message block to the
23830 			 * multidata message.
23831 			 */
23832 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23833 				goto pbuf_panic;
23834 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23835 			pld_ptr = mp->b_rptr + i1;
23836 		}
23837 
23838 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23839 		    KM_NOSLEEP)) == NULL) {
23840 			/*
23841 			 * Any failure other than ENOMEM indicates that we
23842 			 * have passed in invalid pdesc info or parameters
23843 			 * to mmd_addpdesc, which must not happen.
23844 			 *
23845 			 * EINVAL is a result of failure on boundary checks
23846 			 * against the pdesc info contents.  It should not
23847 			 * happen, and we panic because either there's
23848 			 * horrible heap corruption, and/or programming
23849 			 * mistake.
23850 			 */
23851 			if (error != ENOMEM) {
23852 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23853 				    "pdesc logic error detected for "
23854 				    "mmd %p pinfo %p (%d)\n",
23855 				    (void *)mmd, (void *)&pdi, error);
23856 				/* NOTREACHED */
23857 			}
23858 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
23859 			/* Free unattached payload message blocks as well */
23860 			md_mp->b_cont = mp->b_cont;
23861 			goto free_mmd;
23862 		}
23863 
23864 		/* Advance fragment offset. */
23865 		offset += len;
23866 
23867 		/* Advance to location for next header in the buffer. */
23868 		hdr_ptr += hdr_chunk_len;
23869 
23870 		/* Did we reach the next payload message block? */
23871 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23872 			mp = mp->b_cont;
23873 			/*
23874 			 * Attach the next message block with payload
23875 			 * data to the multidata message.
23876 			 */
23877 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23878 				goto pbuf_panic;
23879 			pld_ptr = mp->b_rptr;
23880 		}
23881 	}
23882 
23883 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23884 	ASSERT(mp->b_wptr == pld_ptr);
23885 
23886 	/* Update IP statistics */
23887 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
23888 
23889 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
23890 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
23891 
23892 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
23893 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
23894 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
23895 
23896 	if (pkt_type == OB_PKT) {
23897 		ire->ire_ob_pkt_count += pkts;
23898 		if (ire->ire_ipif != NULL)
23899 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23900 	} else {
23901 		/* The type is IB_PKT in the forwarding path. */
23902 		ire->ire_ib_pkt_count += pkts;
23903 		ASSERT(!IRE_IS_LOCAL(ire));
23904 		if (ire->ire_type & IRE_BROADCAST) {
23905 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23906 		} else {
23907 			UPDATE_MIB(ill->ill_ip_mib,
23908 			    ipIfStatsHCOutForwDatagrams, pkts);
23909 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
23910 		}
23911 	}
23912 	ire->ire_last_used_time = lbolt;
23913 	/* Send it down */
23914 	putnext(ire->ire_stq, md_mp);
23915 	return;
23916 
23917 pbuf_panic:
23918 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
23919 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
23920 	    pbuf_idx);
23921 	/* NOTREACHED */
23922 }
23923 
23924 /*
23925  * Outbound IP fragmentation routine.
23926  *
23927  * NOTE : This routine does not ire_refrele the ire that is passed in
23928  * as the argument.
23929  */
23930 static void
23931 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
23932     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst, conn_t *connp)
23933 {
23934 	int		i1;
23935 	mblk_t		*ll_hdr_mp;
23936 	int 		ll_hdr_len;
23937 	int		hdr_len;
23938 	mblk_t		*hdr_mp;
23939 	ipha_t		*ipha;
23940 	int		ip_data_end;
23941 	int		len;
23942 	mblk_t		*mp = mp_orig, *mp1;
23943 	int		offset;
23944 	queue_t		*q;
23945 	uint32_t	v_hlen_tos_len;
23946 	mblk_t		*first_mp;
23947 	boolean_t	mctl_present;
23948 	ill_t		*ill;
23949 	ill_t		*out_ill;
23950 	mblk_t		*xmit_mp;
23951 	mblk_t		*carve_mp;
23952 	ire_t		*ire1 = NULL;
23953 	ire_t		*save_ire = NULL;
23954 	mblk_t  	*next_mp = NULL;
23955 	boolean_t	last_frag = B_FALSE;
23956 	boolean_t	multirt_send = B_FALSE;
23957 	ire_t		*first_ire = NULL;
23958 	irb_t		*irb = NULL;
23959 	mib2_ipIfStatsEntry_t *mibptr = NULL;
23960 
23961 	ill = ire_to_ill(ire);
23962 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
23963 
23964 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
23965 
23966 	if (max_frag == 0) {
23967 		ip1dbg(("ip_wput_frag: ire frag size is 0"
23968 		    " -  dropping packet\n"));
23969 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
23970 		freemsg(mp);
23971 		return;
23972 	}
23973 
23974 	/*
23975 	 * IPsec does not allow hw accelerated packets to be fragmented
23976 	 * This check is made in ip_wput_ipsec_out prior to coming here
23977 	 * via ip_wput_ire_fragmentit.
23978 	 *
23979 	 * If at this point we have an ire whose ARP request has not
23980 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
23981 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
23982 	 * This packet and all fragmentable packets for this ire will
23983 	 * continue to get dropped while ire_nce->nce_state remains in
23984 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
23985 	 * ND_REACHABLE, all subsquent large packets for this ire will
23986 	 * get fragemented and sent out by this function.
23987 	 */
23988 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
23989 		/* If nce_state is ND_INITIAL, trigger ARP query */
23990 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
23991 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
23992 		    " -  dropping packet\n"));
23993 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
23994 		freemsg(mp);
23995 		return;
23996 	}
23997 
23998 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
23999 	    "ip_wput_frag_start:");
24000 
24001 	if (mp->b_datap->db_type == M_CTL) {
24002 		first_mp = mp;
24003 		mp_orig = mp = mp->b_cont;
24004 		mctl_present = B_TRUE;
24005 	} else {
24006 		first_mp = mp;
24007 		mctl_present = B_FALSE;
24008 	}
24009 
24010 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24011 	ipha = (ipha_t *)mp->b_rptr;
24012 
24013 	/*
24014 	 * If the Don't Fragment flag is on, generate an ICMP destination
24015 	 * unreachable, fragmentation needed.
24016 	 */
24017 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24018 	if (offset & IPH_DF) {
24019 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24020 		if (is_system_labeled()) {
24021 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24022 			    ire->ire_max_frag - max_frag, AF_INET);
24023 		}
24024 		/*
24025 		 * Need to compute hdr checksum if called from ip_wput_ire.
24026 		 * Note that ip_rput_forward verifies the checksum before
24027 		 * calling this routine so in that case this is a noop.
24028 		 */
24029 		ipha->ipha_hdr_checksum = 0;
24030 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24031 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24032 		    ipst);
24033 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24034 		    "ip_wput_frag_end:(%S)",
24035 		    "don't fragment");
24036 		return;
24037 	}
24038 	/*
24039 	 * Labeled systems adjust max_frag if they add a label
24040 	 * to send the correct path mtu.  We need the real mtu since we
24041 	 * are fragmenting the packet after label adjustment.
24042 	 */
24043 	if (is_system_labeled())
24044 		max_frag = ire->ire_max_frag;
24045 	if (mctl_present)
24046 		freeb(first_mp);
24047 	/*
24048 	 * Establish the starting offset.  May not be zero if we are fragging
24049 	 * a fragment that is being forwarded.
24050 	 */
24051 	offset = offset & IPH_OFFSET;
24052 
24053 	/* TODO why is this test needed? */
24054 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24055 	if (((max_frag - LENGTH) & ~7) < 8) {
24056 		/* TODO: notify ulp somehow */
24057 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24058 		freemsg(mp);
24059 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24060 		    "ip_wput_frag_end:(%S)",
24061 		    "len < 8");
24062 		return;
24063 	}
24064 
24065 	hdr_len = (V_HLEN & 0xF) << 2;
24066 
24067 	ipha->ipha_hdr_checksum = 0;
24068 
24069 	/*
24070 	 * Establish the number of bytes maximum per frag, after putting
24071 	 * in the header.
24072 	 */
24073 	len = (max_frag - hdr_len) & ~7;
24074 
24075 	/* Check if we can use MDT to send out the frags. */
24076 	ASSERT(!IRE_IS_LOCAL(ire));
24077 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24078 	    ipst->ips_ip_multidata_outbound &&
24079 	    !(ire->ire_flags & RTF_MULTIRT) &&
24080 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24081 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24082 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24083 		ASSERT(ill->ill_mdt_capab != NULL);
24084 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24085 			/*
24086 			 * If MDT has been previously turned off in the past,
24087 			 * and we currently can do MDT (due to IPQoS policy
24088 			 * removal, etc.) then enable it for this interface.
24089 			 */
24090 			ill->ill_mdt_capab->ill_mdt_on = 1;
24091 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24092 			    ill->ill_name));
24093 		}
24094 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24095 		    offset);
24096 		return;
24097 	}
24098 
24099 	/* Get a copy of the header for the trailing frags */
24100 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24101 	if (!hdr_mp) {
24102 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24103 		freemsg(mp);
24104 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24105 		    "ip_wput_frag_end:(%S)",
24106 		    "couldn't copy hdr");
24107 		return;
24108 	}
24109 	if (DB_CRED(mp) != NULL)
24110 		mblk_setcred(hdr_mp, DB_CRED(mp));
24111 
24112 	/* Store the starting offset, with the MoreFrags flag. */
24113 	i1 = offset | IPH_MF | frag_flag;
24114 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24115 
24116 	/* Establish the ending byte offset, based on the starting offset. */
24117 	offset <<= 3;
24118 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24119 
24120 	/* Store the length of the first fragment in the IP header. */
24121 	i1 = len + hdr_len;
24122 	ASSERT(i1 <= IP_MAXPACKET);
24123 	ipha->ipha_length = htons((uint16_t)i1);
24124 
24125 	/*
24126 	 * Compute the IP header checksum for the first frag.  We have to
24127 	 * watch out that we stop at the end of the header.
24128 	 */
24129 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24130 
24131 	/*
24132 	 * Now carve off the first frag.  Note that this will include the
24133 	 * original IP header.
24134 	 */
24135 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24136 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24137 		freeb(hdr_mp);
24138 		freemsg(mp_orig);
24139 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24140 		    "ip_wput_frag_end:(%S)",
24141 		    "couldn't carve first");
24142 		return;
24143 	}
24144 
24145 	/*
24146 	 * Multirouting case. Each fragment is replicated
24147 	 * via all non-condemned RTF_MULTIRT routes
24148 	 * currently resolved.
24149 	 * We ensure that first_ire is the first RTF_MULTIRT
24150 	 * ire in the bucket.
24151 	 */
24152 	if (ire->ire_flags & RTF_MULTIRT) {
24153 		irb = ire->ire_bucket;
24154 		ASSERT(irb != NULL);
24155 
24156 		multirt_send = B_TRUE;
24157 
24158 		/* Make sure we do not omit any multiroute ire. */
24159 		IRB_REFHOLD(irb);
24160 		for (first_ire = irb->irb_ire;
24161 		    first_ire != NULL;
24162 		    first_ire = first_ire->ire_next) {
24163 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24164 			    (first_ire->ire_addr == ire->ire_addr) &&
24165 			    !(first_ire->ire_marks &
24166 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
24167 				break;
24168 		}
24169 
24170 		if (first_ire != NULL) {
24171 			if (first_ire != ire) {
24172 				IRE_REFHOLD(first_ire);
24173 				/*
24174 				 * Do not release the ire passed in
24175 				 * as the argument.
24176 				 */
24177 				ire = first_ire;
24178 			} else {
24179 				first_ire = NULL;
24180 			}
24181 		}
24182 		IRB_REFRELE(irb);
24183 
24184 		/*
24185 		 * Save the first ire; we will need to restore it
24186 		 * for the trailing frags.
24187 		 * We REFHOLD save_ire, as each iterated ire will be
24188 		 * REFRELEd.
24189 		 */
24190 		save_ire = ire;
24191 		IRE_REFHOLD(save_ire);
24192 	}
24193 
24194 	/*
24195 	 * First fragment emission loop.
24196 	 * In most cases, the emission loop below is entered only
24197 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24198 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24199 	 * bucket, and send the fragment through all crossed
24200 	 * RTF_MULTIRT routes.
24201 	 */
24202 	do {
24203 		if (ire->ire_flags & RTF_MULTIRT) {
24204 			/*
24205 			 * We are in a multiple send case, need to get
24206 			 * the next ire and make a copy of the packet.
24207 			 * ire1 holds here the next ire to process in the
24208 			 * bucket. If multirouting is expected,
24209 			 * any non-RTF_MULTIRT ire that has the
24210 			 * right destination address is ignored.
24211 			 *
24212 			 * We have to take into account the MTU of
24213 			 * each walked ire. max_frag is set by the
24214 			 * the caller and generally refers to
24215 			 * the primary ire entry. Here we ensure that
24216 			 * no route with a lower MTU will be used, as
24217 			 * fragments are carved once for all ires,
24218 			 * then replicated.
24219 			 */
24220 			ASSERT(irb != NULL);
24221 			IRB_REFHOLD(irb);
24222 			for (ire1 = ire->ire_next;
24223 			    ire1 != NULL;
24224 			    ire1 = ire1->ire_next) {
24225 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24226 					continue;
24227 				if (ire1->ire_addr != ire->ire_addr)
24228 					continue;
24229 				if (ire1->ire_marks &
24230 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
24231 					continue;
24232 				/*
24233 				 * Ensure we do not exceed the MTU
24234 				 * of the next route.
24235 				 */
24236 				if (ire1->ire_max_frag < max_frag) {
24237 					ip_multirt_bad_mtu(ire1, max_frag);
24238 					continue;
24239 				}
24240 
24241 				/* Got one. */
24242 				IRE_REFHOLD(ire1);
24243 				break;
24244 			}
24245 			IRB_REFRELE(irb);
24246 
24247 			if (ire1 != NULL) {
24248 				next_mp = copyb(mp);
24249 				if ((next_mp == NULL) ||
24250 				    ((mp->b_cont != NULL) &&
24251 				    ((next_mp->b_cont =
24252 				    dupmsg(mp->b_cont)) == NULL))) {
24253 					freemsg(next_mp);
24254 					next_mp = NULL;
24255 					ire_refrele(ire1);
24256 					ire1 = NULL;
24257 				}
24258 			}
24259 
24260 			/* Last multiroute ire; don't loop anymore. */
24261 			if (ire1 == NULL) {
24262 				multirt_send = B_FALSE;
24263 			}
24264 		}
24265 
24266 		ll_hdr_len = 0;
24267 		LOCK_IRE_FP_MP(ire);
24268 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24269 		if (ll_hdr_mp != NULL) {
24270 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24271 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24272 		} else {
24273 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24274 		}
24275 
24276 		/* If there is a transmit header, get a copy for this frag. */
24277 		/*
24278 		 * TODO: should check db_ref before calling ip_carve_mp since
24279 		 * it might give us a dup.
24280 		 */
24281 		if (!ll_hdr_mp) {
24282 			/* No xmit header. */
24283 			xmit_mp = mp;
24284 
24285 		/* We have a link-layer header that can fit in our mblk. */
24286 		} else if (mp->b_datap->db_ref == 1 &&
24287 		    ll_hdr_len != 0 &&
24288 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24289 			/* M_DATA fastpath */
24290 			mp->b_rptr -= ll_hdr_len;
24291 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24292 			xmit_mp = mp;
24293 
24294 		/* Corner case if copyb has failed */
24295 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24296 			UNLOCK_IRE_FP_MP(ire);
24297 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24298 			freeb(hdr_mp);
24299 			freemsg(mp);
24300 			freemsg(mp_orig);
24301 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24302 			    "ip_wput_frag_end:(%S)",
24303 			    "discard");
24304 
24305 			if (multirt_send) {
24306 				ASSERT(ire1);
24307 				ASSERT(next_mp);
24308 
24309 				freemsg(next_mp);
24310 				ire_refrele(ire1);
24311 			}
24312 			if (save_ire != NULL)
24313 				IRE_REFRELE(save_ire);
24314 
24315 			if (first_ire != NULL)
24316 				ire_refrele(first_ire);
24317 			return;
24318 
24319 		/*
24320 		 * Case of res_mp OR the fastpath mp can't fit
24321 		 * in the mblk
24322 		 */
24323 		} else {
24324 			xmit_mp->b_cont = mp;
24325 			if (DB_CRED(mp) != NULL)
24326 				mblk_setcred(xmit_mp, DB_CRED(mp));
24327 			/*
24328 			 * Get priority marking, if any.
24329 			 * We propagate the CoS marking from the
24330 			 * original packet that went to QoS processing
24331 			 * in ip_wput_ire to the newly carved mp.
24332 			 */
24333 			if (DB_TYPE(xmit_mp) == M_DATA)
24334 				xmit_mp->b_band = mp->b_band;
24335 		}
24336 		UNLOCK_IRE_FP_MP(ire);
24337 
24338 		q = ire->ire_stq;
24339 		out_ill = (ill_t *)q->q_ptr;
24340 
24341 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24342 
24343 		DTRACE_PROBE4(ip4__physical__out__start,
24344 		    ill_t *, NULL, ill_t *, out_ill,
24345 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24346 
24347 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24348 		    ipst->ips_ipv4firewall_physical_out,
24349 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24350 
24351 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24352 
24353 		if (xmit_mp != NULL) {
24354 			DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *, NULL,
24355 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
24356 			    ipha_t *, ipha, ip6_t *, NULL, int, 0);
24357 
24358 			ILL_SEND_TX(out_ill, ire, connp, xmit_mp, 0);
24359 
24360 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24361 			UPDATE_MIB(out_ill->ill_ip_mib,
24362 			    ipIfStatsHCOutOctets, i1);
24363 
24364 			if (pkt_type != OB_PKT) {
24365 				/*
24366 				 * Update the packet count and MIB stats
24367 				 * of trailing RTF_MULTIRT ires.
24368 				 */
24369 				UPDATE_OB_PKT_COUNT(ire);
24370 				BUMP_MIB(out_ill->ill_ip_mib,
24371 				    ipIfStatsOutFragReqds);
24372 			}
24373 		}
24374 
24375 		if (multirt_send) {
24376 			/*
24377 			 * We are in a multiple send case; look for
24378 			 * the next ire and re-enter the loop.
24379 			 */
24380 			ASSERT(ire1);
24381 			ASSERT(next_mp);
24382 			/* REFRELE the current ire before looping */
24383 			ire_refrele(ire);
24384 			ire = ire1;
24385 			ire1 = NULL;
24386 			mp = next_mp;
24387 			next_mp = NULL;
24388 		}
24389 	} while (multirt_send);
24390 
24391 	ASSERT(ire1 == NULL);
24392 
24393 	/* Restore the original ire; we need it for the trailing frags */
24394 	if (save_ire != NULL) {
24395 		/* REFRELE the last iterated ire */
24396 		ire_refrele(ire);
24397 		/* save_ire has been REFHOLDed */
24398 		ire = save_ire;
24399 		save_ire = NULL;
24400 		q = ire->ire_stq;
24401 	}
24402 
24403 	if (pkt_type == OB_PKT) {
24404 		UPDATE_OB_PKT_COUNT(ire);
24405 	} else {
24406 		out_ill = (ill_t *)q->q_ptr;
24407 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24408 		UPDATE_IB_PKT_COUNT(ire);
24409 	}
24410 
24411 	/* Advance the offset to the second frag starting point. */
24412 	offset += len;
24413 	/*
24414 	 * Update hdr_len from the copied header - there might be less options
24415 	 * in the later fragments.
24416 	 */
24417 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24418 	/* Loop until done. */
24419 	for (;;) {
24420 		uint16_t	offset_and_flags;
24421 		uint16_t	ip_len;
24422 
24423 		if (ip_data_end - offset > len) {
24424 			/*
24425 			 * Carve off the appropriate amount from the original
24426 			 * datagram.
24427 			 */
24428 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24429 				mp = NULL;
24430 				break;
24431 			}
24432 			/*
24433 			 * More frags after this one.  Get another copy
24434 			 * of the header.
24435 			 */
24436 			if (carve_mp->b_datap->db_ref == 1 &&
24437 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24438 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24439 				/* Inline IP header */
24440 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24441 				    hdr_mp->b_rptr;
24442 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24443 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24444 				mp = carve_mp;
24445 			} else {
24446 				if (!(mp = copyb(hdr_mp))) {
24447 					freemsg(carve_mp);
24448 					break;
24449 				}
24450 				/* Get priority marking, if any. */
24451 				mp->b_band = carve_mp->b_band;
24452 				mp->b_cont = carve_mp;
24453 			}
24454 			ipha = (ipha_t *)mp->b_rptr;
24455 			offset_and_flags = IPH_MF;
24456 		} else {
24457 			/*
24458 			 * Last frag.  Consume the header. Set len to
24459 			 * the length of this last piece.
24460 			 */
24461 			len = ip_data_end - offset;
24462 
24463 			/*
24464 			 * Carve off the appropriate amount from the original
24465 			 * datagram.
24466 			 */
24467 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24468 				mp = NULL;
24469 				break;
24470 			}
24471 			if (carve_mp->b_datap->db_ref == 1 &&
24472 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24473 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24474 				/* Inline IP header */
24475 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24476 				    hdr_mp->b_rptr;
24477 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24478 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24479 				mp = carve_mp;
24480 				freeb(hdr_mp);
24481 				hdr_mp = mp;
24482 			} else {
24483 				mp = hdr_mp;
24484 				/* Get priority marking, if any. */
24485 				mp->b_band = carve_mp->b_band;
24486 				mp->b_cont = carve_mp;
24487 			}
24488 			ipha = (ipha_t *)mp->b_rptr;
24489 			/* A frag of a frag might have IPH_MF non-zero */
24490 			offset_and_flags =
24491 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24492 			    IPH_MF;
24493 		}
24494 		offset_and_flags |= (uint16_t)(offset >> 3);
24495 		offset_and_flags |= (uint16_t)frag_flag;
24496 		/* Store the offset and flags in the IP header. */
24497 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24498 
24499 		/* Store the length in the IP header. */
24500 		ip_len = (uint16_t)(len + hdr_len);
24501 		ipha->ipha_length = htons(ip_len);
24502 
24503 		/*
24504 		 * Set the IP header checksum.	Note that mp is just
24505 		 * the header, so this is easy to pass to ip_csum.
24506 		 */
24507 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24508 
24509 		/* Attach a transmit header, if any, and ship it. */
24510 		if (pkt_type == OB_PKT) {
24511 			UPDATE_OB_PKT_COUNT(ire);
24512 		} else {
24513 			out_ill = (ill_t *)q->q_ptr;
24514 			BUMP_MIB(out_ill->ill_ip_mib,
24515 			    ipIfStatsHCOutForwDatagrams);
24516 			UPDATE_IB_PKT_COUNT(ire);
24517 		}
24518 
24519 		if (ire->ire_flags & RTF_MULTIRT) {
24520 			irb = ire->ire_bucket;
24521 			ASSERT(irb != NULL);
24522 
24523 			multirt_send = B_TRUE;
24524 
24525 			/*
24526 			 * Save the original ire; we will need to restore it
24527 			 * for the tailing frags.
24528 			 */
24529 			save_ire = ire;
24530 			IRE_REFHOLD(save_ire);
24531 		}
24532 		/*
24533 		 * Emission loop for this fragment, similar
24534 		 * to what is done for the first fragment.
24535 		 */
24536 		do {
24537 			if (multirt_send) {
24538 				/*
24539 				 * We are in a multiple send case, need to get
24540 				 * the next ire and make a copy of the packet.
24541 				 */
24542 				ASSERT(irb != NULL);
24543 				IRB_REFHOLD(irb);
24544 				for (ire1 = ire->ire_next;
24545 				    ire1 != NULL;
24546 				    ire1 = ire1->ire_next) {
24547 					if (!(ire1->ire_flags & RTF_MULTIRT))
24548 						continue;
24549 					if (ire1->ire_addr != ire->ire_addr)
24550 						continue;
24551 					if (ire1->ire_marks &
24552 					    (IRE_MARK_CONDEMNED |
24553 					    IRE_MARK_TESTHIDDEN))
24554 						continue;
24555 					/*
24556 					 * Ensure we do not exceed the MTU
24557 					 * of the next route.
24558 					 */
24559 					if (ire1->ire_max_frag < max_frag) {
24560 						ip_multirt_bad_mtu(ire1,
24561 						    max_frag);
24562 						continue;
24563 					}
24564 
24565 					/* Got one. */
24566 					IRE_REFHOLD(ire1);
24567 					break;
24568 				}
24569 				IRB_REFRELE(irb);
24570 
24571 				if (ire1 != NULL) {
24572 					next_mp = copyb(mp);
24573 					if ((next_mp == NULL) ||
24574 					    ((mp->b_cont != NULL) &&
24575 					    ((next_mp->b_cont =
24576 					    dupmsg(mp->b_cont)) == NULL))) {
24577 						freemsg(next_mp);
24578 						next_mp = NULL;
24579 						ire_refrele(ire1);
24580 						ire1 = NULL;
24581 					}
24582 				}
24583 
24584 				/* Last multiroute ire; don't loop anymore. */
24585 				if (ire1 == NULL) {
24586 					multirt_send = B_FALSE;
24587 				}
24588 			}
24589 
24590 			/* Update transmit header */
24591 			ll_hdr_len = 0;
24592 			LOCK_IRE_FP_MP(ire);
24593 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24594 			if (ll_hdr_mp != NULL) {
24595 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24596 				ll_hdr_len = MBLKL(ll_hdr_mp);
24597 			} else {
24598 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24599 			}
24600 
24601 			if (!ll_hdr_mp) {
24602 				xmit_mp = mp;
24603 
24604 			/*
24605 			 * We have link-layer header that can fit in
24606 			 * our mblk.
24607 			 */
24608 			} else if (mp->b_datap->db_ref == 1 &&
24609 			    ll_hdr_len != 0 &&
24610 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24611 				/* M_DATA fastpath */
24612 				mp->b_rptr -= ll_hdr_len;
24613 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24614 				    ll_hdr_len);
24615 				xmit_mp = mp;
24616 
24617 			/*
24618 			 * Case of res_mp OR the fastpath mp can't fit
24619 			 * in the mblk
24620 			 */
24621 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24622 				xmit_mp->b_cont = mp;
24623 				if (DB_CRED(mp) != NULL)
24624 					mblk_setcred(xmit_mp, DB_CRED(mp));
24625 				/* Get priority marking, if any. */
24626 				if (DB_TYPE(xmit_mp) == M_DATA)
24627 					xmit_mp->b_band = mp->b_band;
24628 
24629 			/* Corner case if copyb failed */
24630 			} else {
24631 				/*
24632 				 * Exit both the replication and
24633 				 * fragmentation loops.
24634 				 */
24635 				UNLOCK_IRE_FP_MP(ire);
24636 				goto drop_pkt;
24637 			}
24638 			UNLOCK_IRE_FP_MP(ire);
24639 
24640 			mp1 = mp;
24641 			out_ill = (ill_t *)q->q_ptr;
24642 
24643 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24644 
24645 			DTRACE_PROBE4(ip4__physical__out__start,
24646 			    ill_t *, NULL, ill_t *, out_ill,
24647 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24648 
24649 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24650 			    ipst->ips_ipv4firewall_physical_out,
24651 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24652 
24653 			DTRACE_PROBE1(ip4__physical__out__end,
24654 			    mblk_t *, xmit_mp);
24655 
24656 			if (mp != mp1 && hdr_mp == mp1)
24657 				hdr_mp = mp;
24658 			if (mp != mp1 && mp_orig == mp1)
24659 				mp_orig = mp;
24660 
24661 			if (xmit_mp != NULL) {
24662 				DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *,
24663 				    NULL, void_ip_t *, ipha,
24664 				    __dtrace_ipsr_ill_t *, out_ill, ipha_t *,
24665 				    ipha, ip6_t *, NULL, int, 0);
24666 
24667 				ILL_SEND_TX(out_ill, ire, connp, xmit_mp, 0);
24668 
24669 				BUMP_MIB(out_ill->ill_ip_mib,
24670 				    ipIfStatsHCOutTransmits);
24671 				UPDATE_MIB(out_ill->ill_ip_mib,
24672 				    ipIfStatsHCOutOctets, ip_len);
24673 
24674 				if (pkt_type != OB_PKT) {
24675 					/*
24676 					 * Update the packet count of trailing
24677 					 * RTF_MULTIRT ires.
24678 					 */
24679 					UPDATE_OB_PKT_COUNT(ire);
24680 				}
24681 			}
24682 
24683 			/* All done if we just consumed the hdr_mp. */
24684 			if (mp == hdr_mp) {
24685 				last_frag = B_TRUE;
24686 				BUMP_MIB(out_ill->ill_ip_mib,
24687 				    ipIfStatsOutFragOKs);
24688 			}
24689 
24690 			if (multirt_send) {
24691 				/*
24692 				 * We are in a multiple send case; look for
24693 				 * the next ire and re-enter the loop.
24694 				 */
24695 				ASSERT(ire1);
24696 				ASSERT(next_mp);
24697 				/* REFRELE the current ire before looping */
24698 				ire_refrele(ire);
24699 				ire = ire1;
24700 				ire1 = NULL;
24701 				q = ire->ire_stq;
24702 				mp = next_mp;
24703 				next_mp = NULL;
24704 			}
24705 		} while (multirt_send);
24706 		/*
24707 		 * Restore the original ire; we need it for the
24708 		 * trailing frags
24709 		 */
24710 		if (save_ire != NULL) {
24711 			ASSERT(ire1 == NULL);
24712 			/* REFRELE the last iterated ire */
24713 			ire_refrele(ire);
24714 			/* save_ire has been REFHOLDed */
24715 			ire = save_ire;
24716 			q = ire->ire_stq;
24717 			save_ire = NULL;
24718 		}
24719 
24720 		if (last_frag) {
24721 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24722 			    "ip_wput_frag_end:(%S)",
24723 			    "consumed hdr_mp");
24724 
24725 			if (first_ire != NULL)
24726 				ire_refrele(first_ire);
24727 			return;
24728 		}
24729 		/* Otherwise, advance and loop. */
24730 		offset += len;
24731 	}
24732 
24733 drop_pkt:
24734 	/* Clean up following allocation failure. */
24735 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24736 	freemsg(mp);
24737 	if (mp != hdr_mp)
24738 		freeb(hdr_mp);
24739 	if (mp != mp_orig)
24740 		freemsg(mp_orig);
24741 
24742 	if (save_ire != NULL)
24743 		IRE_REFRELE(save_ire);
24744 	if (first_ire != NULL)
24745 		ire_refrele(first_ire);
24746 
24747 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24748 	    "ip_wput_frag_end:(%S)",
24749 	    "end--alloc failure");
24750 }
24751 
24752 /*
24753  * Copy the header plus those options which have the copy bit set
24754  */
24755 static mblk_t *
24756 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
24757 {
24758 	mblk_t	*mp;
24759 	uchar_t	*up;
24760 
24761 	/*
24762 	 * Quick check if we need to look for options without the copy bit
24763 	 * set
24764 	 */
24765 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
24766 	if (!mp)
24767 		return (mp);
24768 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24769 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24770 		bcopy(rptr, mp->b_rptr, hdr_len);
24771 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24772 		return (mp);
24773 	}
24774 	up  = mp->b_rptr;
24775 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24776 	up += IP_SIMPLE_HDR_LENGTH;
24777 	rptr += IP_SIMPLE_HDR_LENGTH;
24778 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24779 	while (hdr_len > 0) {
24780 		uint32_t optval;
24781 		uint32_t optlen;
24782 
24783 		optval = *rptr;
24784 		if (optval == IPOPT_EOL)
24785 			break;
24786 		if (optval == IPOPT_NOP)
24787 			optlen = 1;
24788 		else
24789 			optlen = rptr[1];
24790 		if (optval & IPOPT_COPY) {
24791 			bcopy(rptr, up, optlen);
24792 			up += optlen;
24793 		}
24794 		rptr += optlen;
24795 		hdr_len -= optlen;
24796 	}
24797 	/*
24798 	 * Make sure that we drop an even number of words by filling
24799 	 * with EOL to the next word boundary.
24800 	 */
24801 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24802 	    hdr_len & 0x3; hdr_len++)
24803 		*up++ = IPOPT_EOL;
24804 	mp->b_wptr = up;
24805 	/* Update header length */
24806 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24807 	return (mp);
24808 }
24809 
24810 /*
24811  * Delivery to local recipients including fanout to multiple recipients.
24812  * Does not do checksumming of UDP/TCP.
24813  * Note: q should be the read side queue for either the ill or conn.
24814  * Note: rq should be the read side q for the lower (ill) stream.
24815  * We don't send packets to IPPF processing, thus the last argument
24816  * to all the fanout calls are B_FALSE.
24817  */
24818 void
24819 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24820     int fanout_flags, zoneid_t zoneid)
24821 {
24822 	uint32_t	protocol;
24823 	mblk_t		*first_mp;
24824 	boolean_t	mctl_present;
24825 	int		ire_type;
24826 #define	rptr	((uchar_t *)ipha)
24827 	ip_stack_t	*ipst = ill->ill_ipst;
24828 
24829 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24830 	    "ip_wput_local_start: q %p", q);
24831 
24832 	if (ire != NULL) {
24833 		ire_type = ire->ire_type;
24834 	} else {
24835 		/*
24836 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24837 		 * packet is not multicast, we can't tell the ire type.
24838 		 */
24839 		ASSERT(CLASSD(ipha->ipha_dst));
24840 		ire_type = IRE_BROADCAST;
24841 	}
24842 
24843 	first_mp = mp;
24844 	if (first_mp->b_datap->db_type == M_CTL) {
24845 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24846 		if (!io->ipsec_out_secure) {
24847 			/*
24848 			 * This ipsec_out_t was allocated in ip_wput
24849 			 * for multicast packets to store the ill_index.
24850 			 * As this is being delivered locally, we don't
24851 			 * need this anymore.
24852 			 */
24853 			mp = first_mp->b_cont;
24854 			freeb(first_mp);
24855 			first_mp = mp;
24856 			mctl_present = B_FALSE;
24857 		} else {
24858 			/*
24859 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24860 			 * security properties for the looped-back packet.
24861 			 */
24862 			mctl_present = B_TRUE;
24863 			mp = first_mp->b_cont;
24864 			ASSERT(mp != NULL);
24865 			ipsec_out_to_in(first_mp);
24866 		}
24867 	} else {
24868 		mctl_present = B_FALSE;
24869 	}
24870 
24871 	DTRACE_PROBE4(ip4__loopback__in__start,
24872 	    ill_t *, ill, ill_t *, NULL,
24873 	    ipha_t *, ipha, mblk_t *, first_mp);
24874 
24875 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
24876 	    ipst->ips_ipv4firewall_loopback_in,
24877 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
24878 
24879 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24880 
24881 	if (first_mp == NULL)
24882 		return;
24883 
24884 	if (ipst->ips_ipobs_enabled) {
24885 		zoneid_t szone, dzone, lookup_zoneid = ALL_ZONES;
24886 		zoneid_t stackzoneid = netstackid_to_zoneid(
24887 		    ipst->ips_netstack->netstack_stackid);
24888 
24889 		dzone = (stackzoneid == GLOBAL_ZONEID) ? zoneid : stackzoneid;
24890 		/*
24891 		 * 127.0.0.1 is special, as we cannot lookup its zoneid by
24892 		 * address.  Restrict the lookup below to the destination zone.
24893 		 */
24894 		if (ipha->ipha_src == ntohl(INADDR_LOOPBACK))
24895 			lookup_zoneid = zoneid;
24896 		szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
24897 		    lookup_zoneid);
24898 		ipobs_hook(mp, IPOBS_HOOK_LOCAL, szone, dzone, ill,
24899 		    IPV4_VERSION, 0, ipst);
24900 	}
24901 
24902 	DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL, void_ip_t *,
24903 	    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *, NULL,
24904 	    int, 1);
24905 
24906 	ipst->ips_loopback_packets++;
24907 
24908 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
24909 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
24910 	if (!IS_SIMPLE_IPH(ipha)) {
24911 		ip_wput_local_options(ipha, ipst);
24912 	}
24913 
24914 	protocol = ipha->ipha_protocol;
24915 	switch (protocol) {
24916 	case IPPROTO_ICMP: {
24917 		ire_t		*ire_zone;
24918 		ilm_t		*ilm;
24919 		mblk_t		*mp1;
24920 		zoneid_t	last_zoneid;
24921 		ilm_walker_t	ilw;
24922 
24923 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
24924 			ASSERT(ire_type == IRE_BROADCAST);
24925 			/*
24926 			 * In the multicast case, applications may have joined
24927 			 * the group from different zones, so we need to deliver
24928 			 * the packet to each of them. Loop through the
24929 			 * multicast memberships structures (ilm) on the receive
24930 			 * ill and send a copy of the packet up each matching
24931 			 * one. However, we don't do this for multicasts sent on
24932 			 * the loopback interface (PHYI_LOOPBACK flag set) as
24933 			 * they must stay in the sender's zone.
24934 			 *
24935 			 * ilm_add_v6() ensures that ilms in the same zone are
24936 			 * contiguous in the ill_ilm list. We use this property
24937 			 * to avoid sending duplicates needed when two
24938 			 * applications in the same zone join the same group on
24939 			 * different logical interfaces: we ignore the ilm if
24940 			 * it's zoneid is the same as the last matching one.
24941 			 * In addition, the sending of the packet for
24942 			 * ire_zoneid is delayed until all of the other ilms
24943 			 * have been exhausted.
24944 			 */
24945 			last_zoneid = -1;
24946 			ilm = ilm_walker_start(&ilw, ill);
24947 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
24948 				if (ipha->ipha_dst != ilm->ilm_addr ||
24949 				    ilm->ilm_zoneid == last_zoneid ||
24950 				    ilm->ilm_zoneid == zoneid ||
24951 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
24952 					continue;
24953 				mp1 = ip_copymsg(first_mp);
24954 				if (mp1 == NULL)
24955 					continue;
24956 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
24957 				    0, 0, mctl_present, B_FALSE, ill,
24958 				    ilm->ilm_zoneid);
24959 				last_zoneid = ilm->ilm_zoneid;
24960 			}
24961 			ilm_walker_finish(&ilw);
24962 			/*
24963 			 * Loopback case: the sending endpoint has
24964 			 * IP_MULTICAST_LOOP disabled, therefore we don't
24965 			 * dispatch the multicast packet to the sending zone.
24966 			 */
24967 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
24968 				freemsg(first_mp);
24969 				return;
24970 			}
24971 		} else if (ire_type == IRE_BROADCAST) {
24972 			/*
24973 			 * In the broadcast case, there may be many zones
24974 			 * which need a copy of the packet delivered to them.
24975 			 * There is one IRE_BROADCAST per broadcast address
24976 			 * and per zone; we walk those using a helper function.
24977 			 * In addition, the sending of the packet for zoneid is
24978 			 * delayed until all of the other ires have been
24979 			 * processed.
24980 			 */
24981 			IRB_REFHOLD(ire->ire_bucket);
24982 			ire_zone = NULL;
24983 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
24984 			    ire)) != NULL) {
24985 				mp1 = ip_copymsg(first_mp);
24986 				if (mp1 == NULL)
24987 					continue;
24988 
24989 				UPDATE_IB_PKT_COUNT(ire_zone);
24990 				ire_zone->ire_last_used_time = lbolt;
24991 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24992 				    mctl_present, B_FALSE, ill,
24993 				    ire_zone->ire_zoneid);
24994 			}
24995 			IRB_REFRELE(ire->ire_bucket);
24996 		}
24997 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
24998 		    0, mctl_present, B_FALSE, ill, zoneid);
24999 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25000 		    "ip_wput_local_end: q %p (%S)",
25001 		    q, "icmp");
25002 		return;
25003 	}
25004 	case IPPROTO_IGMP:
25005 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25006 			/* Bad packet - discarded by igmp_input */
25007 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25008 			    "ip_wput_local_end: q %p (%S)",
25009 			    q, "igmp_input--bad packet");
25010 			if (mctl_present)
25011 				freeb(first_mp);
25012 			return;
25013 		}
25014 		/*
25015 		 * igmp_input() may have returned the pulled up message.
25016 		 * So first_mp and ipha need to be reinitialized.
25017 		 */
25018 		ipha = (ipha_t *)mp->b_rptr;
25019 		if (mctl_present)
25020 			first_mp->b_cont = mp;
25021 		else
25022 			first_mp = mp;
25023 		/* deliver to local raw users */
25024 		break;
25025 	case IPPROTO_ENCAP:
25026 		/*
25027 		 * This case is covered by either ip_fanout_proto, or by
25028 		 * the above security processing for self-tunneled packets.
25029 		 */
25030 		break;
25031 	case IPPROTO_UDP: {
25032 		uint16_t	*up;
25033 		uint32_t	ports;
25034 
25035 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25036 		    UDP_PORTS_OFFSET);
25037 		/* Force a 'valid' checksum. */
25038 		up[3] = 0;
25039 
25040 		ports = *(uint32_t *)up;
25041 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25042 		    (ire_type == IRE_BROADCAST),
25043 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25044 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25045 		    ill, zoneid);
25046 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25047 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25048 		return;
25049 	}
25050 	case IPPROTO_TCP: {
25051 
25052 		/*
25053 		 * For TCP, discard broadcast packets.
25054 		 */
25055 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25056 			freemsg(first_mp);
25057 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25058 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25059 			return;
25060 		}
25061 
25062 		if (mp->b_datap->db_type == M_DATA) {
25063 			/*
25064 			 * M_DATA mblk, so init mblk (chain) for no struio().
25065 			 */
25066 			mblk_t	*mp1 = mp;
25067 
25068 			do {
25069 				mp1->b_datap->db_struioflag = 0;
25070 			} while ((mp1 = mp1->b_cont) != NULL);
25071 		}
25072 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25073 		    <= mp->b_wptr);
25074 		ip_fanout_tcp(q, first_mp, ill, ipha,
25075 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25076 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25077 		    mctl_present, B_FALSE, zoneid);
25078 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25079 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25080 		return;
25081 	}
25082 	case IPPROTO_SCTP:
25083 	{
25084 		uint32_t	ports;
25085 
25086 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25087 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25088 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25089 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25090 		return;
25091 	}
25092 
25093 	default:
25094 		break;
25095 	}
25096 	/*
25097 	 * Find a client for some other protocol.  We give
25098 	 * copies to multiple clients, if more than one is
25099 	 * bound.
25100 	 */
25101 	ip_fanout_proto(q, first_mp, ill, ipha,
25102 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25103 	    mctl_present, B_FALSE, ill, zoneid);
25104 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25105 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25106 #undef	rptr
25107 }
25108 
25109 /*
25110  * Update any source route, record route, or timestamp options.
25111  * Check that we are at end of strict source route.
25112  * The options have been sanity checked by ip_wput_options().
25113  */
25114 static void
25115 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25116 {
25117 	ipoptp_t	opts;
25118 	uchar_t		*opt;
25119 	uint8_t		optval;
25120 	uint8_t		optlen;
25121 	ipaddr_t	dst;
25122 	uint32_t	ts;
25123 	ire_t		*ire;
25124 	timestruc_t	now;
25125 
25126 	ip2dbg(("ip_wput_local_options\n"));
25127 	for (optval = ipoptp_first(&opts, ipha);
25128 	    optval != IPOPT_EOL;
25129 	    optval = ipoptp_next(&opts)) {
25130 		opt = opts.ipoptp_cur;
25131 		optlen = opts.ipoptp_len;
25132 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25133 		switch (optval) {
25134 			uint32_t off;
25135 		case IPOPT_SSRR:
25136 		case IPOPT_LSRR:
25137 			off = opt[IPOPT_OFFSET];
25138 			off--;
25139 			if (optlen < IP_ADDR_LEN ||
25140 			    off > optlen - IP_ADDR_LEN) {
25141 				/* End of source route */
25142 				break;
25143 			}
25144 			/*
25145 			 * This will only happen if two consecutive entries
25146 			 * in the source route contains our address or if
25147 			 * it is a packet with a loose source route which
25148 			 * reaches us before consuming the whole source route
25149 			 */
25150 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25151 			if (optval == IPOPT_SSRR) {
25152 				return;
25153 			}
25154 			/*
25155 			 * Hack: instead of dropping the packet truncate the
25156 			 * source route to what has been used by filling the
25157 			 * rest with IPOPT_NOP.
25158 			 */
25159 			opt[IPOPT_OLEN] = (uint8_t)off;
25160 			while (off < optlen) {
25161 				opt[off++] = IPOPT_NOP;
25162 			}
25163 			break;
25164 		case IPOPT_RR:
25165 			off = opt[IPOPT_OFFSET];
25166 			off--;
25167 			if (optlen < IP_ADDR_LEN ||
25168 			    off > optlen - IP_ADDR_LEN) {
25169 				/* No more room - ignore */
25170 				ip1dbg((
25171 				    "ip_wput_forward_options: end of RR\n"));
25172 				break;
25173 			}
25174 			dst = htonl(INADDR_LOOPBACK);
25175 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25176 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25177 			break;
25178 		case IPOPT_TS:
25179 			/* Insert timestamp if there is romm */
25180 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25181 			case IPOPT_TS_TSONLY:
25182 				off = IPOPT_TS_TIMELEN;
25183 				break;
25184 			case IPOPT_TS_PRESPEC:
25185 			case IPOPT_TS_PRESPEC_RFC791:
25186 				/* Verify that the address matched */
25187 				off = opt[IPOPT_OFFSET] - 1;
25188 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25189 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25190 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25191 				    ipst);
25192 				if (ire == NULL) {
25193 					/* Not for us */
25194 					break;
25195 				}
25196 				ire_refrele(ire);
25197 				/* FALLTHRU */
25198 			case IPOPT_TS_TSANDADDR:
25199 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25200 				break;
25201 			default:
25202 				/*
25203 				 * ip_*put_options should have already
25204 				 * dropped this packet.
25205 				 */
25206 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25207 				    "unknown IT - bug in ip_wput_options?\n");
25208 				return;	/* Keep "lint" happy */
25209 			}
25210 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25211 				/* Increase overflow counter */
25212 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25213 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25214 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25215 				    (off << 4);
25216 				break;
25217 			}
25218 			off = opt[IPOPT_OFFSET] - 1;
25219 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25220 			case IPOPT_TS_PRESPEC:
25221 			case IPOPT_TS_PRESPEC_RFC791:
25222 			case IPOPT_TS_TSANDADDR:
25223 				dst = htonl(INADDR_LOOPBACK);
25224 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25225 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25226 				/* FALLTHRU */
25227 			case IPOPT_TS_TSONLY:
25228 				off = opt[IPOPT_OFFSET] - 1;
25229 				/* Compute # of milliseconds since midnight */
25230 				gethrestime(&now);
25231 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25232 				    now.tv_nsec / (NANOSEC / MILLISEC);
25233 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25234 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25235 				break;
25236 			}
25237 			break;
25238 		}
25239 	}
25240 }
25241 
25242 /*
25243  * Send out a multicast packet on interface ipif.
25244  * The sender does not have an conn.
25245  * Caller verifies that this isn't a PHYI_LOOPBACK.
25246  */
25247 void
25248 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25249 {
25250 	ipha_t	*ipha;
25251 	ire_t	*ire;
25252 	ipaddr_t	dst;
25253 	mblk_t		*first_mp;
25254 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25255 
25256 	/* igmp_sendpkt always allocates a ipsec_out_t */
25257 	ASSERT(mp->b_datap->db_type == M_CTL);
25258 	ASSERT(!ipif->ipif_isv6);
25259 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25260 
25261 	first_mp = mp;
25262 	mp = first_mp->b_cont;
25263 	ASSERT(mp->b_datap->db_type == M_DATA);
25264 	ipha = (ipha_t *)mp->b_rptr;
25265 
25266 	/*
25267 	 * Find an IRE which matches the destination and the outgoing
25268 	 * queue (i.e. the outgoing interface.)
25269 	 */
25270 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25271 		dst = ipif->ipif_pp_dst_addr;
25272 	else
25273 		dst = ipha->ipha_dst;
25274 	/*
25275 	 * The source address has already been initialized by the
25276 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25277 	 * be sufficient rather than MATCH_IRE_IPIF.
25278 	 *
25279 	 * This function is used for sending IGMP packets.  For IPMP,
25280 	 * we sidestep IGMP snooping issues by sending all multicast
25281 	 * traffic on a single interface in the IPMP group.
25282 	 */
25283 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25284 	    MATCH_IRE_ILL, ipst);
25285 	if (!ire) {
25286 		/*
25287 		 * Mark this packet to make it be delivered to
25288 		 * ip_wput_ire after the new ire has been
25289 		 * created.
25290 		 */
25291 		mp->b_prev = NULL;
25292 		mp->b_next = NULL;
25293 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25294 		    zoneid, &zero_info);
25295 		return;
25296 	}
25297 
25298 	/*
25299 	 * Honor the RTF_SETSRC flag; this is the only case
25300 	 * where we force this addr whatever the current src addr is,
25301 	 * because this address is set by igmp_sendpkt(), and
25302 	 * cannot be specified by any user.
25303 	 */
25304 	if (ire->ire_flags & RTF_SETSRC) {
25305 		ipha->ipha_src = ire->ire_src_addr;
25306 	}
25307 
25308 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25309 }
25310 
25311 /*
25312  * NOTE : This function does not ire_refrele the ire argument passed in.
25313  *
25314  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25315  * failure. The nce_fp_mp can vanish any time in the case of
25316  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25317  * the ire_lock to access the nce_fp_mp in this case.
25318  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25319  * prepending a fastpath message IPQoS processing must precede it, we also set
25320  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25321  * (IPQoS might have set the b_band for CoS marking).
25322  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25323  * must follow it so that IPQoS can mark the dl_priority field for CoS
25324  * marking, if needed.
25325  */
25326 static mblk_t *
25327 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc,
25328     uint32_t ill_index, ipha_t **iphap)
25329 {
25330 	uint_t	hlen;
25331 	ipha_t *ipha;
25332 	mblk_t *mp1;
25333 	boolean_t qos_done = B_FALSE;
25334 	uchar_t	*ll_hdr;
25335 	ip_stack_t	*ipst = ire->ire_ipst;
25336 
25337 #define	rptr	((uchar_t *)ipha)
25338 
25339 	ipha = (ipha_t *)mp->b_rptr;
25340 	hlen = 0;
25341 	LOCK_IRE_FP_MP(ire);
25342 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25343 		ASSERT(DB_TYPE(mp1) == M_DATA);
25344 		/* Initiate IPPF processing */
25345 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25346 			UNLOCK_IRE_FP_MP(ire);
25347 			ip_process(proc, &mp, ill_index);
25348 			if (mp == NULL)
25349 				return (NULL);
25350 
25351 			ipha = (ipha_t *)mp->b_rptr;
25352 			LOCK_IRE_FP_MP(ire);
25353 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25354 				qos_done = B_TRUE;
25355 				goto no_fp_mp;
25356 			}
25357 			ASSERT(DB_TYPE(mp1) == M_DATA);
25358 		}
25359 		hlen = MBLKL(mp1);
25360 		/*
25361 		 * Check if we have enough room to prepend fastpath
25362 		 * header
25363 		 */
25364 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25365 			ll_hdr = rptr - hlen;
25366 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25367 			/*
25368 			 * Set the b_rptr to the start of the link layer
25369 			 * header
25370 			 */
25371 			mp->b_rptr = ll_hdr;
25372 			mp1 = mp;
25373 		} else {
25374 			mp1 = copyb(mp1);
25375 			if (mp1 == NULL)
25376 				goto unlock_err;
25377 			mp1->b_band = mp->b_band;
25378 			mp1->b_cont = mp;
25379 			/*
25380 			 * certain system generated traffic may not
25381 			 * have cred/label in ip header block. This
25382 			 * is true even for a labeled system. But for
25383 			 * labeled traffic, inherit the label in the
25384 			 * new header.
25385 			 */
25386 			if (DB_CRED(mp) != NULL)
25387 				mblk_setcred(mp1, DB_CRED(mp));
25388 			/*
25389 			 * XXX disable ICK_VALID and compute checksum
25390 			 * here; can happen if nce_fp_mp changes and
25391 			 * it can't be copied now due to insufficient
25392 			 * space. (unlikely, fp mp can change, but it
25393 			 * does not increase in length)
25394 			 */
25395 		}
25396 		UNLOCK_IRE_FP_MP(ire);
25397 	} else {
25398 no_fp_mp:
25399 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25400 		if (mp1 == NULL) {
25401 unlock_err:
25402 			UNLOCK_IRE_FP_MP(ire);
25403 			freemsg(mp);
25404 			return (NULL);
25405 		}
25406 		UNLOCK_IRE_FP_MP(ire);
25407 		mp1->b_cont = mp;
25408 		/*
25409 		 * certain system generated traffic may not
25410 		 * have cred/label in ip header block. This
25411 		 * is true even for a labeled system. But for
25412 		 * labeled traffic, inherit the label in the
25413 		 * new header.
25414 		 */
25415 		if (DB_CRED(mp) != NULL)
25416 			mblk_setcred(mp1, DB_CRED(mp));
25417 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25418 			ip_process(proc, &mp1, ill_index);
25419 			if (mp1 == NULL)
25420 				return (NULL);
25421 
25422 			if (mp1->b_cont == NULL)
25423 				ipha = NULL;
25424 			else
25425 				ipha = (ipha_t *)mp1->b_cont->b_rptr;
25426 		}
25427 	}
25428 
25429 	*iphap = ipha;
25430 	return (mp1);
25431 #undef rptr
25432 }
25433 
25434 /*
25435  * Finish the outbound IPsec processing for an IPv6 packet. This function
25436  * is called from ipsec_out_process() if the IPsec packet was processed
25437  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25438  * asynchronously.
25439  */
25440 void
25441 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25442     ire_t *ire_arg)
25443 {
25444 	in6_addr_t *v6dstp;
25445 	ire_t *ire;
25446 	mblk_t *mp;
25447 	ip6_t *ip6h1;
25448 	uint_t	ill_index;
25449 	ipsec_out_t *io;
25450 	boolean_t hwaccel;
25451 	uint32_t flags = IP6_NO_IPPOLICY;
25452 	int match_flags;
25453 	zoneid_t zoneid;
25454 	boolean_t ill_need_rele = B_FALSE;
25455 	boolean_t ire_need_rele = B_FALSE;
25456 	ip_stack_t	*ipst;
25457 
25458 	mp = ipsec_mp->b_cont;
25459 	ip6h1 = (ip6_t *)mp->b_rptr;
25460 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25461 	ASSERT(io->ipsec_out_ns != NULL);
25462 	ipst = io->ipsec_out_ns->netstack_ip;
25463 	ill_index = io->ipsec_out_ill_index;
25464 	if (io->ipsec_out_reachable) {
25465 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25466 	}
25467 	hwaccel = io->ipsec_out_accelerated;
25468 	zoneid = io->ipsec_out_zoneid;
25469 	ASSERT(zoneid != ALL_ZONES);
25470 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25471 	/* Multicast addresses should have non-zero ill_index. */
25472 	v6dstp = &ip6h->ip6_dst;
25473 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25474 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25475 
25476 	if (ill == NULL && ill_index != 0) {
25477 		ill = ip_grab_ill(ipsec_mp, ill_index, B_TRUE, ipst);
25478 		/* Failure case frees things for us. */
25479 		if (ill == NULL)
25480 			return;
25481 
25482 		ill_need_rele = B_TRUE;
25483 	}
25484 	ASSERT(mp != NULL);
25485 
25486 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25487 		boolean_t unspec_src;
25488 		ipif_t	*ipif;
25489 
25490 		/*
25491 		 * Use the ill_index to get the right ill.
25492 		 */
25493 		unspec_src = io->ipsec_out_unspec_src;
25494 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25495 		if (ipif == NULL) {
25496 			if (ill_need_rele)
25497 				ill_refrele(ill);
25498 			freemsg(ipsec_mp);
25499 			return;
25500 		}
25501 
25502 		if (ire_arg != NULL) {
25503 			ire = ire_arg;
25504 		} else {
25505 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25506 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25507 			ire_need_rele = B_TRUE;
25508 		}
25509 		if (ire != NULL) {
25510 			ipif_refrele(ipif);
25511 			/*
25512 			 * XXX Do the multicast forwarding now, as the IPsec
25513 			 * processing has been done.
25514 			 */
25515 			goto send;
25516 		}
25517 
25518 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25519 		mp->b_prev = NULL;
25520 		mp->b_next = NULL;
25521 
25522 		/*
25523 		 * If the IPsec packet was processed asynchronously,
25524 		 * drop it now.
25525 		 */
25526 		if (q == NULL) {
25527 			if (ill_need_rele)
25528 				ill_refrele(ill);
25529 			freemsg(ipsec_mp);
25530 			return;
25531 		}
25532 
25533 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, v6dstp, &ip6h->ip6_src,
25534 		    unspec_src, zoneid);
25535 		ipif_refrele(ipif);
25536 	} else {
25537 		if (ire_arg != NULL) {
25538 			ire = ire_arg;
25539 		} else {
25540 			ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL, ipst);
25541 			ire_need_rele = B_TRUE;
25542 		}
25543 		if (ire != NULL)
25544 			goto send;
25545 		/*
25546 		 * ire disappeared underneath.
25547 		 *
25548 		 * What we need to do here is the ip_newroute
25549 		 * logic to get the ire without doing the IPsec
25550 		 * processing. Follow the same old path. But this
25551 		 * time, ip_wput or ire_add_then_send will call us
25552 		 * directly as all the IPsec operations are done.
25553 		 */
25554 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25555 		mp->b_prev = NULL;
25556 		mp->b_next = NULL;
25557 
25558 		/*
25559 		 * If the IPsec packet was processed asynchronously,
25560 		 * drop it now.
25561 		 */
25562 		if (q == NULL) {
25563 			if (ill_need_rele)
25564 				ill_refrele(ill);
25565 			freemsg(ipsec_mp);
25566 			return;
25567 		}
25568 
25569 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25570 		    zoneid, ipst);
25571 	}
25572 	if (ill != NULL && ill_need_rele)
25573 		ill_refrele(ill);
25574 	return;
25575 send:
25576 	if (ill != NULL && ill_need_rele)
25577 		ill_refrele(ill);
25578 
25579 	/* Local delivery */
25580 	if (ire->ire_stq == NULL) {
25581 		ill_t	*out_ill;
25582 		ASSERT(q != NULL);
25583 
25584 		/* PFHooks: LOOPBACK_OUT */
25585 		out_ill = ire_to_ill(ire);
25586 
25587 		/*
25588 		 * DTrace this as ip:::send.  A blocked packet will fire the
25589 		 * send probe, but not the receive probe.
25590 		 */
25591 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25592 		    void_ip_t *, ip6h, __dtrace_ipsr_ill_t *, out_ill,
25593 		    ipha_t *, NULL, ip6_t *, ip6h, int, 1);
25594 
25595 		DTRACE_PROBE4(ip6__loopback__out__start,
25596 		    ill_t *, NULL, ill_t *, out_ill,
25597 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25598 
25599 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25600 		    ipst->ips_ipv6firewall_loopback_out,
25601 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25602 
25603 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25604 
25605 		if (ipsec_mp != NULL) {
25606 			ip_wput_local_v6(RD(q), out_ill,
25607 			    ip6h, ipsec_mp, ire, 0, zoneid);
25608 		}
25609 		if (ire_need_rele)
25610 			ire_refrele(ire);
25611 		return;
25612 	}
25613 	/*
25614 	 * Everything is done. Send it out on the wire.
25615 	 * We force the insertion of a fragment header using the
25616 	 * IPH_FRAG_HDR flag in two cases:
25617 	 * - after reception of an ICMPv6 "packet too big" message
25618 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25619 	 * - for multirouted IPv6 packets, so that the receiver can
25620 	 *   discard duplicates according to their fragment identifier
25621 	 */
25622 	/* XXX fix flow control problems. */
25623 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25624 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25625 		if (hwaccel) {
25626 			/*
25627 			 * hardware acceleration does not handle these
25628 			 * "slow path" cases.
25629 			 */
25630 			/* IPsec KSTATS: should bump bean counter here. */
25631 			if (ire_need_rele)
25632 				ire_refrele(ire);
25633 			freemsg(ipsec_mp);
25634 			return;
25635 		}
25636 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25637 		    (mp->b_cont ? msgdsize(mp) :
25638 		    mp->b_wptr - (uchar_t *)ip6h)) {
25639 			/* IPsec KSTATS: should bump bean counter here. */
25640 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25641 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25642 			    msgdsize(mp)));
25643 			if (ire_need_rele)
25644 				ire_refrele(ire);
25645 			freemsg(ipsec_mp);
25646 			return;
25647 		}
25648 		ASSERT(mp->b_prev == NULL);
25649 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25650 		    ntohs(ip6h->ip6_plen) +
25651 		    IPV6_HDR_LEN, ire->ire_max_frag));
25652 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25653 		    ire->ire_max_frag);
25654 	} else {
25655 		UPDATE_OB_PKT_COUNT(ire);
25656 		ire->ire_last_used_time = lbolt;
25657 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25658 	}
25659 	if (ire_need_rele)
25660 		ire_refrele(ire);
25661 	freeb(ipsec_mp);
25662 }
25663 
25664 void
25665 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25666 {
25667 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25668 	da_ipsec_t *hada;	/* data attributes */
25669 	ill_t *ill = (ill_t *)q->q_ptr;
25670 
25671 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25672 
25673 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25674 		/* IPsec KSTATS: Bump lose counter here! */
25675 		freemsg(mp);
25676 		return;
25677 	}
25678 
25679 	/*
25680 	 * It's an IPsec packet that must be
25681 	 * accelerated by the Provider, and the
25682 	 * outbound ill is IPsec acceleration capable.
25683 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25684 	 * to the ill.
25685 	 * IPsec KSTATS: should bump packet counter here.
25686 	 */
25687 
25688 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25689 	if (hada_mp == NULL) {
25690 		/* IPsec KSTATS: should bump packet counter here. */
25691 		freemsg(mp);
25692 		return;
25693 	}
25694 
25695 	hada_mp->b_datap->db_type = M_CTL;
25696 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25697 	hada_mp->b_cont = mp;
25698 
25699 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25700 	bzero(hada, sizeof (da_ipsec_t));
25701 	hada->da_type = IPHADA_M_CTL;
25702 
25703 	putnext(q, hada_mp);
25704 }
25705 
25706 /*
25707  * Finish the outbound IPsec processing. This function is called from
25708  * ipsec_out_process() if the IPsec packet was processed
25709  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25710  * asynchronously.
25711  */
25712 void
25713 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25714     ire_t *ire_arg)
25715 {
25716 	uint32_t v_hlen_tos_len;
25717 	ipaddr_t	dst;
25718 	ipif_t	*ipif = NULL;
25719 	ire_t *ire;
25720 	ire_t *ire1 = NULL;
25721 	mblk_t *next_mp = NULL;
25722 	uint32_t max_frag;
25723 	boolean_t multirt_send = B_FALSE;
25724 	mblk_t *mp;
25725 	ipha_t *ipha1;
25726 	uint_t	ill_index;
25727 	ipsec_out_t *io;
25728 	int match_flags;
25729 	irb_t *irb = NULL;
25730 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25731 	zoneid_t zoneid;
25732 	ipxmit_state_t	pktxmit_state;
25733 	ip_stack_t	*ipst;
25734 
25735 #ifdef	_BIG_ENDIAN
25736 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25737 #else
25738 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25739 #endif
25740 
25741 	mp = ipsec_mp->b_cont;
25742 	ipha1 = (ipha_t *)mp->b_rptr;
25743 	ASSERT(mp != NULL);
25744 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25745 	dst = ipha->ipha_dst;
25746 
25747 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25748 	ill_index = io->ipsec_out_ill_index;
25749 	zoneid = io->ipsec_out_zoneid;
25750 	ASSERT(zoneid != ALL_ZONES);
25751 	ipst = io->ipsec_out_ns->netstack_ip;
25752 	ASSERT(io->ipsec_out_ns != NULL);
25753 
25754 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25755 	if (ill == NULL && ill_index != 0) {
25756 		ill = ip_grab_ill(ipsec_mp, ill_index, B_FALSE, ipst);
25757 		/* Failure case frees things for us. */
25758 		if (ill == NULL)
25759 			return;
25760 
25761 		ill_need_rele = B_TRUE;
25762 	}
25763 
25764 	if (CLASSD(dst)) {
25765 		boolean_t conn_dontroute;
25766 		/*
25767 		 * Use the ill_index to get the right ipif.
25768 		 */
25769 		conn_dontroute = io->ipsec_out_dontroute;
25770 		if (ill_index == 0)
25771 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25772 		else
25773 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25774 		if (ipif == NULL) {
25775 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25776 			    " multicast\n"));
25777 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25778 			freemsg(ipsec_mp);
25779 			goto done;
25780 		}
25781 		/*
25782 		 * ipha_src has already been intialized with the
25783 		 * value of the ipif in ip_wput. All we need now is
25784 		 * an ire to send this downstream.
25785 		 */
25786 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25787 		    MBLK_GETLABEL(mp), match_flags, ipst);
25788 		if (ire != NULL) {
25789 			ill_t *ill1;
25790 			/*
25791 			 * Do the multicast forwarding now, as the IPsec
25792 			 * processing has been done.
25793 			 */
25794 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25795 			    (ill1 = ire_to_ill(ire))) {
25796 				if (ip_mforward(ill1, ipha, mp)) {
25797 					freemsg(ipsec_mp);
25798 					ip1dbg(("ip_wput_ipsec_out: mforward "
25799 					    "failed\n"));
25800 					ire_refrele(ire);
25801 					goto done;
25802 				}
25803 			}
25804 			goto send;
25805 		}
25806 
25807 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25808 		mp->b_prev = NULL;
25809 		mp->b_next = NULL;
25810 
25811 		/*
25812 		 * If the IPsec packet was processed asynchronously,
25813 		 * drop it now.
25814 		 */
25815 		if (q == NULL) {
25816 			freemsg(ipsec_mp);
25817 			goto done;
25818 		}
25819 
25820 		/*
25821 		 * We may be using a wrong ipif to create the ire.
25822 		 * But it is okay as the source address is assigned
25823 		 * for the packet already. Next outbound packet would
25824 		 * create the IRE with the right IPIF in ip_wput.
25825 		 *
25826 		 * Also handle RTF_MULTIRT routes.
25827 		 */
25828 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25829 		    zoneid, &zero_info);
25830 	} else {
25831 		if (ire_arg != NULL) {
25832 			ire = ire_arg;
25833 			ire_need_rele = B_FALSE;
25834 		} else {
25835 			ire = ire_cache_lookup(dst, zoneid,
25836 			    MBLK_GETLABEL(mp), ipst);
25837 		}
25838 		if (ire != NULL) {
25839 			goto send;
25840 		}
25841 
25842 		/*
25843 		 * ire disappeared underneath.
25844 		 *
25845 		 * What we need to do here is the ip_newroute
25846 		 * logic to get the ire without doing the IPsec
25847 		 * processing. Follow the same old path. But this
25848 		 * time, ip_wput or ire_add_then_put will call us
25849 		 * directly as all the IPsec operations are done.
25850 		 */
25851 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25852 		mp->b_prev = NULL;
25853 		mp->b_next = NULL;
25854 
25855 		/*
25856 		 * If the IPsec packet was processed asynchronously,
25857 		 * drop it now.
25858 		 */
25859 		if (q == NULL) {
25860 			freemsg(ipsec_mp);
25861 			goto done;
25862 		}
25863 
25864 		/*
25865 		 * Since we're going through ip_newroute() again, we
25866 		 * need to make sure we don't:
25867 		 *
25868 		 *	1.) Trigger the ASSERT() with the ipha_ident
25869 		 *	    overloading.
25870 		 *	2.) Redo transport-layer checksumming, since we've
25871 		 *	    already done all that to get this far.
25872 		 *
25873 		 * The easiest way not do either of the above is to set
25874 		 * the ipha_ident field to IP_HDR_INCLUDED.
25875 		 */
25876 		ipha->ipha_ident = IP_HDR_INCLUDED;
25877 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
25878 		    zoneid, ipst);
25879 	}
25880 	goto done;
25881 send:
25882 	if (ire->ire_stq == NULL) {
25883 		ill_t	*out_ill;
25884 		/*
25885 		 * Loopbacks go through ip_wput_local except for one case.
25886 		 * We come here if we generate a icmp_frag_needed message
25887 		 * after IPsec processing is over. When this function calls
25888 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
25889 		 * icmp_frag_needed. The message generated comes back here
25890 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
25891 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
25892 		 * source address as it is usually set in ip_wput_ire. As
25893 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
25894 		 * and we end up here. We can't enter ip_wput_ire once the
25895 		 * IPsec processing is over and hence we need to do it here.
25896 		 */
25897 		ASSERT(q != NULL);
25898 		UPDATE_OB_PKT_COUNT(ire);
25899 		ire->ire_last_used_time = lbolt;
25900 		if (ipha->ipha_src == 0)
25901 			ipha->ipha_src = ire->ire_src_addr;
25902 
25903 		/* PFHooks: LOOPBACK_OUT */
25904 		out_ill = ire_to_ill(ire);
25905 
25906 		/*
25907 		 * DTrace this as ip:::send.  A blocked packet will fire the
25908 		 * send probe, but not the receive probe.
25909 		 */
25910 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25911 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
25912 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
25913 
25914 		DTRACE_PROBE4(ip4__loopback__out__start,
25915 		    ill_t *, NULL, ill_t *, out_ill,
25916 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
25917 
25918 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
25919 		    ipst->ips_ipv4firewall_loopback_out,
25920 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
25921 
25922 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
25923 
25924 		if (ipsec_mp != NULL)
25925 			ip_wput_local(RD(q), out_ill,
25926 			    ipha, ipsec_mp, ire, 0, zoneid);
25927 		if (ire_need_rele)
25928 			ire_refrele(ire);
25929 		goto done;
25930 	}
25931 
25932 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
25933 		/*
25934 		 * We are through with IPsec processing.
25935 		 * Fragment this and send it on the wire.
25936 		 */
25937 		if (io->ipsec_out_accelerated) {
25938 			/*
25939 			 * The packet has been accelerated but must
25940 			 * be fragmented. This should not happen
25941 			 * since AH and ESP must not accelerate
25942 			 * packets that need fragmentation, however
25943 			 * the configuration could have changed
25944 			 * since the AH or ESP processing.
25945 			 * Drop packet.
25946 			 * IPsec KSTATS: bump bean counter here.
25947 			 */
25948 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
25949 			    "fragmented accelerated packet!\n"));
25950 			freemsg(ipsec_mp);
25951 		} else {
25952 			ip_wput_ire_fragmentit(ipsec_mp, ire,
25953 			    zoneid, ipst, NULL);
25954 		}
25955 		if (ire_need_rele)
25956 			ire_refrele(ire);
25957 		goto done;
25958 	}
25959 
25960 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
25961 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
25962 	    (void *)ire->ire_ipif, (void *)ipif));
25963 
25964 	/*
25965 	 * Multiroute the secured packet.
25966 	 */
25967 	if (ire->ire_flags & RTF_MULTIRT) {
25968 		ire_t *first_ire;
25969 		irb = ire->ire_bucket;
25970 		ASSERT(irb != NULL);
25971 		/*
25972 		 * This ire has been looked up as the one that
25973 		 * goes through the given ipif;
25974 		 * make sure we do not omit any other multiroute ire
25975 		 * that may be present in the bucket before this one.
25976 		 */
25977 		IRB_REFHOLD(irb);
25978 		for (first_ire = irb->irb_ire;
25979 		    first_ire != NULL;
25980 		    first_ire = first_ire->ire_next) {
25981 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
25982 			    (first_ire->ire_addr == ire->ire_addr) &&
25983 			    !(first_ire->ire_marks &
25984 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
25985 				break;
25986 		}
25987 
25988 		if ((first_ire != NULL) && (first_ire != ire)) {
25989 			/*
25990 			 * Don't change the ire if the packet must
25991 			 * be fragmented if sent via this new one.
25992 			 */
25993 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
25994 				IRE_REFHOLD(first_ire);
25995 				if (ire_need_rele)
25996 					ire_refrele(ire);
25997 				else
25998 					ire_need_rele = B_TRUE;
25999 				ire = first_ire;
26000 			}
26001 		}
26002 		IRB_REFRELE(irb);
26003 
26004 		multirt_send = B_TRUE;
26005 		max_frag = ire->ire_max_frag;
26006 	}
26007 
26008 	/*
26009 	 * In most cases, the emission loop below is entered only once.
26010 	 * Only in the case where the ire holds the RTF_MULTIRT
26011 	 * flag, we loop to process all RTF_MULTIRT ires in the
26012 	 * bucket, and send the packet through all crossed
26013 	 * RTF_MULTIRT routes.
26014 	 */
26015 	do {
26016 		if (multirt_send) {
26017 			/*
26018 			 * ire1 holds here the next ire to process in the
26019 			 * bucket. If multirouting is expected,
26020 			 * any non-RTF_MULTIRT ire that has the
26021 			 * right destination address is ignored.
26022 			 */
26023 			ASSERT(irb != NULL);
26024 			IRB_REFHOLD(irb);
26025 			for (ire1 = ire->ire_next;
26026 			    ire1 != NULL;
26027 			    ire1 = ire1->ire_next) {
26028 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26029 					continue;
26030 				if (ire1->ire_addr != ire->ire_addr)
26031 					continue;
26032 				if (ire1->ire_marks &
26033 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
26034 					continue;
26035 				/* No loopback here */
26036 				if (ire1->ire_stq == NULL)
26037 					continue;
26038 				/*
26039 				 * Ensure we do not exceed the MTU
26040 				 * of the next route.
26041 				 */
26042 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26043 					ip_multirt_bad_mtu(ire1, max_frag);
26044 					continue;
26045 				}
26046 
26047 				IRE_REFHOLD(ire1);
26048 				break;
26049 			}
26050 			IRB_REFRELE(irb);
26051 			if (ire1 != NULL) {
26052 				/*
26053 				 * We are in a multiple send case, need to
26054 				 * make a copy of the packet.
26055 				 */
26056 				next_mp = copymsg(ipsec_mp);
26057 				if (next_mp == NULL) {
26058 					ire_refrele(ire1);
26059 					ire1 = NULL;
26060 				}
26061 			}
26062 		}
26063 		/*
26064 		 * Everything is done. Send it out on the wire
26065 		 *
26066 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26067 		 * either send it on the wire or, in the case of
26068 		 * HW acceleration, call ipsec_hw_putnext.
26069 		 */
26070 		if (ire->ire_nce &&
26071 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26072 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26073 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26074 			/*
26075 			 * If ire's link-layer is unresolved (this
26076 			 * would only happen if the incomplete ire
26077 			 * was added to cachetable via forwarding path)
26078 			 * don't bother going to ip_xmit_v4. Just drop the
26079 			 * packet.
26080 			 * There is a slight risk here, in that, if we
26081 			 * have the forwarding path create an incomplete
26082 			 * IRE, then until the IRE is completed, any
26083 			 * transmitted IPsec packets will be dropped
26084 			 * instead of being queued waiting for resolution.
26085 			 *
26086 			 * But the likelihood of a forwarding packet and a wput
26087 			 * packet sending to the same dst at the same time
26088 			 * and there not yet be an ARP entry for it is small.
26089 			 * Furthermore, if this actually happens, it might
26090 			 * be likely that wput would generate multiple
26091 			 * packets (and forwarding would also have a train
26092 			 * of packets) for that destination. If this is
26093 			 * the case, some of them would have been dropped
26094 			 * anyway, since ARP only queues a few packets while
26095 			 * waiting for resolution
26096 			 *
26097 			 * NOTE: We should really call ip_xmit_v4,
26098 			 * and let it queue the packet and send the
26099 			 * ARP query and have ARP come back thus:
26100 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26101 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26102 			 * hw accel work. But it's too complex to get
26103 			 * the IPsec hw  acceleration approach to fit
26104 			 * well with ip_xmit_v4 doing ARP without
26105 			 * doing IPsec simplification. For now, we just
26106 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26107 			 * that we can continue with the send on the next
26108 			 * attempt.
26109 			 *
26110 			 * XXX THis should be revisited, when
26111 			 * the IPsec/IP interaction is cleaned up
26112 			 */
26113 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26114 			    " - dropping packet\n"));
26115 			freemsg(ipsec_mp);
26116 			/*
26117 			 * Call ip_xmit_v4() to trigger ARP query
26118 			 * in case the nce_state is ND_INITIAL
26119 			 */
26120 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
26121 			goto drop_pkt;
26122 		}
26123 
26124 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26125 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26126 		    mblk_t *, ipsec_mp);
26127 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26128 		    ipst->ips_ipv4firewall_physical_out, NULL,
26129 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26130 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26131 		if (ipsec_mp == NULL)
26132 			goto drop_pkt;
26133 
26134 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26135 		pktxmit_state = ip_xmit_v4(mp, ire,
26136 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE, NULL);
26137 
26138 		if ((pktxmit_state ==  SEND_FAILED) ||
26139 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26140 
26141 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26142 drop_pkt:
26143 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26144 			    ipIfStatsOutDiscards);
26145 			if (ire_need_rele)
26146 				ire_refrele(ire);
26147 			if (ire1 != NULL) {
26148 				ire_refrele(ire1);
26149 				freemsg(next_mp);
26150 			}
26151 			goto done;
26152 		}
26153 
26154 		freeb(ipsec_mp);
26155 		if (ire_need_rele)
26156 			ire_refrele(ire);
26157 
26158 		if (ire1 != NULL) {
26159 			ire = ire1;
26160 			ire_need_rele = B_TRUE;
26161 			ASSERT(next_mp);
26162 			ipsec_mp = next_mp;
26163 			mp = ipsec_mp->b_cont;
26164 			ire1 = NULL;
26165 			next_mp = NULL;
26166 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26167 		} else {
26168 			multirt_send = B_FALSE;
26169 		}
26170 	} while (multirt_send);
26171 done:
26172 	if (ill != NULL && ill_need_rele)
26173 		ill_refrele(ill);
26174 	if (ipif != NULL)
26175 		ipif_refrele(ipif);
26176 }
26177 
26178 /*
26179  * Get the ill corresponding to the specified ire, and compare its
26180  * capabilities with the protocol and algorithms specified by the
26181  * the SA obtained from ipsec_out. If they match, annotate the
26182  * ipsec_out structure to indicate that the packet needs acceleration.
26183  *
26184  *
26185  * A packet is eligible for outbound hardware acceleration if the
26186  * following conditions are satisfied:
26187  *
26188  * 1. the packet will not be fragmented
26189  * 2. the provider supports the algorithm
26190  * 3. there is no pending control message being exchanged
26191  * 4. snoop is not attached
26192  * 5. the destination address is not a broadcast or multicast address.
26193  *
26194  * Rationale:
26195  *	- Hardware drivers do not support fragmentation with
26196  *	  the current interface.
26197  *	- snoop, multicast, and broadcast may result in exposure of
26198  *	  a cleartext datagram.
26199  * We check all five of these conditions here.
26200  *
26201  * XXX would like to nuke "ire_t *" parameter here; problem is that
26202  * IRE is only way to figure out if a v4 address is a broadcast and
26203  * thus ineligible for acceleration...
26204  */
26205 static void
26206 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26207 {
26208 	ipsec_out_t *io;
26209 	mblk_t *data_mp;
26210 	uint_t plen, overhead;
26211 	ip_stack_t	*ipst;
26212 
26213 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26214 		return;
26215 
26216 	if (ill == NULL)
26217 		return;
26218 	ipst = ill->ill_ipst;
26219 	/*
26220 	 * Destination address is a broadcast or multicast.  Punt.
26221 	 */
26222 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26223 	    IRE_LOCAL)))
26224 		return;
26225 
26226 	data_mp = ipsec_mp->b_cont;
26227 
26228 	if (ill->ill_isv6) {
26229 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26230 
26231 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26232 			return;
26233 
26234 		plen = ip6h->ip6_plen;
26235 	} else {
26236 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26237 
26238 		if (CLASSD(ipha->ipha_dst))
26239 			return;
26240 
26241 		plen = ipha->ipha_length;
26242 	}
26243 	/*
26244 	 * Is there a pending DLPI control message being exchanged
26245 	 * between IP/IPsec and the DLS Provider? If there is, it
26246 	 * could be a SADB update, and the state of the DLS Provider
26247 	 * SADB might not be in sync with the SADB maintained by
26248 	 * IPsec. To avoid dropping packets or using the wrong keying
26249 	 * material, we do not accelerate this packet.
26250 	 */
26251 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26252 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26253 		    "ill_dlpi_pending! don't accelerate packet\n"));
26254 		return;
26255 	}
26256 
26257 	/*
26258 	 * Is the Provider in promiscous mode? If it does, we don't
26259 	 * accelerate the packet since it will bounce back up to the
26260 	 * listeners in the clear.
26261 	 */
26262 	if (ill->ill_promisc_on_phys) {
26263 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26264 		    "ill in promiscous mode, don't accelerate packet\n"));
26265 		return;
26266 	}
26267 
26268 	/*
26269 	 * Will the packet require fragmentation?
26270 	 */
26271 
26272 	/*
26273 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26274 	 * as is used elsewhere.
26275 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26276 	 *	+ 2-byte trailer
26277 	 */
26278 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26279 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26280 
26281 	if ((plen + overhead) > ill->ill_max_mtu)
26282 		return;
26283 
26284 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26285 
26286 	/*
26287 	 * Can the ill accelerate this IPsec protocol and algorithm
26288 	 * specified by the SA?
26289 	 */
26290 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26291 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26292 		return;
26293 	}
26294 
26295 	/*
26296 	 * Tell AH or ESP that the outbound ill is capable of
26297 	 * accelerating this packet.
26298 	 */
26299 	io->ipsec_out_is_capab_ill = B_TRUE;
26300 }
26301 
26302 /*
26303  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26304  *
26305  * If this function returns B_TRUE, the requested SA's have been filled
26306  * into the ipsec_out_*_sa pointers.
26307  *
26308  * If the function returns B_FALSE, the packet has been "consumed", most
26309  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26310  *
26311  * The SA references created by the protocol-specific "select"
26312  * function will be released when the ipsec_mp is freed, thanks to the
26313  * ipsec_out_free destructor -- see spd.c.
26314  */
26315 static boolean_t
26316 ipsec_out_select_sa(mblk_t *ipsec_mp)
26317 {
26318 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26319 	ipsec_out_t *io;
26320 	ipsec_policy_t *pp;
26321 	ipsec_action_t *ap;
26322 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26323 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26324 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26325 
26326 	if (!io->ipsec_out_secure) {
26327 		/*
26328 		 * We came here by mistake.
26329 		 * Don't bother with ipsec processing
26330 		 * We should "discourage" this path in the future.
26331 		 */
26332 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26333 		return (B_FALSE);
26334 	}
26335 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26336 	ASSERT((io->ipsec_out_policy != NULL) ||
26337 	    (io->ipsec_out_act != NULL));
26338 
26339 	ASSERT(io->ipsec_out_failed == B_FALSE);
26340 
26341 	/*
26342 	 * IPsec processing has started.
26343 	 */
26344 	io->ipsec_out_proc_begin = B_TRUE;
26345 	ap = io->ipsec_out_act;
26346 	if (ap == NULL) {
26347 		pp = io->ipsec_out_policy;
26348 		ASSERT(pp != NULL);
26349 		ap = pp->ipsp_act;
26350 		ASSERT(ap != NULL);
26351 	}
26352 
26353 	/*
26354 	 * We have an action.  now, let's select SA's.
26355 	 * (In the future, we can cache this in the conn_t..)
26356 	 */
26357 	if (ap->ipa_want_esp) {
26358 		if (io->ipsec_out_esp_sa == NULL) {
26359 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26360 			    IPPROTO_ESP);
26361 		}
26362 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26363 	}
26364 
26365 	if (ap->ipa_want_ah) {
26366 		if (io->ipsec_out_ah_sa == NULL) {
26367 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26368 			    IPPROTO_AH);
26369 		}
26370 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26371 		/*
26372 		 * The ESP and AH processing order needs to be preserved
26373 		 * when both protocols are required (ESP should be applied
26374 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26375 		 * when both ESP and AH are required, and an AH ACQUIRE
26376 		 * is needed.
26377 		 */
26378 		if (ap->ipa_want_esp && need_ah_acquire)
26379 			need_esp_acquire = B_TRUE;
26380 	}
26381 
26382 	/*
26383 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26384 	 * Release SAs that got referenced, but will not be used until we
26385 	 * acquire _all_ of the SAs we need.
26386 	 */
26387 	if (need_ah_acquire || need_esp_acquire) {
26388 		if (io->ipsec_out_ah_sa != NULL) {
26389 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26390 			io->ipsec_out_ah_sa = NULL;
26391 		}
26392 		if (io->ipsec_out_esp_sa != NULL) {
26393 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26394 			io->ipsec_out_esp_sa = NULL;
26395 		}
26396 
26397 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26398 		return (B_FALSE);
26399 	}
26400 
26401 	return (B_TRUE);
26402 }
26403 
26404 /*
26405  * Process an IPSEC_OUT message and see what you can
26406  * do with it.
26407  * IPQoS Notes:
26408  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26409  * IPsec.
26410  * XXX would like to nuke ire_t.
26411  * XXX ill_index better be "real"
26412  */
26413 void
26414 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26415 {
26416 	ipsec_out_t *io;
26417 	ipsec_policy_t *pp;
26418 	ipsec_action_t *ap;
26419 	ipha_t *ipha;
26420 	ip6_t *ip6h;
26421 	mblk_t *mp;
26422 	ill_t *ill;
26423 	zoneid_t zoneid;
26424 	ipsec_status_t ipsec_rc;
26425 	boolean_t ill_need_rele = B_FALSE;
26426 	ip_stack_t	*ipst;
26427 	ipsec_stack_t	*ipss;
26428 
26429 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26430 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26431 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26432 	ipst = io->ipsec_out_ns->netstack_ip;
26433 	mp = ipsec_mp->b_cont;
26434 
26435 	/*
26436 	 * Initiate IPPF processing. We do it here to account for packets
26437 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26438 	 * We can check for ipsec_out_proc_begin even for such packets, as
26439 	 * they will always be false (asserted below).
26440 	 */
26441 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26442 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26443 		    io->ipsec_out_ill_index : ill_index);
26444 		if (mp == NULL) {
26445 			ip2dbg(("ipsec_out_process: packet dropped "\
26446 			    "during IPPF processing\n"));
26447 			freeb(ipsec_mp);
26448 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26449 			return;
26450 		}
26451 	}
26452 
26453 	if (!io->ipsec_out_secure) {
26454 		/*
26455 		 * We came here by mistake.
26456 		 * Don't bother with ipsec processing
26457 		 * Should "discourage" this path in the future.
26458 		 */
26459 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26460 		goto done;
26461 	}
26462 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26463 	ASSERT((io->ipsec_out_policy != NULL) ||
26464 	    (io->ipsec_out_act != NULL));
26465 	ASSERT(io->ipsec_out_failed == B_FALSE);
26466 
26467 	ipss = ipst->ips_netstack->netstack_ipsec;
26468 	if (!ipsec_loaded(ipss)) {
26469 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26470 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26471 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26472 		} else {
26473 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26474 		}
26475 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26476 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26477 		    &ipss->ipsec_dropper);
26478 		return;
26479 	}
26480 
26481 	/*
26482 	 * IPsec processing has started.
26483 	 */
26484 	io->ipsec_out_proc_begin = B_TRUE;
26485 	ap = io->ipsec_out_act;
26486 	if (ap == NULL) {
26487 		pp = io->ipsec_out_policy;
26488 		ASSERT(pp != NULL);
26489 		ap = pp->ipsp_act;
26490 		ASSERT(ap != NULL);
26491 	}
26492 
26493 	/*
26494 	 * Save the outbound ill index. When the packet comes back
26495 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26496 	 * before sending it the accelerated packet.
26497 	 */
26498 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26499 		ill = ire_to_ill(ire);
26500 		io->ipsec_out_capab_ill_index = ill->ill_phyint->phyint_ifindex;
26501 	}
26502 
26503 	/*
26504 	 * The order of processing is first insert a IP header if needed.
26505 	 * Then insert the ESP header and then the AH header.
26506 	 */
26507 	if ((io->ipsec_out_se_done == B_FALSE) &&
26508 	    (ap->ipa_want_se)) {
26509 		/*
26510 		 * First get the outer IP header before sending
26511 		 * it to ESP.
26512 		 */
26513 		ipha_t *oipha, *iipha;
26514 		mblk_t *outer_mp, *inner_mp;
26515 
26516 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26517 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26518 			    "ipsec_out_process: "
26519 			    "Self-Encapsulation failed: Out of memory\n");
26520 			freemsg(ipsec_mp);
26521 			if (ill != NULL) {
26522 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26523 			} else {
26524 				BUMP_MIB(&ipst->ips_ip_mib,
26525 				    ipIfStatsOutDiscards);
26526 			}
26527 			return;
26528 		}
26529 		inner_mp = ipsec_mp->b_cont;
26530 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26531 		oipha = (ipha_t *)outer_mp->b_rptr;
26532 		iipha = (ipha_t *)inner_mp->b_rptr;
26533 		*oipha = *iipha;
26534 		outer_mp->b_wptr += sizeof (ipha_t);
26535 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26536 		    sizeof (ipha_t));
26537 		oipha->ipha_protocol = IPPROTO_ENCAP;
26538 		oipha->ipha_version_and_hdr_length =
26539 		    IP_SIMPLE_HDR_VERSION;
26540 		oipha->ipha_hdr_checksum = 0;
26541 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26542 		outer_mp->b_cont = inner_mp;
26543 		ipsec_mp->b_cont = outer_mp;
26544 
26545 		io->ipsec_out_se_done = B_TRUE;
26546 		io->ipsec_out_tunnel = B_TRUE;
26547 	}
26548 
26549 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26550 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26551 	    !ipsec_out_select_sa(ipsec_mp))
26552 		return;
26553 
26554 	/*
26555 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26556 	 * to do the heavy lifting.
26557 	 */
26558 	zoneid = io->ipsec_out_zoneid;
26559 	ASSERT(zoneid != ALL_ZONES);
26560 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26561 		ASSERT(io->ipsec_out_esp_sa != NULL);
26562 		io->ipsec_out_esp_done = B_TRUE;
26563 		/*
26564 		 * Note that since hw accel can only apply one transform,
26565 		 * not two, we skip hw accel for ESP if we also have AH
26566 		 * This is an design limitation of the interface
26567 		 * which should be revisited.
26568 		 */
26569 		ASSERT(ire != NULL);
26570 		if (io->ipsec_out_ah_sa == NULL) {
26571 			ill = (ill_t *)ire->ire_stq->q_ptr;
26572 			ipsec_out_is_accelerated(ipsec_mp,
26573 			    io->ipsec_out_esp_sa, ill, ire);
26574 		}
26575 
26576 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26577 		switch (ipsec_rc) {
26578 		case IPSEC_STATUS_SUCCESS:
26579 			break;
26580 		case IPSEC_STATUS_FAILED:
26581 			if (ill != NULL) {
26582 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26583 			} else {
26584 				BUMP_MIB(&ipst->ips_ip_mib,
26585 				    ipIfStatsOutDiscards);
26586 			}
26587 			/* FALLTHRU */
26588 		case IPSEC_STATUS_PENDING:
26589 			return;
26590 		}
26591 	}
26592 
26593 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26594 		ASSERT(io->ipsec_out_ah_sa != NULL);
26595 		io->ipsec_out_ah_done = B_TRUE;
26596 		if (ire == NULL) {
26597 			int idx = io->ipsec_out_capab_ill_index;
26598 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26599 			    NULL, NULL, NULL, NULL, ipst);
26600 			ill_need_rele = B_TRUE;
26601 		} else {
26602 			ill = (ill_t *)ire->ire_stq->q_ptr;
26603 		}
26604 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26605 		    ire);
26606 
26607 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26608 		switch (ipsec_rc) {
26609 		case IPSEC_STATUS_SUCCESS:
26610 			break;
26611 		case IPSEC_STATUS_FAILED:
26612 			if (ill != NULL) {
26613 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26614 			} else {
26615 				BUMP_MIB(&ipst->ips_ip_mib,
26616 				    ipIfStatsOutDiscards);
26617 			}
26618 			/* FALLTHRU */
26619 		case IPSEC_STATUS_PENDING:
26620 			if (ill != NULL && ill_need_rele)
26621 				ill_refrele(ill);
26622 			return;
26623 		}
26624 	}
26625 	/*
26626 	 * We are done with IPsec processing. Send it over the wire.
26627 	 */
26628 done:
26629 	mp = ipsec_mp->b_cont;
26630 	ipha = (ipha_t *)mp->b_rptr;
26631 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26632 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ire->ire_ipif->ipif_ill,
26633 		    ire);
26634 	} else {
26635 		ip6h = (ip6_t *)ipha;
26636 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ire->ire_ipif->ipif_ill,
26637 		    ire);
26638 	}
26639 	if (ill != NULL && ill_need_rele)
26640 		ill_refrele(ill);
26641 }
26642 
26643 /* ARGSUSED */
26644 void
26645 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26646 {
26647 	opt_restart_t	*or;
26648 	int	err;
26649 	conn_t	*connp;
26650 
26651 	ASSERT(CONN_Q(q));
26652 	connp = Q_TO_CONN(q);
26653 
26654 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26655 	or = (opt_restart_t *)first_mp->b_rptr;
26656 	/*
26657 	 * We don't need to pass any credentials here since this is just
26658 	 * a restart. The credentials are passed in when svr4_optcom_req
26659 	 * is called the first time (from ip_wput_nondata).
26660 	 */
26661 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26662 		err = svr4_optcom_req(q, first_mp, NULL,
26663 		    &ip_opt_obj, B_FALSE);
26664 	} else {
26665 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26666 		err = tpi_optcom_req(q, first_mp, NULL,
26667 		    &ip_opt_obj, B_FALSE);
26668 	}
26669 	if (err != EINPROGRESS) {
26670 		/* operation is done */
26671 		CONN_OPER_PENDING_DONE(connp);
26672 	}
26673 }
26674 
26675 /*
26676  * ioctls that go through a down/up sequence may need to wait for the down
26677  * to complete. This involves waiting for the ire and ipif refcnts to go down
26678  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26679  */
26680 /* ARGSUSED */
26681 void
26682 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26683 {
26684 	struct iocblk *iocp;
26685 	mblk_t *mp1;
26686 	ip_ioctl_cmd_t *ipip;
26687 	int err;
26688 	sin_t	*sin;
26689 	struct lifreq *lifr;
26690 	struct ifreq *ifr;
26691 
26692 	iocp = (struct iocblk *)mp->b_rptr;
26693 	ASSERT(ipsq != NULL);
26694 	/* Existence of mp1 verified in ip_wput_nondata */
26695 	mp1 = mp->b_cont->b_cont;
26696 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26697 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26698 		/*
26699 		 * Special case where ipx_current_ipif is not set:
26700 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26701 		 * We are here as were not able to complete the operation in
26702 		 * ipif_set_values because we could not become exclusive on
26703 		 * the new ipsq.
26704 		 */
26705 		ill_t *ill = q->q_ptr;
26706 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26707 	}
26708 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
26709 
26710 	if (ipip->ipi_cmd_type == IF_CMD) {
26711 		/* This a old style SIOC[GS]IF* command */
26712 		ifr = (struct ifreq *)mp1->b_rptr;
26713 		sin = (sin_t *)&ifr->ifr_addr;
26714 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26715 		/* This a new style SIOC[GS]LIF* command */
26716 		lifr = (struct lifreq *)mp1->b_rptr;
26717 		sin = (sin_t *)&lifr->lifr_addr;
26718 	} else {
26719 		sin = NULL;
26720 	}
26721 
26722 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
26723 	    q, mp, ipip, mp1->b_rptr);
26724 
26725 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26726 }
26727 
26728 /*
26729  * ioctl processing
26730  *
26731  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26732  * the ioctl command in the ioctl tables, determines the copyin data size
26733  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26734  *
26735  * ioctl processing then continues when the M_IOCDATA makes its way down to
26736  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26737  * associated 'conn' is refheld till the end of the ioctl and the general
26738  * ioctl processing function ip_process_ioctl() is called to extract the
26739  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26740  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26741  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26742  * is used to extract the ioctl's arguments.
26743  *
26744  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26745  * so goes thru the serialization primitive ipsq_try_enter. Then the
26746  * appropriate function to handle the ioctl is called based on the entry in
26747  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26748  * which also refreleases the 'conn' that was refheld at the start of the
26749  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26750  *
26751  * Many exclusive ioctls go thru an internal down up sequence as part of
26752  * the operation. For example an attempt to change the IP address of an
26753  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26754  * does all the cleanup such as deleting all ires that use this address.
26755  * Then we need to wait till all references to the interface go away.
26756  */
26757 void
26758 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26759 {
26760 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26761 	ip_ioctl_cmd_t *ipip = arg;
26762 	ip_extract_func_t *extract_funcp;
26763 	cmd_info_t ci;
26764 	int err;
26765 	boolean_t entered_ipsq = B_FALSE;
26766 
26767 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26768 
26769 	if (ipip == NULL)
26770 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26771 
26772 	/*
26773 	 * SIOCLIFADDIF needs to go thru a special path since the
26774 	 * ill may not exist yet. This happens in the case of lo0
26775 	 * which is created using this ioctl.
26776 	 */
26777 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26778 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26779 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26780 		return;
26781 	}
26782 
26783 	ci.ci_ipif = NULL;
26784 	if (ipip->ipi_cmd_type == MISC_CMD) {
26785 		/*
26786 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26787 		 */
26788 		if (ipip->ipi_cmd == IF_UNITSEL) {
26789 			/* ioctl comes down the ill */
26790 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26791 			ipif_refhold(ci.ci_ipif);
26792 		}
26793 		err = 0;
26794 		ci.ci_sin = NULL;
26795 		ci.ci_sin6 = NULL;
26796 		ci.ci_lifr = NULL;
26797 	} else {
26798 		switch (ipip->ipi_cmd_type) {
26799 		case IF_CMD:
26800 		case LIF_CMD:
26801 			extract_funcp = ip_extract_lifreq;
26802 			break;
26803 
26804 		case ARP_CMD:
26805 		case XARP_CMD:
26806 			extract_funcp = ip_extract_arpreq;
26807 			break;
26808 
26809 		case TUN_CMD:
26810 			extract_funcp = ip_extract_tunreq;
26811 			break;
26812 
26813 		case MSFILT_CMD:
26814 			extract_funcp = ip_extract_msfilter;
26815 			break;
26816 
26817 		default:
26818 			ASSERT(0);
26819 		}
26820 
26821 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
26822 		if (err != 0) {
26823 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26824 			return;
26825 		}
26826 
26827 		/*
26828 		 * All of the extraction functions return a refheld ipif.
26829 		 */
26830 		ASSERT(ci.ci_ipif != NULL);
26831 	}
26832 
26833 	if (!(ipip->ipi_flags & IPI_WR)) {
26834 		/*
26835 		 * A return value of EINPROGRESS means the ioctl is
26836 		 * either queued and waiting for some reason or has
26837 		 * already completed.
26838 		 */
26839 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26840 		    ci.ci_lifr);
26841 		if (ci.ci_ipif != NULL)
26842 			ipif_refrele(ci.ci_ipif);
26843 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26844 		return;
26845 	}
26846 
26847 	ASSERT(ci.ci_ipif != NULL);
26848 
26849 	/*
26850 	 * If ipsq is non-NULL, we are already being called exclusively.
26851 	 */
26852 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26853 	if (ipsq == NULL) {
26854 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
26855 		    NEW_OP, B_TRUE);
26856 		if (ipsq == NULL) {
26857 			ipif_refrele(ci.ci_ipif);
26858 			return;
26859 		}
26860 		entered_ipsq = B_TRUE;
26861 	}
26862 
26863 	/*
26864 	 * Release the ipif so that ipif_down and friends that wait for
26865 	 * references to go away are not misled about the current ipif_refcnt
26866 	 * values. We are writer so we can access the ipif even after releasing
26867 	 * the ipif.
26868 	 */
26869 	ipif_refrele(ci.ci_ipif);
26870 
26871 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
26872 
26873 	/*
26874 	 * For most set ioctls that come here, this serves as a single point
26875 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
26876 	 * be any new references to the ipif. This helps functions that go
26877 	 * through this path and end up trying to wait for the refcnts
26878 	 * associated with the ipif to go down to zero.  The exception is
26879 	 * SIOCSLIFREMOVEIF, which sets IPIF_CONDEMNED internally after
26880 	 * identifying the right ipif to operate on.
26881 	 */
26882 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
26883 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF)
26884 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
26885 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
26886 
26887 	/*
26888 	 * A return value of EINPROGRESS means the ioctl is
26889 	 * either queued and waiting for some reason or has
26890 	 * already completed.
26891 	 */
26892 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
26893 
26894 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26895 
26896 	if (entered_ipsq)
26897 		ipsq_exit(ipsq);
26898 }
26899 
26900 /*
26901  * Complete the ioctl. Typically ioctls use the mi package and need to
26902  * do mi_copyout/mi_copy_done.
26903  */
26904 void
26905 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
26906 {
26907 	conn_t	*connp = NULL;
26908 
26909 	if (err == EINPROGRESS)
26910 		return;
26911 
26912 	if (CONN_Q(q)) {
26913 		connp = Q_TO_CONN(q);
26914 		ASSERT(connp->conn_ref >= 2);
26915 	}
26916 
26917 	switch (mode) {
26918 	case COPYOUT:
26919 		if (err == 0)
26920 			mi_copyout(q, mp);
26921 		else
26922 			mi_copy_done(q, mp, err);
26923 		break;
26924 
26925 	case NO_COPYOUT:
26926 		mi_copy_done(q, mp, err);
26927 		break;
26928 
26929 	default:
26930 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
26931 		break;
26932 	}
26933 
26934 	/*
26935 	 * The refhold placed at the start of the ioctl is released here.
26936 	 */
26937 	if (connp != NULL)
26938 		CONN_OPER_PENDING_DONE(connp);
26939 
26940 	if (ipsq != NULL)
26941 		ipsq_current_finish(ipsq);
26942 }
26943 
26944 /* Called from ip_wput for all non data messages */
26945 /* ARGSUSED */
26946 void
26947 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26948 {
26949 	mblk_t		*mp1;
26950 	ire_t		*ire, *fake_ire;
26951 	ill_t		*ill;
26952 	struct iocblk	*iocp;
26953 	ip_ioctl_cmd_t	*ipip;
26954 	cred_t		*cr;
26955 	conn_t		*connp;
26956 	int		err;
26957 	nce_t		*nce;
26958 	ipif_t		*ipif;
26959 	ip_stack_t	*ipst;
26960 	char		*proto_str;
26961 
26962 	if (CONN_Q(q)) {
26963 		connp = Q_TO_CONN(q);
26964 		ipst = connp->conn_netstack->netstack_ip;
26965 	} else {
26966 		connp = NULL;
26967 		ipst = ILLQ_TO_IPST(q);
26968 	}
26969 
26970 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
26971 
26972 	switch (DB_TYPE(mp)) {
26973 	case M_IOCTL:
26974 		/*
26975 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
26976 		 * will arrange to copy in associated control structures.
26977 		 */
26978 		ip_sioctl_copyin_setup(q, mp);
26979 		return;
26980 	case M_IOCDATA:
26981 		/*
26982 		 * Ensure that this is associated with one of our trans-
26983 		 * parent ioctls.  If it's not ours, discard it if we're
26984 		 * running as a driver, or pass it on if we're a module.
26985 		 */
26986 		iocp = (struct iocblk *)mp->b_rptr;
26987 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26988 		if (ipip == NULL) {
26989 			if (q->q_next == NULL) {
26990 				goto nak;
26991 			} else {
26992 				putnext(q, mp);
26993 			}
26994 			return;
26995 		}
26996 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
26997 			/*
26998 			 * the ioctl is one we recognise, but is not
26999 			 * consumed by IP as a module, pass M_IOCDATA
27000 			 * for processing downstream, but only for
27001 			 * common Streams ioctls.
27002 			 */
27003 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27004 				putnext(q, mp);
27005 				return;
27006 			} else {
27007 				goto nak;
27008 			}
27009 		}
27010 
27011 		/* IOCTL continuation following copyin or copyout. */
27012 		if (mi_copy_state(q, mp, NULL) == -1) {
27013 			/*
27014 			 * The copy operation failed.  mi_copy_state already
27015 			 * cleaned up, so we're out of here.
27016 			 */
27017 			return;
27018 		}
27019 		/*
27020 		 * If we just completed a copy in, we become writer and
27021 		 * continue processing in ip_sioctl_copyin_done.  If it
27022 		 * was a copy out, we call mi_copyout again.  If there is
27023 		 * nothing more to copy out, it will complete the IOCTL.
27024 		 */
27025 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27026 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27027 				mi_copy_done(q, mp, EPROTO);
27028 				return;
27029 			}
27030 			/*
27031 			 * Check for cases that need more copying.  A return
27032 			 * value of 0 means a second copyin has been started,
27033 			 * so we return; a return value of 1 means no more
27034 			 * copying is needed, so we continue.
27035 			 */
27036 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27037 			    MI_COPY_COUNT(mp) == 1) {
27038 				if (ip_copyin_msfilter(q, mp) == 0)
27039 					return;
27040 			}
27041 			/*
27042 			 * Refhold the conn, till the ioctl completes. This is
27043 			 * needed in case the ioctl ends up in the pending mp
27044 			 * list. Every mp in the ill_pending_mp list and
27045 			 * the ipx_pending_mp must have a refhold on the conn
27046 			 * to resume processing. The refhold is released when
27047 			 * the ioctl completes. (normally or abnormally)
27048 			 * In all cases ip_ioctl_finish is called to finish
27049 			 * the ioctl.
27050 			 */
27051 			if (connp != NULL) {
27052 				/* This is not a reentry */
27053 				ASSERT(ipsq == NULL);
27054 				CONN_INC_REF(connp);
27055 			} else {
27056 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27057 					mi_copy_done(q, mp, EINVAL);
27058 					return;
27059 				}
27060 			}
27061 
27062 			ip_process_ioctl(ipsq, q, mp, ipip);
27063 
27064 		} else {
27065 			mi_copyout(q, mp);
27066 		}
27067 		return;
27068 nak:
27069 		iocp->ioc_error = EINVAL;
27070 		mp->b_datap->db_type = M_IOCNAK;
27071 		iocp->ioc_count = 0;
27072 		qreply(q, mp);
27073 		return;
27074 
27075 	case M_IOCNAK:
27076 		/*
27077 		 * The only way we could get here is if a resolver didn't like
27078 		 * an IOCTL we sent it.	 This shouldn't happen.
27079 		 */
27080 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27081 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27082 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27083 		freemsg(mp);
27084 		return;
27085 	case M_IOCACK:
27086 		/* /dev/ip shouldn't see this */
27087 		if (CONN_Q(q))
27088 			goto nak;
27089 
27090 		/*
27091 		 * Finish socket ioctls passed through to ARP.  We use the
27092 		 * ioc_cmd values we set in ip_sioctl_arp() to decide whether
27093 		 * we need to become writer before calling ip_sioctl_iocack().
27094 		 * Note that qwriter_ip() will release the refhold, and that a
27095 		 * refhold is OK without ILL_CAN_LOOKUP() since we're on the
27096 		 * ill stream.
27097 		 */
27098 		iocp = (struct iocblk *)mp->b_rptr;
27099 		if (iocp->ioc_cmd == AR_ENTRY_SQUERY) {
27100 			ip_sioctl_iocack(NULL, q, mp, NULL);
27101 			return;
27102 		}
27103 
27104 		ASSERT(iocp->ioc_cmd == AR_ENTRY_DELETE ||
27105 		    iocp->ioc_cmd == AR_ENTRY_ADD);
27106 		ill = q->q_ptr;
27107 		ill_refhold(ill);
27108 		qwriter_ip(ill, q, mp, ip_sioctl_iocack, CUR_OP, B_FALSE);
27109 		return;
27110 	case M_FLUSH:
27111 		if (*mp->b_rptr & FLUSHW)
27112 			flushq(q, FLUSHALL);
27113 		if (q->q_next) {
27114 			putnext(q, mp);
27115 			return;
27116 		}
27117 		if (*mp->b_rptr & FLUSHR) {
27118 			*mp->b_rptr &= ~FLUSHW;
27119 			qreply(q, mp);
27120 			return;
27121 		}
27122 		freemsg(mp);
27123 		return;
27124 	case IRE_DB_REQ_TYPE:
27125 		if (connp == NULL) {
27126 			proto_str = "IRE_DB_REQ_TYPE";
27127 			goto protonak;
27128 		}
27129 		/* An Upper Level Protocol wants a copy of an IRE. */
27130 		ip_ire_req(q, mp);
27131 		return;
27132 	case M_CTL:
27133 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27134 			break;
27135 
27136 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27137 		    TUN_HELLO) {
27138 			ASSERT(connp != NULL);
27139 			connp->conn_flags |= IPCL_IPTUN;
27140 			freeb(mp);
27141 			return;
27142 		}
27143 
27144 		/* M_CTL messages are used by ARP to tell us things. */
27145 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27146 			break;
27147 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27148 		case AR_ENTRY_SQUERY:
27149 			ip_wput_ctl(q, mp);
27150 			return;
27151 		case AR_CLIENT_NOTIFY:
27152 			ip_arp_news(q, mp);
27153 			return;
27154 		case AR_DLPIOP_DONE:
27155 			ASSERT(q->q_next != NULL);
27156 			ill = (ill_t *)q->q_ptr;
27157 			/* qwriter_ip releases the refhold */
27158 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27159 			ill_refhold(ill);
27160 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27161 			return;
27162 		case AR_ARP_CLOSING:
27163 			/*
27164 			 * ARP (above us) is closing. If no ARP bringup is
27165 			 * currently pending, ack the message so that ARP
27166 			 * can complete its close. Also mark ill_arp_closing
27167 			 * so that new ARP bringups will fail. If any
27168 			 * ARP bringup is currently in progress, we will
27169 			 * ack this when the current ARP bringup completes.
27170 			 */
27171 			ASSERT(q->q_next != NULL);
27172 			ill = (ill_t *)q->q_ptr;
27173 			mutex_enter(&ill->ill_lock);
27174 			ill->ill_arp_closing = 1;
27175 			if (!ill->ill_arp_bringup_pending) {
27176 				mutex_exit(&ill->ill_lock);
27177 				qreply(q, mp);
27178 			} else {
27179 				mutex_exit(&ill->ill_lock);
27180 				freemsg(mp);
27181 			}
27182 			return;
27183 		case AR_ARP_EXTEND:
27184 			/*
27185 			 * The ARP module above us is capable of duplicate
27186 			 * address detection.  Old ATM drivers will not send
27187 			 * this message.
27188 			 */
27189 			ASSERT(q->q_next != NULL);
27190 			ill = (ill_t *)q->q_ptr;
27191 			ill->ill_arp_extend = B_TRUE;
27192 			freemsg(mp);
27193 			return;
27194 		default:
27195 			break;
27196 		}
27197 		break;
27198 	case M_PROTO:
27199 	case M_PCPROTO:
27200 		/*
27201 		 * The only PROTO messages we expect are copies of option
27202 		 * negotiation acknowledgements, AH and ESP bind requests
27203 		 * are also expected.
27204 		 */
27205 		switch (((union T_primitives *)mp->b_rptr)->type) {
27206 		case O_T_BIND_REQ:
27207 		case T_BIND_REQ: {
27208 			/* Request can get queued in bind */
27209 			if (connp == NULL) {
27210 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27211 				goto protonak;
27212 			}
27213 			/*
27214 			 * The transports except SCTP call ip_bind_{v4,v6}()
27215 			 * directly instead of a a putnext. SCTP doesn't
27216 			 * generate any T_BIND_REQ since it has its own
27217 			 * fanout data structures. However, ESP and AH
27218 			 * come in for regular binds; all other cases are
27219 			 * bind retries.
27220 			 */
27221 			ASSERT(!IPCL_IS_SCTP(connp));
27222 
27223 			/* Don't increment refcnt if this is a re-entry */
27224 			if (ipsq == NULL)
27225 				CONN_INC_REF(connp);
27226 
27227 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27228 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27229 			ASSERT(mp != NULL);
27230 
27231 			ASSERT(!IPCL_IS_TCP(connp));
27232 			ASSERT(!IPCL_IS_UDP(connp));
27233 			ASSERT(!IPCL_IS_RAWIP(connp));
27234 
27235 			/* The case of AH and ESP */
27236 			qreply(q, mp);
27237 			CONN_OPER_PENDING_DONE(connp);
27238 			return;
27239 		}
27240 		case T_SVR4_OPTMGMT_REQ:
27241 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27242 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27243 
27244 			if (connp == NULL) {
27245 				proto_str = "T_SVR4_OPTMGMT_REQ";
27246 				goto protonak;
27247 			}
27248 
27249 			if (!snmpcom_req(q, mp, ip_snmp_set,
27250 			    ip_snmp_get, cr)) {
27251 				/*
27252 				 * Call svr4_optcom_req so that it can
27253 				 * generate the ack. We don't come here
27254 				 * if this operation is being restarted.
27255 				 * ip_restart_optmgmt will drop the conn ref.
27256 				 * In the case of ipsec option after the ipsec
27257 				 * load is complete conn_restart_ipsec_waiter
27258 				 * drops the conn ref.
27259 				 */
27260 				ASSERT(ipsq == NULL);
27261 				CONN_INC_REF(connp);
27262 				if (ip_check_for_ipsec_opt(q, mp))
27263 					return;
27264 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27265 				    B_FALSE);
27266 				if (err != EINPROGRESS) {
27267 					/* Operation is done */
27268 					CONN_OPER_PENDING_DONE(connp);
27269 				}
27270 			}
27271 			return;
27272 		case T_OPTMGMT_REQ:
27273 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27274 			/*
27275 			 * Note: No snmpcom_req support through new
27276 			 * T_OPTMGMT_REQ.
27277 			 * Call tpi_optcom_req so that it can
27278 			 * generate the ack.
27279 			 */
27280 			if (connp == NULL) {
27281 				proto_str = "T_OPTMGMT_REQ";
27282 				goto protonak;
27283 			}
27284 
27285 			ASSERT(ipsq == NULL);
27286 			/*
27287 			 * We don't come here for restart. ip_restart_optmgmt
27288 			 * will drop the conn ref. In the case of ipsec option
27289 			 * after the ipsec load is complete
27290 			 * conn_restart_ipsec_waiter drops the conn ref.
27291 			 */
27292 			CONN_INC_REF(connp);
27293 			if (ip_check_for_ipsec_opt(q, mp))
27294 				return;
27295 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27296 			if (err != EINPROGRESS) {
27297 				/* Operation is done */
27298 				CONN_OPER_PENDING_DONE(connp);
27299 			}
27300 			return;
27301 		case T_UNBIND_REQ:
27302 			if (connp == NULL) {
27303 				proto_str = "T_UNBIND_REQ";
27304 				goto protonak;
27305 			}
27306 			ip_unbind(Q_TO_CONN(q));
27307 			mp = mi_tpi_ok_ack_alloc(mp);
27308 			qreply(q, mp);
27309 			return;
27310 		default:
27311 			/*
27312 			 * Have to drop any DLPI messages coming down from
27313 			 * arp (such as an info_req which would cause ip
27314 			 * to receive an extra info_ack if it was passed
27315 			 * through.
27316 			 */
27317 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27318 			    (int)*(uint_t *)mp->b_rptr));
27319 			freemsg(mp);
27320 			return;
27321 		}
27322 		/* NOTREACHED */
27323 	case IRE_DB_TYPE: {
27324 		nce_t		*nce;
27325 		ill_t		*ill;
27326 		in6_addr_t	gw_addr_v6;
27327 
27328 
27329 		/*
27330 		 * This is a response back from a resolver.  It
27331 		 * consists of a message chain containing:
27332 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27333 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27334 		 * The LL_HDR_MBLK is the DLPI header to use to get
27335 		 * the attached packet, and subsequent ones for the
27336 		 * same destination, transmitted.
27337 		 */
27338 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27339 			break;
27340 		/*
27341 		 * First, check to make sure the resolution succeeded.
27342 		 * If it failed, the second mblk will be empty.
27343 		 * If it is, free the chain, dropping the packet.
27344 		 * (We must ire_delete the ire; that frees the ire mblk)
27345 		 * We're doing this now to support PVCs for ATM; it's
27346 		 * a partial xresolv implementation. When we fully implement
27347 		 * xresolv interfaces, instead of freeing everything here
27348 		 * we'll initiate neighbor discovery.
27349 		 *
27350 		 * For v4 (ARP and other external resolvers) the resolver
27351 		 * frees the message, so no check is needed. This check
27352 		 * is required, though, for a full xresolve implementation.
27353 		 * Including this code here now both shows how external
27354 		 * resolvers can NACK a resolution request using an
27355 		 * existing design that has no specific provisions for NACKs,
27356 		 * and also takes into account that the current non-ARP
27357 		 * external resolver has been coded to use this method of
27358 		 * NACKing for all IPv6 (xresolv) cases,
27359 		 * whether our xresolv implementation is complete or not.
27360 		 *
27361 		 */
27362 		ire = (ire_t *)mp->b_rptr;
27363 		ill = ire_to_ill(ire);
27364 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27365 		if (mp1->b_rptr == mp1->b_wptr) {
27366 			if (ire->ire_ipversion == IPV6_VERSION) {
27367 				/*
27368 				 * XRESOLV interface.
27369 				 */
27370 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27371 				mutex_enter(&ire->ire_lock);
27372 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27373 				mutex_exit(&ire->ire_lock);
27374 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27375 					nce = ndp_lookup_v6(ill, B_FALSE,
27376 					    &ire->ire_addr_v6, B_FALSE);
27377 				} else {
27378 					nce = ndp_lookup_v6(ill, B_FALSE,
27379 					    &gw_addr_v6, B_FALSE);
27380 				}
27381 				if (nce != NULL) {
27382 					nce_resolv_failed(nce);
27383 					ndp_delete(nce);
27384 					NCE_REFRELE(nce);
27385 				}
27386 			}
27387 			mp->b_cont = NULL;
27388 			freemsg(mp1);		/* frees the pkt as well */
27389 			ASSERT(ire->ire_nce == NULL);
27390 			ire_delete((ire_t *)mp->b_rptr);
27391 			return;
27392 		}
27393 
27394 		/*
27395 		 * Split them into IRE_MBLK and pkt and feed it into
27396 		 * ire_add_then_send. Then in ire_add_then_send
27397 		 * the IRE will be added, and then the packet will be
27398 		 * run back through ip_wput. This time it will make
27399 		 * it to the wire.
27400 		 */
27401 		mp->b_cont = NULL;
27402 		mp = mp1->b_cont;		/* now, mp points to pkt */
27403 		mp1->b_cont = NULL;
27404 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27405 		if (ire->ire_ipversion == IPV6_VERSION) {
27406 			/*
27407 			 * XRESOLV interface. Find the nce and put a copy
27408 			 * of the dl_unitdata_req in nce_res_mp
27409 			 */
27410 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27411 			mutex_enter(&ire->ire_lock);
27412 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27413 			mutex_exit(&ire->ire_lock);
27414 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27415 				nce = ndp_lookup_v6(ill, B_FALSE,
27416 				    &ire->ire_addr_v6, B_FALSE);
27417 			} else {
27418 				nce = ndp_lookup_v6(ill, B_FALSE,
27419 				    &gw_addr_v6, B_FALSE);
27420 			}
27421 			if (nce != NULL) {
27422 				/*
27423 				 * We have to protect nce_res_mp here
27424 				 * from being accessed by other threads
27425 				 * while we change the mblk pointer.
27426 				 * Other functions will also lock the nce when
27427 				 * accessing nce_res_mp.
27428 				 *
27429 				 * The reason we change the mblk pointer
27430 				 * here rather than copying the resolved address
27431 				 * into the template is that, unlike with
27432 				 * ethernet, we have no guarantee that the
27433 				 * resolved address length will be
27434 				 * smaller than or equal to the lla length
27435 				 * with which the template was allocated,
27436 				 * (for ethernet, they're equal)
27437 				 * so we have to use the actual resolved
27438 				 * address mblk - which holds the real
27439 				 * dl_unitdata_req with the resolved address.
27440 				 *
27441 				 * Doing this is the same behavior as was
27442 				 * previously used in the v4 ARP case.
27443 				 */
27444 				mutex_enter(&nce->nce_lock);
27445 				if (nce->nce_res_mp != NULL)
27446 					freemsg(nce->nce_res_mp);
27447 				nce->nce_res_mp = mp1;
27448 				mutex_exit(&nce->nce_lock);
27449 				/*
27450 				 * We do a fastpath probe here because
27451 				 * we have resolved the address without
27452 				 * using Neighbor Discovery.
27453 				 * In the non-XRESOLV v6 case, the fastpath
27454 				 * probe is done right after neighbor
27455 				 * discovery completes.
27456 				 */
27457 				if (nce->nce_res_mp != NULL) {
27458 					int res;
27459 					nce_fastpath_list_add(nce);
27460 					res = ill_fastpath_probe(ill,
27461 					    nce->nce_res_mp);
27462 					if (res != 0 && res != EAGAIN)
27463 						nce_fastpath_list_delete(nce);
27464 				}
27465 
27466 				ire_add_then_send(q, ire, mp);
27467 				/*
27468 				 * Now we have to clean out any packets
27469 				 * that may have been queued on the nce
27470 				 * while it was waiting for address resolution
27471 				 * to complete.
27472 				 */
27473 				mutex_enter(&nce->nce_lock);
27474 				mp1 = nce->nce_qd_mp;
27475 				nce->nce_qd_mp = NULL;
27476 				mutex_exit(&nce->nce_lock);
27477 				while (mp1 != NULL) {
27478 					mblk_t *nxt_mp;
27479 					queue_t *fwdq = NULL;
27480 					ill_t   *inbound_ill;
27481 					uint_t ifindex;
27482 
27483 					nxt_mp = mp1->b_next;
27484 					mp1->b_next = NULL;
27485 					/*
27486 					 * Retrieve ifindex stored in
27487 					 * ip_rput_data_v6()
27488 					 */
27489 					ifindex =
27490 					    (uint_t)(uintptr_t)mp1->b_prev;
27491 					inbound_ill =
27492 					    ill_lookup_on_ifindex(ifindex,
27493 					    B_TRUE, NULL, NULL, NULL,
27494 					    NULL, ipst);
27495 					mp1->b_prev = NULL;
27496 					if (inbound_ill != NULL)
27497 						fwdq = inbound_ill->ill_rq;
27498 
27499 					if (fwdq != NULL) {
27500 						put(fwdq, mp1);
27501 						ill_refrele(inbound_ill);
27502 					} else
27503 						put(WR(ill->ill_rq), mp1);
27504 					mp1 = nxt_mp;
27505 				}
27506 				NCE_REFRELE(nce);
27507 			} else {	/* nce is NULL; clean up */
27508 				ire_delete(ire);
27509 				freemsg(mp);
27510 				freemsg(mp1);
27511 				return;
27512 			}
27513 		} else {
27514 			nce_t *arpce;
27515 			/*
27516 			 * Link layer resolution succeeded. Recompute the
27517 			 * ire_nce.
27518 			 */
27519 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27520 			if ((arpce = ndp_lookup_v4(ill,
27521 			    (ire->ire_gateway_addr != INADDR_ANY ?
27522 			    &ire->ire_gateway_addr : &ire->ire_addr),
27523 			    B_FALSE)) == NULL) {
27524 				freeb(ire->ire_mp);
27525 				freeb(mp1);
27526 				freemsg(mp);
27527 				return;
27528 			}
27529 			mutex_enter(&arpce->nce_lock);
27530 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27531 			if (arpce->nce_state == ND_REACHABLE) {
27532 				/*
27533 				 * Someone resolved this before us;
27534 				 * cleanup the res_mp. Since ire has
27535 				 * not been added yet, the call to ire_add_v4
27536 				 * from ire_add_then_send (when a dup is
27537 				 * detected) will clean up the ire.
27538 				 */
27539 				freeb(mp1);
27540 			} else {
27541 				ASSERT(arpce->nce_res_mp == NULL);
27542 				arpce->nce_res_mp = mp1;
27543 				arpce->nce_state = ND_REACHABLE;
27544 			}
27545 			mutex_exit(&arpce->nce_lock);
27546 			if (ire->ire_marks & IRE_MARK_NOADD) {
27547 				/*
27548 				 * this ire will not be added to the ire
27549 				 * cache table, so we can set the ire_nce
27550 				 * here, as there are no atomicity constraints.
27551 				 */
27552 				ire->ire_nce = arpce;
27553 				/*
27554 				 * We are associating this nce with the ire
27555 				 * so change the nce ref taken in
27556 				 * ndp_lookup_v4() from
27557 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27558 				 */
27559 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27560 			} else {
27561 				NCE_REFRELE(arpce);
27562 			}
27563 			ire_add_then_send(q, ire, mp);
27564 		}
27565 		return;	/* All is well, the packet has been sent. */
27566 	}
27567 	case IRE_ARPRESOLVE_TYPE: {
27568 
27569 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27570 			break;
27571 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27572 		mp->b_cont = NULL;
27573 		/*
27574 		 * First, check to make sure the resolution succeeded.
27575 		 * If it failed, the second mblk will be empty.
27576 		 */
27577 		if (mp1->b_rptr == mp1->b_wptr) {
27578 			/* cleanup  the incomplete ire, free queued packets */
27579 			freemsg(mp); /* fake ire */
27580 			freeb(mp1);  /* dl_unitdata response */
27581 			return;
27582 		}
27583 
27584 		/*
27585 		 * Update any incomplete nce_t found. We search the ctable
27586 		 * and find the nce from the ire->ire_nce because we need
27587 		 * to pass the ire to ip_xmit_v4 later, and can find both
27588 		 * ire and nce in one lookup.
27589 		 */
27590 		fake_ire = (ire_t *)mp->b_rptr;
27591 
27592 		/*
27593 		 * By the time we come back here from ARP the logical outgoing
27594 		 * interface of the incomplete ire we added in ire_forward()
27595 		 * could have disappeared, causing the incomplete ire to also
27596 		 * disappear.  So we need to retreive the proper ipif for the
27597 		 * ire before looking in ctable.  In the case of IPMP, the
27598 		 * ipif may be on the IPMP ill, so look it up based on the
27599 		 * ire_ipif_ifindex we stashed back in ire_init_common().
27600 		 * Then, we can verify that ire_ipif_seqid still exists.
27601 		 */
27602 		ill = ill_lookup_on_ifindex(fake_ire->ire_ipif_ifindex, B_FALSE,
27603 		    NULL, NULL, NULL, NULL, ipst);
27604 		if (ill == NULL) {
27605 			ip1dbg(("ill for incomplete ire vanished\n"));
27606 			freemsg(mp); /* fake ire */
27607 			freeb(mp1);  /* dl_unitdata response */
27608 			return;
27609 		}
27610 
27611 		/* Get the outgoing ipif */
27612 		mutex_enter(&ill->ill_lock);
27613 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27614 		if (ipif == NULL) {
27615 			mutex_exit(&ill->ill_lock);
27616 			ill_refrele(ill);
27617 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27618 			freemsg(mp); /* fake_ire */
27619 			freeb(mp1);  /* dl_unitdata response */
27620 			return;
27621 		}
27622 
27623 		ipif_refhold_locked(ipif);
27624 		mutex_exit(&ill->ill_lock);
27625 		ill_refrele(ill);
27626 		ire = ire_arpresolve_lookup(fake_ire->ire_addr,
27627 		    fake_ire->ire_gateway_addr, ipif, fake_ire->ire_zoneid,
27628 		    ipst, ((ill_t *)q->q_ptr)->ill_wq);
27629 		ipif_refrele(ipif);
27630 		if (ire == NULL) {
27631 			/*
27632 			 * no ire was found; check if there is an nce
27633 			 * for this lookup; if it has no ire's pointing at it
27634 			 * cleanup.
27635 			 */
27636 			if ((nce = ndp_lookup_v4(q->q_ptr,
27637 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27638 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27639 			    B_FALSE)) != NULL) {
27640 				/*
27641 				 * cleanup:
27642 				 * We check for refcnt 2 (one for the nce
27643 				 * hash list + 1 for the ref taken by
27644 				 * ndp_lookup_v4) to check that there are
27645 				 * no ire's pointing at the nce.
27646 				 */
27647 				if (nce->nce_refcnt == 2)
27648 					ndp_delete(nce);
27649 				NCE_REFRELE(nce);
27650 			}
27651 			freeb(mp1);  /* dl_unitdata response */
27652 			freemsg(mp); /* fake ire */
27653 			return;
27654 		}
27655 
27656 		nce = ire->ire_nce;
27657 		DTRACE_PROBE2(ire__arpresolve__type,
27658 		    ire_t *, ire, nce_t *, nce);
27659 		ASSERT(nce->nce_state != ND_INITIAL);
27660 		mutex_enter(&nce->nce_lock);
27661 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27662 		if (nce->nce_state == ND_REACHABLE) {
27663 			/*
27664 			 * Someone resolved this before us;
27665 			 * our response is not needed any more.
27666 			 */
27667 			mutex_exit(&nce->nce_lock);
27668 			freeb(mp1);  /* dl_unitdata response */
27669 		} else {
27670 			ASSERT(nce->nce_res_mp == NULL);
27671 			nce->nce_res_mp = mp1;
27672 			nce->nce_state = ND_REACHABLE;
27673 			mutex_exit(&nce->nce_lock);
27674 			nce_fastpath(nce);
27675 		}
27676 		/*
27677 		 * The cached nce_t has been updated to be reachable;
27678 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27679 		 */
27680 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27681 		freemsg(mp);
27682 		/*
27683 		 * send out queued packets.
27684 		 */
27685 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
27686 
27687 		IRE_REFRELE(ire);
27688 		return;
27689 	}
27690 	default:
27691 		break;
27692 	}
27693 	if (q->q_next) {
27694 		putnext(q, mp);
27695 	} else
27696 		freemsg(mp);
27697 	return;
27698 
27699 protonak:
27700 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27701 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27702 		qreply(q, mp);
27703 }
27704 
27705 /*
27706  * Process IP options in an outbound packet.  Modify the destination if there
27707  * is a source route option.
27708  * Returns non-zero if something fails in which case an ICMP error has been
27709  * sent and mp freed.
27710  */
27711 static int
27712 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27713     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27714 {
27715 	ipoptp_t	opts;
27716 	uchar_t		*opt;
27717 	uint8_t		optval;
27718 	uint8_t		optlen;
27719 	ipaddr_t	dst;
27720 	intptr_t	code = 0;
27721 	mblk_t		*mp;
27722 	ire_t		*ire = NULL;
27723 
27724 	ip2dbg(("ip_wput_options\n"));
27725 	mp = ipsec_mp;
27726 	if (mctl_present) {
27727 		mp = ipsec_mp->b_cont;
27728 	}
27729 
27730 	dst = ipha->ipha_dst;
27731 	for (optval = ipoptp_first(&opts, ipha);
27732 	    optval != IPOPT_EOL;
27733 	    optval = ipoptp_next(&opts)) {
27734 		opt = opts.ipoptp_cur;
27735 		optlen = opts.ipoptp_len;
27736 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27737 		    optval, optlen));
27738 		switch (optval) {
27739 			uint32_t off;
27740 		case IPOPT_SSRR:
27741 		case IPOPT_LSRR:
27742 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27743 				ip1dbg((
27744 				    "ip_wput_options: bad option offset\n"));
27745 				code = (char *)&opt[IPOPT_OLEN] -
27746 				    (char *)ipha;
27747 				goto param_prob;
27748 			}
27749 			off = opt[IPOPT_OFFSET];
27750 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27751 			    ntohl(dst)));
27752 			/*
27753 			 * For strict: verify that dst is directly
27754 			 * reachable.
27755 			 */
27756 			if (optval == IPOPT_SSRR) {
27757 				ire = ire_ftable_lookup(dst, 0, 0,
27758 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27759 				    MBLK_GETLABEL(mp),
27760 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27761 				if (ire == NULL) {
27762 					ip1dbg(("ip_wput_options: SSRR not"
27763 					    " directly reachable: 0x%x\n",
27764 					    ntohl(dst)));
27765 					goto bad_src_route;
27766 				}
27767 				ire_refrele(ire);
27768 			}
27769 			break;
27770 		case IPOPT_RR:
27771 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27772 				ip1dbg((
27773 				    "ip_wput_options: bad option offset\n"));
27774 				code = (char *)&opt[IPOPT_OLEN] -
27775 				    (char *)ipha;
27776 				goto param_prob;
27777 			}
27778 			break;
27779 		case IPOPT_TS:
27780 			/*
27781 			 * Verify that length >=5 and that there is either
27782 			 * room for another timestamp or that the overflow
27783 			 * counter is not maxed out.
27784 			 */
27785 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27786 			if (optlen < IPOPT_MINLEN_IT) {
27787 				goto param_prob;
27788 			}
27789 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27790 				ip1dbg((
27791 				    "ip_wput_options: bad option offset\n"));
27792 				code = (char *)&opt[IPOPT_OFFSET] -
27793 				    (char *)ipha;
27794 				goto param_prob;
27795 			}
27796 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27797 			case IPOPT_TS_TSONLY:
27798 				off = IPOPT_TS_TIMELEN;
27799 				break;
27800 			case IPOPT_TS_TSANDADDR:
27801 			case IPOPT_TS_PRESPEC:
27802 			case IPOPT_TS_PRESPEC_RFC791:
27803 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27804 				break;
27805 			default:
27806 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27807 				    (char *)ipha;
27808 				goto param_prob;
27809 			}
27810 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27811 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27812 				/*
27813 				 * No room and the overflow counter is 15
27814 				 * already.
27815 				 */
27816 				goto param_prob;
27817 			}
27818 			break;
27819 		}
27820 	}
27821 
27822 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27823 		return (0);
27824 
27825 	ip1dbg(("ip_wput_options: error processing IP options."));
27826 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27827 
27828 param_prob:
27829 	/*
27830 	 * Since ip_wput() isn't close to finished, we fill
27831 	 * in enough of the header for credible error reporting.
27832 	 */
27833 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27834 		/* Failed */
27835 		freemsg(ipsec_mp);
27836 		return (-1);
27837 	}
27838 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
27839 	return (-1);
27840 
27841 bad_src_route:
27842 	/*
27843 	 * Since ip_wput() isn't close to finished, we fill
27844 	 * in enough of the header for credible error reporting.
27845 	 */
27846 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27847 		/* Failed */
27848 		freemsg(ipsec_mp);
27849 		return (-1);
27850 	}
27851 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
27852 	return (-1);
27853 }
27854 
27855 /*
27856  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
27857  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
27858  * thru /etc/system.
27859  */
27860 #define	CONN_MAXDRAINCNT	64
27861 
27862 static void
27863 conn_drain_init(ip_stack_t *ipst)
27864 {
27865 	int i;
27866 
27867 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
27868 
27869 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
27870 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
27871 		/*
27872 		 * Default value of the number of drainers is the
27873 		 * number of cpus, subject to maximum of 8 drainers.
27874 		 */
27875 		if (boot_max_ncpus != -1)
27876 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
27877 		else
27878 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
27879 	}
27880 
27881 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
27882 	    sizeof (idl_t), KM_SLEEP);
27883 
27884 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
27885 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
27886 		    MUTEX_DEFAULT, NULL);
27887 	}
27888 }
27889 
27890 static void
27891 conn_drain_fini(ip_stack_t *ipst)
27892 {
27893 	int i;
27894 
27895 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
27896 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
27897 	kmem_free(ipst->ips_conn_drain_list,
27898 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
27899 	ipst->ips_conn_drain_list = NULL;
27900 }
27901 
27902 /*
27903  * Note: For an overview of how flowcontrol is handled in IP please see the
27904  * IP Flowcontrol notes at the top of this file.
27905  *
27906  * Flow control has blocked us from proceeding. Insert the given conn in one
27907  * of the conn drain lists. These conn wq's will be qenabled later on when
27908  * STREAMS flow control does a backenable. conn_walk_drain will enable
27909  * the first conn in each of these drain lists. Each of these qenabled conns
27910  * in turn enables the next in the list, after it runs, or when it closes,
27911  * thus sustaining the drain process.
27912  *
27913  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
27914  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
27915  * running at any time, on a given conn, since there can be only 1 service proc
27916  * running on a queue at any time.
27917  */
27918 void
27919 conn_drain_insert(conn_t *connp)
27920 {
27921 	idl_t	*idl;
27922 	uint_t	index;
27923 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
27924 
27925 	mutex_enter(&connp->conn_lock);
27926 	if (connp->conn_state_flags & CONN_CLOSING) {
27927 		/*
27928 		 * The conn is closing as a result of which CONN_CLOSING
27929 		 * is set. Return.
27930 		 */
27931 		mutex_exit(&connp->conn_lock);
27932 		return;
27933 	} else if (connp->conn_idl == NULL) {
27934 		/*
27935 		 * Assign the next drain list round robin. We dont' use
27936 		 * a lock, and thus it may not be strictly round robin.
27937 		 * Atomicity of load/stores is enough to make sure that
27938 		 * conn_drain_list_index is always within bounds.
27939 		 */
27940 		index = ipst->ips_conn_drain_list_index;
27941 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
27942 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
27943 		index++;
27944 		if (index == ipst->ips_conn_drain_list_cnt)
27945 			index = 0;
27946 		ipst->ips_conn_drain_list_index = index;
27947 	}
27948 	mutex_exit(&connp->conn_lock);
27949 
27950 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27951 	if ((connp->conn_drain_prev != NULL) ||
27952 	    (connp->conn_state_flags & CONN_CLOSING)) {
27953 		/*
27954 		 * The conn is already in the drain list, OR
27955 		 * the conn is closing. We need to check again for
27956 		 * the closing case again since close can happen
27957 		 * after we drop the conn_lock, and before we
27958 		 * acquire the CONN_DRAIN_LIST_LOCK.
27959 		 */
27960 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27961 		return;
27962 	} else {
27963 		idl = connp->conn_idl;
27964 	}
27965 
27966 	/*
27967 	 * The conn is not in the drain list. Insert it at the
27968 	 * tail of the drain list. The drain list is circular
27969 	 * and doubly linked. idl_conn points to the 1st element
27970 	 * in the list.
27971 	 */
27972 	if (idl->idl_conn == NULL) {
27973 		idl->idl_conn = connp;
27974 		connp->conn_drain_next = connp;
27975 		connp->conn_drain_prev = connp;
27976 	} else {
27977 		conn_t *head = idl->idl_conn;
27978 
27979 		connp->conn_drain_next = head;
27980 		connp->conn_drain_prev = head->conn_drain_prev;
27981 		head->conn_drain_prev->conn_drain_next = connp;
27982 		head->conn_drain_prev = connp;
27983 	}
27984 	/*
27985 	 * For non streams based sockets assert flow control.
27986 	 */
27987 	if (IPCL_IS_NONSTR(connp)) {
27988 		(*connp->conn_upcalls->su_txq_full)
27989 		    (connp->conn_upper_handle, B_TRUE);
27990 	}
27991 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27992 }
27993 
27994 /*
27995  * This conn is closing, and we are called from ip_close. OR
27996  * This conn has been serviced by ip_wsrv, and we need to do the tail
27997  * processing.
27998  * If this conn is part of the drain list, we may need to sustain the drain
27999  * process by qenabling the next conn in the drain list. We may also need to
28000  * remove this conn from the list, if it is done.
28001  */
28002 static void
28003 conn_drain_tail(conn_t *connp, boolean_t closing)
28004 {
28005 	idl_t *idl;
28006 
28007 	/*
28008 	 * connp->conn_idl is stable at this point, and no lock is needed
28009 	 * to check it. If we are called from ip_close, close has already
28010 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28011 	 * called us only because conn_idl is non-null. If we are called thru
28012 	 * service, conn_idl could be null, but it cannot change because
28013 	 * service is single-threaded per queue, and there cannot be another
28014 	 * instance of service trying to call conn_drain_insert on this conn
28015 	 * now.
28016 	 */
28017 	ASSERT(!closing || (connp->conn_idl != NULL));
28018 
28019 	/*
28020 	 * If connp->conn_idl is null, the conn has not been inserted into any
28021 	 * drain list even once since creation of the conn. Just return.
28022 	 */
28023 	if (connp->conn_idl == NULL)
28024 		return;
28025 
28026 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28027 
28028 	if (connp->conn_drain_prev == NULL) {
28029 		/* This conn is currently not in the drain list.  */
28030 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28031 		return;
28032 	}
28033 	idl = connp->conn_idl;
28034 	if (idl->idl_conn_draining == connp) {
28035 		/*
28036 		 * This conn is the current drainer. If this is the last conn
28037 		 * in the drain list, we need to do more checks, in the 'if'
28038 		 * below. Otherwwise we need to just qenable the next conn,
28039 		 * to sustain the draining, and is handled in the 'else'
28040 		 * below.
28041 		 */
28042 		if (connp->conn_drain_next == idl->idl_conn) {
28043 			/*
28044 			 * This conn is the last in this list. This round
28045 			 * of draining is complete. If idl_repeat is set,
28046 			 * it means another flow enabling has happened from
28047 			 * the driver/streams and we need to another round
28048 			 * of draining.
28049 			 * If there are more than 2 conns in the drain list,
28050 			 * do a left rotate by 1, so that all conns except the
28051 			 * conn at the head move towards the head by 1, and the
28052 			 * the conn at the head goes to the tail. This attempts
28053 			 * a more even share for all queues that are being
28054 			 * drained.
28055 			 */
28056 			if ((connp->conn_drain_next != connp) &&
28057 			    (idl->idl_conn->conn_drain_next != connp)) {
28058 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28059 			}
28060 			if (idl->idl_repeat) {
28061 				qenable(idl->idl_conn->conn_wq);
28062 				idl->idl_conn_draining = idl->idl_conn;
28063 				idl->idl_repeat = 0;
28064 			} else {
28065 				idl->idl_conn_draining = NULL;
28066 			}
28067 		} else {
28068 			/*
28069 			 * If the next queue that we are now qenable'ing,
28070 			 * is closing, it will remove itself from this list
28071 			 * and qenable the subsequent queue in ip_close().
28072 			 * Serialization is acheived thru idl_lock.
28073 			 */
28074 			qenable(connp->conn_drain_next->conn_wq);
28075 			idl->idl_conn_draining = connp->conn_drain_next;
28076 		}
28077 	}
28078 	if (!connp->conn_did_putbq || closing) {
28079 		/*
28080 		 * Remove ourself from the drain list, if we did not do
28081 		 * a putbq, or if the conn is closing.
28082 		 * Note: It is possible that q->q_first is non-null. It means
28083 		 * that these messages landed after we did a enableok() in
28084 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28085 		 * service them.
28086 		 */
28087 		if (connp->conn_drain_next == connp) {
28088 			/* Singleton in the list */
28089 			ASSERT(connp->conn_drain_prev == connp);
28090 			idl->idl_conn = NULL;
28091 			idl->idl_conn_draining = NULL;
28092 		} else {
28093 			connp->conn_drain_prev->conn_drain_next =
28094 			    connp->conn_drain_next;
28095 			connp->conn_drain_next->conn_drain_prev =
28096 			    connp->conn_drain_prev;
28097 			if (idl->idl_conn == connp)
28098 				idl->idl_conn = connp->conn_drain_next;
28099 			ASSERT(idl->idl_conn_draining != connp);
28100 
28101 		}
28102 		connp->conn_drain_next = NULL;
28103 		connp->conn_drain_prev = NULL;
28104 
28105 		/*
28106 		 * For non streams based sockets open up flow control.
28107 		 */
28108 		if (IPCL_IS_NONSTR(connp)) {
28109 			(*connp->conn_upcalls->su_txq_full)
28110 			    (connp->conn_upper_handle, B_FALSE);
28111 		}
28112 	}
28113 
28114 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28115 }
28116 
28117 /*
28118  * Write service routine. Shared perimeter entry point.
28119  * ip_wsrv can be called in any of the following ways.
28120  * 1. The device queue's messages has fallen below the low water mark
28121  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28122  *    the drain lists and backenable the first conn in each list.
28123  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28124  *    qenabled non-tcp upper layers. We start dequeing messages and call
28125  *    ip_wput for each message.
28126  */
28127 
28128 void
28129 ip_wsrv(queue_t *q)
28130 {
28131 	conn_t	*connp;
28132 	ill_t	*ill;
28133 	mblk_t	*mp;
28134 
28135 	if (q->q_next) {
28136 		ill = (ill_t *)q->q_ptr;
28137 		if (ill->ill_state_flags == 0) {
28138 			/*
28139 			 * The device flow control has opened up.
28140 			 * Walk through conn drain lists and qenable the
28141 			 * first conn in each list. This makes sense only
28142 			 * if the stream is fully plumbed and setup.
28143 			 * Hence the if check above.
28144 			 */
28145 			ip1dbg(("ip_wsrv: walking\n"));
28146 			conn_walk_drain(ill->ill_ipst);
28147 		}
28148 		return;
28149 	}
28150 
28151 	connp = Q_TO_CONN(q);
28152 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28153 
28154 	/*
28155 	 * 1. Set conn_draining flag to signal that service is active.
28156 	 *
28157 	 * 2. ip_output determines whether it has been called from service,
28158 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28159 	 *    has been called from service.
28160 	 *
28161 	 * 3. Message ordering is preserved by the following logic.
28162 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28163 	 *    the message at the tail, if conn_draining is set (i.e. service
28164 	 *    is running) or if q->q_first is non-null.
28165 	 *
28166 	 *    ii. If ip_output is called from service, and if ip_output cannot
28167 	 *    putnext due to flow control, it does a putbq.
28168 	 *
28169 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28170 	 *    (causing an infinite loop).
28171 	 */
28172 	ASSERT(!connp->conn_did_putbq);
28173 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28174 		connp->conn_draining = 1;
28175 		noenable(q);
28176 		while ((mp = getq(q)) != NULL) {
28177 			ASSERT(CONN_Q(q));
28178 
28179 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28180 			if (connp->conn_did_putbq) {
28181 				/* ip_wput did a putbq */
28182 				break;
28183 			}
28184 		}
28185 		/*
28186 		 * At this point, a thread coming down from top, calling
28187 		 * ip_wput, may end up queueing the message. We have not yet
28188 		 * enabled the queue, so ip_wsrv won't be called again.
28189 		 * To avoid this race, check q->q_first again (in the loop)
28190 		 * If the other thread queued the message before we call
28191 		 * enableok(), we will catch it in the q->q_first check.
28192 		 * If the other thread queues the message after we call
28193 		 * enableok(), ip_wsrv will be called again by STREAMS.
28194 		 */
28195 		connp->conn_draining = 0;
28196 		enableok(q);
28197 
28198 	}
28199 
28200 	/* Enable the next conn for draining */
28201 	conn_drain_tail(connp, B_FALSE);
28202 
28203 	connp->conn_did_putbq = 0;
28204 }
28205 
28206 /*
28207  * Callback to disable flow control in IP.
28208  *
28209  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
28210  * is enabled.
28211  *
28212  * When MAC_TX() is not able to send any more packets, dld sets its queue
28213  * to QFULL and enable the STREAMS flow control. Later, when the underlying
28214  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
28215  * function and wakes up corresponding mac worker threads, which in turn
28216  * calls this callback function, and disables flow control.
28217  */
28218 /* ARGSUSED */
28219 void
28220 ill_flow_enable(void *ill, ip_mac_tx_cookie_t cookie)
28221 {
28222 	qenable(((ill_t *)ill)->ill_wq);
28223 }
28224 
28225 /*
28226  * Walk the list of all conn's calling the function provided with the
28227  * specified argument for each.	 Note that this only walks conn's that
28228  * have been bound.
28229  * Applies to both IPv4 and IPv6.
28230  */
28231 static void
28232 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28233 {
28234 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28235 	    ipst->ips_ipcl_udp_fanout_size,
28236 	    func, arg, zoneid);
28237 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28238 	    ipst->ips_ipcl_conn_fanout_size,
28239 	    func, arg, zoneid);
28240 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28241 	    ipst->ips_ipcl_bind_fanout_size,
28242 	    func, arg, zoneid);
28243 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28244 	    IPPROTO_MAX, func, arg, zoneid);
28245 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28246 	    IPPROTO_MAX, func, arg, zoneid);
28247 }
28248 
28249 /*
28250  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28251  * of conns that need to be drained, check if drain is already in progress.
28252  * If so set the idl_repeat bit, indicating that the last conn in the list
28253  * needs to reinitiate the drain once again, for the list. If drain is not
28254  * in progress for the list, initiate the draining, by qenabling the 1st
28255  * conn in the list. The drain is self-sustaining, each qenabled conn will
28256  * in turn qenable the next conn, when it is done/blocked/closing.
28257  */
28258 static void
28259 conn_walk_drain(ip_stack_t *ipst)
28260 {
28261 	int i;
28262 	idl_t *idl;
28263 
28264 	IP_STAT(ipst, ip_conn_walk_drain);
28265 
28266 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28267 		idl = &ipst->ips_conn_drain_list[i];
28268 		mutex_enter(&idl->idl_lock);
28269 		if (idl->idl_conn == NULL) {
28270 			mutex_exit(&idl->idl_lock);
28271 			continue;
28272 		}
28273 		/*
28274 		 * If this list is not being drained currently by
28275 		 * an ip_wsrv thread, start the process.
28276 		 */
28277 		if (idl->idl_conn_draining == NULL) {
28278 			ASSERT(idl->idl_repeat == 0);
28279 			qenable(idl->idl_conn->conn_wq);
28280 			idl->idl_conn_draining = idl->idl_conn;
28281 		} else {
28282 			idl->idl_repeat = 1;
28283 		}
28284 		mutex_exit(&idl->idl_lock);
28285 	}
28286 }
28287 
28288 /*
28289  * Walk an conn hash table of `count' buckets, calling func for each entry.
28290  */
28291 static void
28292 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28293     zoneid_t zoneid)
28294 {
28295 	conn_t	*connp;
28296 
28297 	while (count-- > 0) {
28298 		mutex_enter(&connfp->connf_lock);
28299 		for (connp = connfp->connf_head; connp != NULL;
28300 		    connp = connp->conn_next) {
28301 			if (zoneid == GLOBAL_ZONEID ||
28302 			    zoneid == connp->conn_zoneid) {
28303 				CONN_INC_REF(connp);
28304 				mutex_exit(&connfp->connf_lock);
28305 				(*func)(connp, arg);
28306 				mutex_enter(&connfp->connf_lock);
28307 				CONN_DEC_REF(connp);
28308 			}
28309 		}
28310 		mutex_exit(&connfp->connf_lock);
28311 		connfp++;
28312 	}
28313 }
28314 
28315 /* conn_walk_fanout routine invoked for ip_conn_report for each conn. */
28316 static void
28317 conn_report1(conn_t *connp, void *mp)
28318 {
28319 	char	buf1[INET6_ADDRSTRLEN];
28320 	char	buf2[INET6_ADDRSTRLEN];
28321 	uint_t	print_len, buf_len;
28322 
28323 	ASSERT(connp != NULL);
28324 
28325 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28326 	if (buf_len <= 0)
28327 		return;
28328 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28329 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28330 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28331 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28332 	    "%5d %s/%05d %s/%05d\n",
28333 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28334 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28335 	    buf1, connp->conn_lport,
28336 	    buf2, connp->conn_fport);
28337 	if (print_len < buf_len) {
28338 		((mblk_t *)mp)->b_wptr += print_len;
28339 	} else {
28340 		((mblk_t *)mp)->b_wptr += buf_len;
28341 	}
28342 }
28343 
28344 /*
28345  * Named Dispatch routine to produce a formatted report on all conns
28346  * that are listed in one of the fanout tables.
28347  * This report is accessed by using the ndd utility to "get" ND variable
28348  * "ip_conn_status".
28349  */
28350 /* ARGSUSED */
28351 static int
28352 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28353 {
28354 	conn_t *connp = Q_TO_CONN(q);
28355 
28356 	(void) mi_mpprintf(mp,
28357 	    "CONN      " MI_COL_HDRPAD_STR
28358 	    "rfq      " MI_COL_HDRPAD_STR
28359 	    "stq      " MI_COL_HDRPAD_STR
28360 	    " zone local		 remote");
28361 
28362 	/*
28363 	 * Because of the ndd constraint, at most we can have 64K buffer
28364 	 * to put in all conn info.  So to be more efficient, just
28365 	 * allocate a 64K buffer here, assuming we need that large buffer.
28366 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28367 	 */
28368 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28369 		/* The following may work even if we cannot get a large buf. */
28370 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28371 		return (0);
28372 	}
28373 
28374 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28375 	    connp->conn_netstack->netstack_ip);
28376 	return (0);
28377 }
28378 
28379 /*
28380  * Determine if the ill and multicast aspects of that packets
28381  * "matches" the conn.
28382  */
28383 boolean_t
28384 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28385     zoneid_t zoneid)
28386 {
28387 	ill_t *bound_ill;
28388 	boolean_t found;
28389 	ipif_t *ipif;
28390 	ire_t *ire;
28391 	ipaddr_t dst, src;
28392 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28393 
28394 	dst = ipha->ipha_dst;
28395 	src = ipha->ipha_src;
28396 
28397 	/*
28398 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28399 	 * unicast, broadcast and multicast reception to
28400 	 * conn_incoming_ill. conn_wantpacket itself is called
28401 	 * only for BROADCAST and multicast.
28402 	 */
28403 	bound_ill = connp->conn_incoming_ill;
28404 	if (bound_ill != NULL) {
28405 		if (IS_IPMP(bound_ill)) {
28406 			if (bound_ill->ill_grp != ill->ill_grp)
28407 				return (B_FALSE);
28408 		} else {
28409 			if (bound_ill != ill)
28410 				return (B_FALSE);
28411 		}
28412 	}
28413 
28414 	if (!CLASSD(dst)) {
28415 		if (IPCL_ZONE_MATCH(connp, zoneid))
28416 			return (B_TRUE);
28417 		/*
28418 		 * The conn is in a different zone; we need to check that this
28419 		 * broadcast address is configured in the application's zone.
28420 		 */
28421 		ipif = ipif_get_next_ipif(NULL, ill);
28422 		if (ipif == NULL)
28423 			return (B_FALSE);
28424 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28425 		    connp->conn_zoneid, NULL,
28426 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL), ipst);
28427 		ipif_refrele(ipif);
28428 		if (ire != NULL) {
28429 			ire_refrele(ire);
28430 			return (B_TRUE);
28431 		} else {
28432 			return (B_FALSE);
28433 		}
28434 	}
28435 
28436 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28437 	    connp->conn_zoneid == zoneid) {
28438 		/*
28439 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28440 		 * disabled, therefore we don't dispatch the multicast packet to
28441 		 * the sending zone.
28442 		 */
28443 		return (B_FALSE);
28444 	}
28445 
28446 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28447 		/*
28448 		 * Multicast packet on the loopback interface: we only match
28449 		 * conns who joined the group in the specified zone.
28450 		 */
28451 		return (B_FALSE);
28452 	}
28453 
28454 	if (connp->conn_multi_router) {
28455 		/* multicast packet and multicast router socket: send up */
28456 		return (B_TRUE);
28457 	}
28458 
28459 	mutex_enter(&connp->conn_lock);
28460 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28461 	mutex_exit(&connp->conn_lock);
28462 	return (found);
28463 }
28464 
28465 /*
28466  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28467  */
28468 /* ARGSUSED */
28469 static void
28470 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28471 {
28472 	ill_t *ill = (ill_t *)q->q_ptr;
28473 	mblk_t	*mp1, *mp2;
28474 	ipif_t  *ipif;
28475 	int err = 0;
28476 	conn_t *connp = NULL;
28477 	ipsq_t	*ipsq;
28478 	arc_t	*arc;
28479 
28480 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28481 
28482 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28483 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28484 
28485 	ASSERT(IAM_WRITER_ILL(ill));
28486 	mp2 = mp->b_cont;
28487 	mp->b_cont = NULL;
28488 
28489 	/*
28490 	 * We have now received the arp bringup completion message
28491 	 * from ARP. Mark the arp bringup as done. Also if the arp
28492 	 * stream has already started closing, send up the AR_ARP_CLOSING
28493 	 * ack now since ARP is waiting in close for this ack.
28494 	 */
28495 	mutex_enter(&ill->ill_lock);
28496 	ill->ill_arp_bringup_pending = 0;
28497 	if (ill->ill_arp_closing) {
28498 		mutex_exit(&ill->ill_lock);
28499 		/* Let's reuse the mp for sending the ack */
28500 		arc = (arc_t *)mp->b_rptr;
28501 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28502 		arc->arc_cmd = AR_ARP_CLOSING;
28503 		qreply(q, mp);
28504 	} else {
28505 		mutex_exit(&ill->ill_lock);
28506 		freeb(mp);
28507 	}
28508 
28509 	ipsq = ill->ill_phyint->phyint_ipsq;
28510 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
28511 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28512 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28513 	if (mp1 == NULL) {
28514 		/* bringup was aborted by the user */
28515 		freemsg(mp2);
28516 		return;
28517 	}
28518 
28519 	/*
28520 	 * If an IOCTL is waiting on this (ipx_current_ioctl != 0), then we
28521 	 * must have an associated conn_t.  Otherwise, we're bringing this
28522 	 * interface back up as part of handling an asynchronous event (e.g.,
28523 	 * physical address change).
28524 	 */
28525 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0) {
28526 		ASSERT(connp != NULL);
28527 		q = CONNP_TO_WQ(connp);
28528 	} else {
28529 		ASSERT(connp == NULL);
28530 		q = ill->ill_rq;
28531 	}
28532 
28533 	/*
28534 	 * If the DL_BIND_REQ fails, it is noted
28535 	 * in arc_name_offset.
28536 	 */
28537 	err = *((int *)mp2->b_rptr);
28538 	if (err == 0) {
28539 		if (ipif->ipif_isv6) {
28540 			if ((err = ipif_up_done_v6(ipif)) != 0)
28541 				ip0dbg(("ip_arp_done: init failed\n"));
28542 		} else {
28543 			if ((err = ipif_up_done(ipif)) != 0)
28544 				ip0dbg(("ip_arp_done: init failed\n"));
28545 		}
28546 	} else {
28547 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28548 	}
28549 
28550 	freemsg(mp2);
28551 
28552 	if ((err == 0) && (ill->ill_up_ipifs)) {
28553 		err = ill_up_ipifs(ill, q, mp1);
28554 		if (err == EINPROGRESS)
28555 			return;
28556 	}
28557 
28558 	/*
28559 	 * If we have a moved ipif to bring up, and everything has succeeded
28560 	 * to this point, bring it up on the IPMP ill.  Otherwise, leave it
28561 	 * down -- the admin can try to bring it up by hand if need be.
28562 	 */
28563 	if (ill->ill_move_ipif != NULL) {
28564 		ipif = ill->ill_move_ipif;
28565 		ill->ill_move_ipif = NULL;
28566 		if (err == 0) {
28567 			err = ipif_up(ipif, q, mp1);
28568 			if (err == EINPROGRESS)
28569 				return;
28570 		}
28571 	}
28572 
28573 	/*
28574 	 * The operation must complete without EINPROGRESS since
28575 	 * ipsq_pending_mp_get() has removed the mblk.  Otherwise, the
28576 	 * operation will be stuck forever in the ipsq.
28577 	 */
28578 	ASSERT(err != EINPROGRESS);
28579 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0)
28580 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28581 	else
28582 		ipsq_current_finish(ipsq);
28583 }
28584 
28585 /* Allocate the private structure */
28586 static int
28587 ip_priv_alloc(void **bufp)
28588 {
28589 	void	*buf;
28590 
28591 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28592 		return (ENOMEM);
28593 
28594 	*bufp = buf;
28595 	return (0);
28596 }
28597 
28598 /* Function to delete the private structure */
28599 void
28600 ip_priv_free(void *buf)
28601 {
28602 	ASSERT(buf != NULL);
28603 	kmem_free(buf, sizeof (ip_priv_t));
28604 }
28605 
28606 /*
28607  * The entry point for IPPF processing.
28608  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28609  * routine just returns.
28610  *
28611  * When called, ip_process generates an ipp_packet_t structure
28612  * which holds the state information for this packet and invokes the
28613  * the classifier (via ipp_packet_process). The classification, depending on
28614  * configured filters, results in a list of actions for this packet. Invoking
28615  * an action may cause the packet to be dropped, in which case the resulting
28616  * mblk (*mpp) is NULL. proc indicates the callout position for
28617  * this packet and ill_index is the interface this packet on or will leave
28618  * on (inbound and outbound resp.).
28619  */
28620 void
28621 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28622 {
28623 	mblk_t		*mp;
28624 	ip_priv_t	*priv;
28625 	ipp_action_id_t	aid;
28626 	int		rc = 0;
28627 	ipp_packet_t	*pp;
28628 #define	IP_CLASS	"ip"
28629 
28630 	/* If the classifier is not loaded, return  */
28631 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28632 		return;
28633 	}
28634 
28635 	mp = *mpp;
28636 	ASSERT(mp != NULL);
28637 
28638 	/* Allocate the packet structure */
28639 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28640 	if (rc != 0) {
28641 		*mpp = NULL;
28642 		freemsg(mp);
28643 		return;
28644 	}
28645 
28646 	/* Allocate the private structure */
28647 	rc = ip_priv_alloc((void **)&priv);
28648 	if (rc != 0) {
28649 		*mpp = NULL;
28650 		freemsg(mp);
28651 		ipp_packet_free(pp);
28652 		return;
28653 	}
28654 	priv->proc = proc;
28655 	priv->ill_index = ill_index;
28656 	ipp_packet_set_private(pp, priv, ip_priv_free);
28657 	ipp_packet_set_data(pp, mp);
28658 
28659 	/* Invoke the classifier */
28660 	rc = ipp_packet_process(&pp);
28661 	if (pp != NULL) {
28662 		mp = ipp_packet_get_data(pp);
28663 		ipp_packet_free(pp);
28664 		if (rc != 0) {
28665 			freemsg(mp);
28666 			*mpp = NULL;
28667 		}
28668 	} else {
28669 		*mpp = NULL;
28670 	}
28671 #undef	IP_CLASS
28672 }
28673 
28674 /*
28675  * Propagate a multicast group membership operation (add/drop) on
28676  * all the interfaces crossed by the related multirt routes.
28677  * The call is considered successful if the operation succeeds
28678  * on at least one interface.
28679  */
28680 static int
28681 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28682     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28683     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28684     mblk_t *first_mp)
28685 {
28686 	ire_t		*ire_gw;
28687 	irb_t		*irb;
28688 	int		error = 0;
28689 	opt_restart_t	*or;
28690 	ip_stack_t	*ipst = ire->ire_ipst;
28691 
28692 	irb = ire->ire_bucket;
28693 	ASSERT(irb != NULL);
28694 
28695 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28696 
28697 	or = (opt_restart_t *)first_mp->b_rptr;
28698 	IRB_REFHOLD(irb);
28699 	for (; ire != NULL; ire = ire->ire_next) {
28700 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28701 			continue;
28702 		if (ire->ire_addr != group)
28703 			continue;
28704 
28705 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28706 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28707 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28708 		/* No resolver exists for the gateway; skip this ire. */
28709 		if (ire_gw == NULL)
28710 			continue;
28711 
28712 		/*
28713 		 * This function can return EINPROGRESS. If so the operation
28714 		 * will be restarted from ip_restart_optmgmt which will
28715 		 * call ip_opt_set and option processing will restart for
28716 		 * this option. So we may end up calling 'fn' more than once.
28717 		 * This requires that 'fn' is idempotent except for the
28718 		 * return value. The operation is considered a success if
28719 		 * it succeeds at least once on any one interface.
28720 		 */
28721 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28722 		    NULL, fmode, src, first_mp);
28723 		if (error == 0)
28724 			or->or_private = CGTP_MCAST_SUCCESS;
28725 
28726 		if (ip_debug > 0) {
28727 			ulong_t	off;
28728 			char	*ksym;
28729 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28730 			ip2dbg(("ip_multirt_apply_membership: "
28731 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28732 			    "error %d [success %u]\n",
28733 			    ksym ? ksym : "?",
28734 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28735 			    error, or->or_private));
28736 		}
28737 
28738 		ire_refrele(ire_gw);
28739 		if (error == EINPROGRESS) {
28740 			IRB_REFRELE(irb);
28741 			return (error);
28742 		}
28743 	}
28744 	IRB_REFRELE(irb);
28745 	/*
28746 	 * Consider the call as successful if we succeeded on at least
28747 	 * one interface. Otherwise, return the last encountered error.
28748 	 */
28749 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28750 }
28751 
28752 /*
28753  * Issue a warning regarding a route crossing an interface with an
28754  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28755  * amount of time is logged.
28756  */
28757 static void
28758 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28759 {
28760 	hrtime_t	current = gethrtime();
28761 	char		buf[INET_ADDRSTRLEN];
28762 	ip_stack_t	*ipst = ire->ire_ipst;
28763 
28764 	/* Convert interval in ms to hrtime in ns */
28765 	if (ipst->ips_multirt_bad_mtu_last_time +
28766 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28767 	    current) {
28768 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28769 		    "to %s, incorrect MTU %u (expected %u)\n",
28770 		    ip_dot_addr(ire->ire_addr, buf),
28771 		    ire->ire_max_frag, max_frag);
28772 
28773 		ipst->ips_multirt_bad_mtu_last_time = current;
28774 	}
28775 }
28776 
28777 
28778 /*
28779  * Get the CGTP (multirouting) filtering status.
28780  * If 0, the CGTP hooks are transparent.
28781  */
28782 /* ARGSUSED */
28783 static int
28784 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28785 {
28786 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28787 
28788 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28789 	return (0);
28790 }
28791 
28792 
28793 /*
28794  * Set the CGTP (multirouting) filtering status.
28795  * If the status is changed from active to transparent
28796  * or from transparent to active, forward the new status
28797  * to the filtering module (if loaded).
28798  */
28799 /* ARGSUSED */
28800 static int
28801 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28802     cred_t *ioc_cr)
28803 {
28804 	long		new_value;
28805 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28806 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28807 
28808 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
28809 		return (EPERM);
28810 
28811 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28812 	    new_value < 0 || new_value > 1) {
28813 		return (EINVAL);
28814 	}
28815 
28816 	if ((!*ip_cgtp_filter_value) && new_value) {
28817 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28818 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28819 		    " (module not loaded)" : "");
28820 	}
28821 	if (*ip_cgtp_filter_value && (!new_value)) {
28822 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28823 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28824 		    " (module not loaded)" : "");
28825 	}
28826 
28827 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28828 		int	res;
28829 		netstackid_t stackid;
28830 
28831 		stackid = ipst->ips_netstack->netstack_stackid;
28832 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
28833 		    new_value);
28834 		if (res)
28835 			return (res);
28836 	}
28837 
28838 	*ip_cgtp_filter_value = (boolean_t)new_value;
28839 
28840 	return (0);
28841 }
28842 
28843 
28844 /*
28845  * Return the expected CGTP hooks version number.
28846  */
28847 int
28848 ip_cgtp_filter_supported(void)
28849 {
28850 	return (ip_cgtp_filter_rev);
28851 }
28852 
28853 
28854 /*
28855  * CGTP hooks can be registered by invoking this function.
28856  * Checks that the version number matches.
28857  */
28858 int
28859 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
28860 {
28861 	netstack_t *ns;
28862 	ip_stack_t *ipst;
28863 
28864 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28865 		return (ENOTSUP);
28866 
28867 	ns = netstack_find_by_stackid(stackid);
28868 	if (ns == NULL)
28869 		return (EINVAL);
28870 	ipst = ns->netstack_ip;
28871 	ASSERT(ipst != NULL);
28872 
28873 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28874 		netstack_rele(ns);
28875 		return (EALREADY);
28876 	}
28877 
28878 	ipst->ips_ip_cgtp_filter_ops = ops;
28879 	netstack_rele(ns);
28880 	return (0);
28881 }
28882 
28883 /*
28884  * CGTP hooks can be unregistered by invoking this function.
28885  * Returns ENXIO if there was no registration.
28886  * Returns EBUSY if the ndd variable has not been turned off.
28887  */
28888 int
28889 ip_cgtp_filter_unregister(netstackid_t stackid)
28890 {
28891 	netstack_t *ns;
28892 	ip_stack_t *ipst;
28893 
28894 	ns = netstack_find_by_stackid(stackid);
28895 	if (ns == NULL)
28896 		return (EINVAL);
28897 	ipst = ns->netstack_ip;
28898 	ASSERT(ipst != NULL);
28899 
28900 	if (ipst->ips_ip_cgtp_filter) {
28901 		netstack_rele(ns);
28902 		return (EBUSY);
28903 	}
28904 
28905 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
28906 		netstack_rele(ns);
28907 		return (ENXIO);
28908 	}
28909 	ipst->ips_ip_cgtp_filter_ops = NULL;
28910 	netstack_rele(ns);
28911 	return (0);
28912 }
28913 
28914 /*
28915  * Check whether there is a CGTP filter registration.
28916  * Returns non-zero if there is a registration, otherwise returns zero.
28917  * Note: returns zero if bad stackid.
28918  */
28919 int
28920 ip_cgtp_filter_is_registered(netstackid_t stackid)
28921 {
28922 	netstack_t *ns;
28923 	ip_stack_t *ipst;
28924 	int ret;
28925 
28926 	ns = netstack_find_by_stackid(stackid);
28927 	if (ns == NULL)
28928 		return (0);
28929 	ipst = ns->netstack_ip;
28930 	ASSERT(ipst != NULL);
28931 
28932 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
28933 		ret = 1;
28934 	else
28935 		ret = 0;
28936 
28937 	netstack_rele(ns);
28938 	return (ret);
28939 }
28940 
28941 static int
28942 ip_squeue_switch(int val)
28943 {
28944 	int rval = SQ_FILL;
28945 
28946 	switch (val) {
28947 	case IP_SQUEUE_ENTER_NODRAIN:
28948 		rval = SQ_NODRAIN;
28949 		break;
28950 	case IP_SQUEUE_ENTER:
28951 		rval = SQ_PROCESS;
28952 		break;
28953 	default:
28954 		break;
28955 	}
28956 	return (rval);
28957 }
28958 
28959 /* ARGSUSED */
28960 static int
28961 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
28962     caddr_t addr, cred_t *cr)
28963 {
28964 	int *v = (int *)addr;
28965 	long new_value;
28966 
28967 	if (secpolicy_net_config(cr, B_FALSE) != 0)
28968 		return (EPERM);
28969 
28970 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28971 		return (EINVAL);
28972 
28973 	ip_squeue_flag = ip_squeue_switch(new_value);
28974 	*v = new_value;
28975 	return (0);
28976 }
28977 
28978 /*
28979  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
28980  * ip_debug.
28981  */
28982 /* ARGSUSED */
28983 static int
28984 ip_int_set(queue_t *q, mblk_t *mp, char *value,
28985     caddr_t addr, cred_t *cr)
28986 {
28987 	int *v = (int *)addr;
28988 	long new_value;
28989 
28990 	if (secpolicy_net_config(cr, B_FALSE) != 0)
28991 		return (EPERM);
28992 
28993 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28994 		return (EINVAL);
28995 
28996 	*v = new_value;
28997 	return (0);
28998 }
28999 
29000 static void *
29001 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29002 {
29003 	kstat_t *ksp;
29004 
29005 	ip_stat_t template = {
29006 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29007 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29008 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29009 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29010 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29011 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29012 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29013 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29014 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29015 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29016 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29017 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29018 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29019 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29020 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29021 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29022 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29023 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29024 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29025 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29026 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29027 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29028 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29029 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29030 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29031 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29032 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29033 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29034 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29035 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29036 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29037 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29038 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29039 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29040 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29041 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29042 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29043 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29044 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29045 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29046 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29047 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29048 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29049 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29050 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29051 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29052 	};
29053 
29054 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29055 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29056 	    KSTAT_FLAG_VIRTUAL, stackid);
29057 
29058 	if (ksp == NULL)
29059 		return (NULL);
29060 
29061 	bcopy(&template, ip_statisticsp, sizeof (template));
29062 	ksp->ks_data = (void *)ip_statisticsp;
29063 	ksp->ks_private = (void *)(uintptr_t)stackid;
29064 
29065 	kstat_install(ksp);
29066 	return (ksp);
29067 }
29068 
29069 static void
29070 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29071 {
29072 	if (ksp != NULL) {
29073 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29074 		kstat_delete_netstack(ksp, stackid);
29075 	}
29076 }
29077 
29078 static void *
29079 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29080 {
29081 	kstat_t	*ksp;
29082 
29083 	ip_named_kstat_t template = {
29084 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29085 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29086 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29087 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29088 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29089 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29090 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29091 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29092 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29093 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29094 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29095 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29096 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29097 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29098 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29099 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29100 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29101 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29102 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29103 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29104 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29105 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29106 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29107 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29108 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29109 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29110 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29111 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29112 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29113 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29114 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29115 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29116 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29117 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29118 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29119 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29120 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29121 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29122 	};
29123 
29124 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29125 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29126 	if (ksp == NULL || ksp->ks_data == NULL)
29127 		return (NULL);
29128 
29129 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29130 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29131 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29132 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29133 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29134 
29135 	template.netToMediaEntrySize.value.i32 =
29136 	    sizeof (mib2_ipNetToMediaEntry_t);
29137 
29138 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29139 
29140 	bcopy(&template, ksp->ks_data, sizeof (template));
29141 	ksp->ks_update = ip_kstat_update;
29142 	ksp->ks_private = (void *)(uintptr_t)stackid;
29143 
29144 	kstat_install(ksp);
29145 	return (ksp);
29146 }
29147 
29148 static void
29149 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29150 {
29151 	if (ksp != NULL) {
29152 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29153 		kstat_delete_netstack(ksp, stackid);
29154 	}
29155 }
29156 
29157 static int
29158 ip_kstat_update(kstat_t *kp, int rw)
29159 {
29160 	ip_named_kstat_t *ipkp;
29161 	mib2_ipIfStatsEntry_t ipmib;
29162 	ill_walk_context_t ctx;
29163 	ill_t *ill;
29164 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29165 	netstack_t	*ns;
29166 	ip_stack_t	*ipst;
29167 
29168 	if (kp == NULL || kp->ks_data == NULL)
29169 		return (EIO);
29170 
29171 	if (rw == KSTAT_WRITE)
29172 		return (EACCES);
29173 
29174 	ns = netstack_find_by_stackid(stackid);
29175 	if (ns == NULL)
29176 		return (-1);
29177 	ipst = ns->netstack_ip;
29178 	if (ipst == NULL) {
29179 		netstack_rele(ns);
29180 		return (-1);
29181 	}
29182 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29183 
29184 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29185 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29186 	ill = ILL_START_WALK_V4(&ctx, ipst);
29187 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29188 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29189 	rw_exit(&ipst->ips_ill_g_lock);
29190 
29191 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29192 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29193 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29194 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29195 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29196 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29197 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29198 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29199 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29200 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29201 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29202 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29203 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29204 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29205 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29206 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29207 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29208 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29209 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29210 
29211 	ipkp->routingDiscards.value.ui32 =	0;
29212 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29213 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29214 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29215 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29216 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29217 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29218 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29219 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29220 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29221 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29222 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29223 
29224 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29225 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29226 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29227 
29228 	netstack_rele(ns);
29229 
29230 	return (0);
29231 }
29232 
29233 static void *
29234 icmp_kstat_init(netstackid_t stackid)
29235 {
29236 	kstat_t	*ksp;
29237 
29238 	icmp_named_kstat_t template = {
29239 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29240 		{ "inErrors",		KSTAT_DATA_UINT32 },
29241 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29242 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29243 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29244 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29245 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29246 		{ "inEchos",		KSTAT_DATA_UINT32 },
29247 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29248 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29249 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29250 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29251 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29252 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29253 		{ "outErrors",		KSTAT_DATA_UINT32 },
29254 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29255 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29256 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29257 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29258 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29259 		{ "outEchos",		KSTAT_DATA_UINT32 },
29260 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29261 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29262 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29263 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29264 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29265 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29266 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29267 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29268 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29269 		{ "outDrops",		KSTAT_DATA_UINT32 },
29270 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29271 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29272 	};
29273 
29274 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29275 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29276 	if (ksp == NULL || ksp->ks_data == NULL)
29277 		return (NULL);
29278 
29279 	bcopy(&template, ksp->ks_data, sizeof (template));
29280 
29281 	ksp->ks_update = icmp_kstat_update;
29282 	ksp->ks_private = (void *)(uintptr_t)stackid;
29283 
29284 	kstat_install(ksp);
29285 	return (ksp);
29286 }
29287 
29288 static void
29289 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29290 {
29291 	if (ksp != NULL) {
29292 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29293 		kstat_delete_netstack(ksp, stackid);
29294 	}
29295 }
29296 
29297 static int
29298 icmp_kstat_update(kstat_t *kp, int rw)
29299 {
29300 	icmp_named_kstat_t *icmpkp;
29301 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29302 	netstack_t	*ns;
29303 	ip_stack_t	*ipst;
29304 
29305 	if ((kp == NULL) || (kp->ks_data == NULL))
29306 		return (EIO);
29307 
29308 	if (rw == KSTAT_WRITE)
29309 		return (EACCES);
29310 
29311 	ns = netstack_find_by_stackid(stackid);
29312 	if (ns == NULL)
29313 		return (-1);
29314 	ipst = ns->netstack_ip;
29315 	if (ipst == NULL) {
29316 		netstack_rele(ns);
29317 		return (-1);
29318 	}
29319 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29320 
29321 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29322 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29323 	icmpkp->inDestUnreachs.value.ui32 =
29324 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29325 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29326 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29327 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29328 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29329 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29330 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29331 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29332 	icmpkp->inTimestampReps.value.ui32 =
29333 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29334 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29335 	icmpkp->inAddrMaskReps.value.ui32 =
29336 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29337 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29338 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29339 	icmpkp->outDestUnreachs.value.ui32 =
29340 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29341 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29342 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29343 	icmpkp->outSrcQuenchs.value.ui32 =
29344 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29345 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29346 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29347 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29348 	icmpkp->outTimestamps.value.ui32 =
29349 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29350 	icmpkp->outTimestampReps.value.ui32 =
29351 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29352 	icmpkp->outAddrMasks.value.ui32 =
29353 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29354 	icmpkp->outAddrMaskReps.value.ui32 =
29355 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29356 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29357 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29358 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29359 	icmpkp->outFragNeeded.value.ui32 =
29360 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29361 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29362 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29363 	icmpkp->inBadRedirects.value.ui32 =
29364 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29365 
29366 	netstack_rele(ns);
29367 	return (0);
29368 }
29369 
29370 /*
29371  * This is the fanout function for raw socket opened for SCTP.  Note
29372  * that it is called after SCTP checks that there is no socket which
29373  * wants a packet.  Then before SCTP handles this out of the blue packet,
29374  * this function is called to see if there is any raw socket for SCTP.
29375  * If there is and it is bound to the correct address, the packet will
29376  * be sent to that socket.  Note that only one raw socket can be bound to
29377  * a port.  This is assured in ipcl_sctp_hash_insert();
29378  */
29379 void
29380 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29381     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29382     zoneid_t zoneid)
29383 {
29384 	conn_t		*connp;
29385 	queue_t		*rq;
29386 	mblk_t		*first_mp;
29387 	boolean_t	secure;
29388 	ip6_t		*ip6h;
29389 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29390 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29391 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29392 	boolean_t	sctp_csum_err = B_FALSE;
29393 
29394 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29395 		sctp_csum_err = B_TRUE;
29396 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29397 	}
29398 
29399 	first_mp = mp;
29400 	if (mctl_present) {
29401 		mp = first_mp->b_cont;
29402 		secure = ipsec_in_is_secure(first_mp);
29403 		ASSERT(mp != NULL);
29404 	} else {
29405 		secure = B_FALSE;
29406 	}
29407 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29408 
29409 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29410 	if (connp == NULL) {
29411 		/*
29412 		 * Although raw sctp is not summed, OOB chunks must be.
29413 		 * Drop the packet here if the sctp checksum failed.
29414 		 */
29415 		if (sctp_csum_err) {
29416 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29417 			freemsg(first_mp);
29418 			return;
29419 		}
29420 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29421 		return;
29422 	}
29423 	rq = connp->conn_rq;
29424 	if (!canputnext(rq)) {
29425 		CONN_DEC_REF(connp);
29426 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29427 		freemsg(first_mp);
29428 		return;
29429 	}
29430 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29431 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29432 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29433 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29434 		if (first_mp == NULL) {
29435 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29436 			CONN_DEC_REF(connp);
29437 			return;
29438 		}
29439 	}
29440 	/*
29441 	 * We probably should not send M_CTL message up to
29442 	 * raw socket.
29443 	 */
29444 	if (mctl_present)
29445 		freeb(first_mp);
29446 
29447 	/* Initiate IPPF processing here if needed. */
29448 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29449 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29450 		ip_process(IPP_LOCAL_IN, &mp,
29451 		    recv_ill->ill_phyint->phyint_ifindex);
29452 		if (mp == NULL) {
29453 			CONN_DEC_REF(connp);
29454 			return;
29455 		}
29456 	}
29457 
29458 	if (connp->conn_recvif || connp->conn_recvslla ||
29459 	    ((connp->conn_ip_recvpktinfo ||
29460 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29461 	    (flags & IP_FF_IPINFO))) {
29462 		int in_flags = 0;
29463 
29464 		/*
29465 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29466 		 * IPF_RECVIF.
29467 		 */
29468 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29469 			in_flags = IPF_RECVIF;
29470 		}
29471 		if (connp->conn_recvslla) {
29472 			in_flags |= IPF_RECVSLLA;
29473 		}
29474 		if (isv4) {
29475 			mp = ip_add_info(mp, recv_ill, in_flags,
29476 			    IPCL_ZONEID(connp), ipst);
29477 		} else {
29478 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29479 			if (mp == NULL) {
29480 				BUMP_MIB(recv_ill->ill_ip_mib,
29481 				    ipIfStatsInDiscards);
29482 				CONN_DEC_REF(connp);
29483 				return;
29484 			}
29485 		}
29486 	}
29487 
29488 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29489 	/*
29490 	 * We are sending the IPSEC_IN message also up. Refer
29491 	 * to comments above this function.
29492 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29493 	 */
29494 	(connp->conn_recv)(connp, mp, NULL);
29495 	CONN_DEC_REF(connp);
29496 }
29497 
29498 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29499 {									\
29500 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29501 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29502 }
29503 /*
29504  * This function should be called only if all packet processing
29505  * including fragmentation is complete. Callers of this function
29506  * must set mp->b_prev to one of these values:
29507  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29508  * prior to handing over the mp as first argument to this function.
29509  *
29510  * If the ire passed by caller is incomplete, this function
29511  * queues the packet and if necessary, sends ARP request and bails.
29512  * If the ire passed is fully resolved, we simply prepend
29513  * the link-layer header to the packet, do ipsec hw acceleration
29514  * work if necessary, and send the packet out on the wire.
29515  *
29516  * NOTE: IPsec will only call this function with fully resolved
29517  * ires if hw acceleration is involved.
29518  * TODO list :
29519  * 	a Handle M_MULTIDATA so that
29520  *	  tcp_multisend->tcp_multisend_data can
29521  *	  call ip_xmit_v4 directly
29522  *	b Handle post-ARP work for fragments so that
29523  *	  ip_wput_frag can call this function.
29524  */
29525 ipxmit_state_t
29526 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io,
29527     boolean_t flow_ctl_enabled, conn_t *connp)
29528 {
29529 	nce_t		*arpce;
29530 	ipha_t		*ipha;
29531 	queue_t		*q;
29532 	int		ill_index;
29533 	mblk_t		*nxt_mp, *first_mp;
29534 	boolean_t	xmit_drop = B_FALSE;
29535 	ip_proc_t	proc;
29536 	ill_t		*out_ill;
29537 	int		pkt_len;
29538 
29539 	arpce = ire->ire_nce;
29540 	ASSERT(arpce != NULL);
29541 
29542 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29543 
29544 	mutex_enter(&arpce->nce_lock);
29545 	switch (arpce->nce_state) {
29546 	case ND_REACHABLE:
29547 		/* If there are other queued packets, queue this packet */
29548 		if (arpce->nce_qd_mp != NULL) {
29549 			if (mp != NULL)
29550 				nce_queue_mp_common(arpce, mp, B_FALSE);
29551 			mp = arpce->nce_qd_mp;
29552 		}
29553 		arpce->nce_qd_mp = NULL;
29554 		mutex_exit(&arpce->nce_lock);
29555 
29556 		/*
29557 		 * Flush the queue.  In the common case, where the
29558 		 * ARP is already resolved,  it will go through the
29559 		 * while loop only once.
29560 		 */
29561 		while (mp != NULL) {
29562 
29563 			nxt_mp = mp->b_next;
29564 			mp->b_next = NULL;
29565 			ASSERT(mp->b_datap->db_type != M_CTL);
29566 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29567 			/*
29568 			 * This info is needed for IPQOS to do COS marking
29569 			 * in ip_wput_attach_llhdr->ip_process.
29570 			 */
29571 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29572 			mp->b_prev = NULL;
29573 
29574 			/* set up ill index for outbound qos processing */
29575 			out_ill = ire_to_ill(ire);
29576 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29577 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29578 			    ill_index, &ipha);
29579 			if (first_mp == NULL) {
29580 				xmit_drop = B_TRUE;
29581 				BUMP_MIB(out_ill->ill_ip_mib,
29582 				    ipIfStatsOutDiscards);
29583 				goto next_mp;
29584 			}
29585 
29586 			/* non-ipsec hw accel case */
29587 			if (io == NULL || !io->ipsec_out_accelerated) {
29588 				/* send it */
29589 				q = ire->ire_stq;
29590 				if (proc == IPP_FWD_OUT) {
29591 					UPDATE_IB_PKT_COUNT(ire);
29592 				} else {
29593 					UPDATE_OB_PKT_COUNT(ire);
29594 				}
29595 				ire->ire_last_used_time = lbolt;
29596 
29597 				if (flow_ctl_enabled || canputnext(q)) {
29598 					if (proc == IPP_FWD_OUT) {
29599 
29600 					BUMP_MIB(out_ill->ill_ip_mib,
29601 					    ipIfStatsHCOutForwDatagrams);
29602 
29603 					}
29604 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29605 					    pkt_len);
29606 
29607 					DTRACE_IP7(send, mblk_t *, first_mp,
29608 					    conn_t *, NULL, void_ip_t *, ipha,
29609 					    __dtrace_ipsr_ill_t *, out_ill,
29610 					    ipha_t *, ipha, ip6_t *, NULL, int,
29611 					    0);
29612 
29613 					ILL_SEND_TX(out_ill,
29614 					    ire, connp, first_mp, 0);
29615 				} else {
29616 					BUMP_MIB(out_ill->ill_ip_mib,
29617 					    ipIfStatsOutDiscards);
29618 					xmit_drop = B_TRUE;
29619 					freemsg(first_mp);
29620 				}
29621 			} else {
29622 				/*
29623 				 * Safety Pup says: make sure this
29624 				 *  is going to the right interface!
29625 				 */
29626 				ill_t *ill1 =
29627 				    (ill_t *)ire->ire_stq->q_ptr;
29628 				int ifindex =
29629 				    ill1->ill_phyint->phyint_ifindex;
29630 				if (ifindex !=
29631 				    io->ipsec_out_capab_ill_index) {
29632 					xmit_drop = B_TRUE;
29633 					freemsg(mp);
29634 				} else {
29635 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29636 					    pkt_len);
29637 
29638 					DTRACE_IP7(send, mblk_t *, first_mp,
29639 					    conn_t *, NULL, void_ip_t *, ipha,
29640 					    __dtrace_ipsr_ill_t *, ill1,
29641 					    ipha_t *, ipha, ip6_t *, NULL,
29642 					    int, 0);
29643 
29644 					ipsec_hw_putnext(ire->ire_stq, mp);
29645 				}
29646 			}
29647 next_mp:
29648 			mp = nxt_mp;
29649 		} /* while (mp != NULL) */
29650 		if (xmit_drop)
29651 			return (SEND_FAILED);
29652 		else
29653 			return (SEND_PASSED);
29654 
29655 	case ND_INITIAL:
29656 	case ND_INCOMPLETE:
29657 
29658 		/*
29659 		 * While we do send off packets to dests that
29660 		 * use fully-resolved CGTP routes, we do not
29661 		 * handle unresolved CGTP routes.
29662 		 */
29663 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29664 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29665 
29666 		if (mp != NULL) {
29667 			/* queue the packet */
29668 			nce_queue_mp_common(arpce, mp, B_FALSE);
29669 		}
29670 
29671 		if (arpce->nce_state == ND_INCOMPLETE) {
29672 			mutex_exit(&arpce->nce_lock);
29673 			DTRACE_PROBE3(ip__xmit__incomplete,
29674 			    (ire_t *), ire, (mblk_t *), mp,
29675 			    (ipsec_out_t *), io);
29676 			return (LOOKUP_IN_PROGRESS);
29677 		}
29678 
29679 		arpce->nce_state = ND_INCOMPLETE;
29680 		mutex_exit(&arpce->nce_lock);
29681 
29682 		/*
29683 		 * Note that ire_add() (called from ire_forward())
29684 		 * holds a ref on the ire until ARP is completed.
29685 		 */
29686 		ire_arpresolve(ire);
29687 		return (LOOKUP_IN_PROGRESS);
29688 	default:
29689 		ASSERT(0);
29690 		mutex_exit(&arpce->nce_lock);
29691 		return (LLHDR_RESLV_FAILED);
29692 	}
29693 }
29694 
29695 #undef	UPDATE_IP_MIB_OB_COUNTERS
29696 
29697 /*
29698  * Return B_TRUE if the buffers differ in length or content.
29699  * This is used for comparing extension header buffers.
29700  * Note that an extension header would be declared different
29701  * even if all that changed was the next header value in that header i.e.
29702  * what really changed is the next extension header.
29703  */
29704 boolean_t
29705 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29706     uint_t blen)
29707 {
29708 	if (!b_valid)
29709 		blen = 0;
29710 
29711 	if (alen != blen)
29712 		return (B_TRUE);
29713 	if (alen == 0)
29714 		return (B_FALSE);	/* Both zero length */
29715 	return (bcmp(abuf, bbuf, alen));
29716 }
29717 
29718 /*
29719  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29720  * Return B_FALSE if memory allocation fails - don't change any state!
29721  */
29722 boolean_t
29723 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29724     const void *src, uint_t srclen)
29725 {
29726 	void *dst;
29727 
29728 	if (!src_valid)
29729 		srclen = 0;
29730 
29731 	ASSERT(*dstlenp == 0);
29732 	if (src != NULL && srclen != 0) {
29733 		dst = mi_alloc(srclen, BPRI_MED);
29734 		if (dst == NULL)
29735 			return (B_FALSE);
29736 	} else {
29737 		dst = NULL;
29738 	}
29739 	if (*dstp != NULL)
29740 		mi_free(*dstp);
29741 	*dstp = dst;
29742 	*dstlenp = dst == NULL ? 0 : srclen;
29743 	return (B_TRUE);
29744 }
29745 
29746 /*
29747  * Replace what is in *dst, *dstlen with the source.
29748  * Assumes ip_allocbuf has already been called.
29749  */
29750 void
29751 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29752     const void *src, uint_t srclen)
29753 {
29754 	if (!src_valid)
29755 		srclen = 0;
29756 
29757 	ASSERT(*dstlenp == srclen);
29758 	if (src != NULL && srclen != 0)
29759 		bcopy(src, *dstp, srclen);
29760 }
29761 
29762 /*
29763  * Free the storage pointed to by the members of an ip6_pkt_t.
29764  */
29765 void
29766 ip6_pkt_free(ip6_pkt_t *ipp)
29767 {
29768 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29769 
29770 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29771 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
29772 		ipp->ipp_hopopts = NULL;
29773 		ipp->ipp_hopoptslen = 0;
29774 	}
29775 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29776 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29777 		ipp->ipp_rtdstopts = NULL;
29778 		ipp->ipp_rtdstoptslen = 0;
29779 	}
29780 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
29781 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
29782 		ipp->ipp_dstopts = NULL;
29783 		ipp->ipp_dstoptslen = 0;
29784 	}
29785 	if (ipp->ipp_fields & IPPF_RTHDR) {
29786 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29787 		ipp->ipp_rthdr = NULL;
29788 		ipp->ipp_rthdrlen = 0;
29789 	}
29790 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
29791 	    IPPF_RTHDR);
29792 }
29793 
29794 zoneid_t
29795 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_stack_t *ipst,
29796     zoneid_t lookup_zoneid)
29797 {
29798 	ire_t		*ire;
29799 	int		ire_flags = MATCH_IRE_TYPE;
29800 	zoneid_t	zoneid = ALL_ZONES;
29801 
29802 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
29803 		return (ALL_ZONES);
29804 
29805 	if (lookup_zoneid != ALL_ZONES)
29806 		ire_flags |= MATCH_IRE_ZONEONLY;
29807 	ire = ire_ctable_lookup(addr, NULL, IRE_LOCAL | IRE_LOOPBACK, NULL,
29808 	    lookup_zoneid, NULL, ire_flags, ipst);
29809 	if (ire != NULL) {
29810 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
29811 		ire_refrele(ire);
29812 	}
29813 	return (zoneid);
29814 }
29815 
29816 zoneid_t
29817 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
29818     ip_stack_t *ipst, zoneid_t lookup_zoneid)
29819 {
29820 	ire_t		*ire;
29821 	int		ire_flags = MATCH_IRE_TYPE;
29822 	zoneid_t	zoneid = ALL_ZONES;
29823 	ipif_t		*ipif_arg = NULL;
29824 
29825 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
29826 		return (ALL_ZONES);
29827 
29828 	if (IN6_IS_ADDR_LINKLOCAL(addr)) {
29829 		ire_flags |= MATCH_IRE_ILL;
29830 		ipif_arg = ill->ill_ipif;
29831 	}
29832 	if (lookup_zoneid != ALL_ZONES)
29833 		ire_flags |= MATCH_IRE_ZONEONLY;
29834 	ire = ire_ctable_lookup_v6(addr, NULL, IRE_LOCAL | IRE_LOOPBACK,
29835 	    ipif_arg, lookup_zoneid, NULL, ire_flags, ipst);
29836 	if (ire != NULL) {
29837 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
29838 		ire_refrele(ire);
29839 	}
29840 	return (zoneid);
29841 }
29842 
29843 /*
29844  * IP obserability hook support functions.
29845  */
29846 
29847 static void
29848 ipobs_init(ip_stack_t *ipst)
29849 {
29850 	ipst->ips_ipobs_enabled = B_FALSE;
29851 	list_create(&ipst->ips_ipobs_cb_list, sizeof (ipobs_cb_t),
29852 	    offsetof(ipobs_cb_t, ipobs_cbnext));
29853 	mutex_init(&ipst->ips_ipobs_cb_lock, NULL, MUTEX_DEFAULT, NULL);
29854 	ipst->ips_ipobs_cb_nwalkers = 0;
29855 	cv_init(&ipst->ips_ipobs_cb_cv, NULL, CV_DRIVER, NULL);
29856 }
29857 
29858 static void
29859 ipobs_fini(ip_stack_t *ipst)
29860 {
29861 	ipobs_cb_t *cb;
29862 
29863 	mutex_enter(&ipst->ips_ipobs_cb_lock);
29864 	while (ipst->ips_ipobs_cb_nwalkers != 0)
29865 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
29866 
29867 	while ((cb = list_head(&ipst->ips_ipobs_cb_list)) != NULL) {
29868 		list_remove(&ipst->ips_ipobs_cb_list, cb);
29869 		kmem_free(cb, sizeof (*cb));
29870 	}
29871 	list_destroy(&ipst->ips_ipobs_cb_list);
29872 	mutex_exit(&ipst->ips_ipobs_cb_lock);
29873 	mutex_destroy(&ipst->ips_ipobs_cb_lock);
29874 	cv_destroy(&ipst->ips_ipobs_cb_cv);
29875 }
29876 
29877 void
29878 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
29879     const ill_t *ill, int ipver, uint32_t hlen, ip_stack_t *ipst)
29880 {
29881 	mblk_t *mp2;
29882 	ipobs_cb_t *ipobs_cb;
29883 	ipobs_hook_data_t *ihd;
29884 	uint64_t grifindex = 0;
29885 
29886 	ASSERT(DB_TYPE(mp) == M_DATA);
29887 
29888 	if (IS_UNDER_IPMP(ill))
29889 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
29890 
29891 	mutex_enter(&ipst->ips_ipobs_cb_lock);
29892 	ipst->ips_ipobs_cb_nwalkers++;
29893 	mutex_exit(&ipst->ips_ipobs_cb_lock);
29894 	for (ipobs_cb = list_head(&ipst->ips_ipobs_cb_list); ipobs_cb != NULL;
29895 	    ipobs_cb = list_next(&ipst->ips_ipobs_cb_list, ipobs_cb)) {
29896 		mp2 = allocb(sizeof (ipobs_hook_data_t), BPRI_HI);
29897 		if (mp2 != NULL) {
29898 			ihd = (ipobs_hook_data_t *)mp2->b_rptr;
29899 			if (((ihd->ihd_mp = dupmsg(mp)) == NULL) &&
29900 			    ((ihd->ihd_mp = copymsg(mp)) == NULL)) {
29901 				freemsg(mp2);
29902 				continue;
29903 			}
29904 			ihd->ihd_mp->b_rptr += hlen;
29905 			ihd->ihd_htype = htype;
29906 			ihd->ihd_ipver = ipver;
29907 			ihd->ihd_zsrc = zsrc;
29908 			ihd->ihd_zdst = zdst;
29909 			ihd->ihd_ifindex = ill->ill_phyint->phyint_ifindex;
29910 			ihd->ihd_grifindex = grifindex;
29911 			ihd->ihd_stack = ipst->ips_netstack;
29912 			mp2->b_wptr += sizeof (*ihd);
29913 			ipobs_cb->ipobs_cbfunc(mp2);
29914 		}
29915 	}
29916 	mutex_enter(&ipst->ips_ipobs_cb_lock);
29917 	ipst->ips_ipobs_cb_nwalkers--;
29918 	if (ipst->ips_ipobs_cb_nwalkers == 0)
29919 		cv_broadcast(&ipst->ips_ipobs_cb_cv);
29920 	mutex_exit(&ipst->ips_ipobs_cb_lock);
29921 }
29922 
29923 void
29924 ipobs_register_hook(netstack_t *ns, pfv_t func)
29925 {
29926 	ipobs_cb_t   *cb;
29927 	ip_stack_t *ipst = ns->netstack_ip;
29928 
29929 	cb = kmem_alloc(sizeof (*cb), KM_SLEEP);
29930 
29931 	mutex_enter(&ipst->ips_ipobs_cb_lock);
29932 	while (ipst->ips_ipobs_cb_nwalkers != 0)
29933 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
29934 	ASSERT(ipst->ips_ipobs_cb_nwalkers == 0);
29935 
29936 	cb->ipobs_cbfunc = func;
29937 	list_insert_head(&ipst->ips_ipobs_cb_list, cb);
29938 	ipst->ips_ipobs_enabled = B_TRUE;
29939 	mutex_exit(&ipst->ips_ipobs_cb_lock);
29940 }
29941 
29942 void
29943 ipobs_unregister_hook(netstack_t *ns, pfv_t func)
29944 {
29945 	ipobs_cb_t	*curcb;
29946 	ip_stack_t	*ipst = ns->netstack_ip;
29947 
29948 	mutex_enter(&ipst->ips_ipobs_cb_lock);
29949 	while (ipst->ips_ipobs_cb_nwalkers != 0)
29950 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
29951 
29952 	for (curcb = list_head(&ipst->ips_ipobs_cb_list); curcb != NULL;
29953 	    curcb = list_next(&ipst->ips_ipobs_cb_list, curcb)) {
29954 		if (func == curcb->ipobs_cbfunc) {
29955 			list_remove(&ipst->ips_ipobs_cb_list, curcb);
29956 			kmem_free(curcb, sizeof (*curcb));
29957 			break;
29958 		}
29959 	}
29960 	if (list_is_empty(&ipst->ips_ipobs_cb_list))
29961 		ipst->ips_ipobs_enabled = B_FALSE;
29962 	mutex_exit(&ipst->ips_ipobs_cb_lock);
29963 }
29964