xref: /titanic_52/usr/src/uts/common/inet/ip/ip.c (revision 62615d1b6cd28c7db6dea1cdad6d219ffbcd7881)
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 		    mblk_t *);
727 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
728 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
729 		    zoneid_t, ip_stack_t *);
730 
731 static void	conn_drain_init(ip_stack_t *);
732 static void	conn_drain_fini(ip_stack_t *);
733 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
734 
735 static void	conn_walk_drain(ip_stack_t *);
736 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
737     zoneid_t);
738 
739 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
740 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
741 static void	ip_stack_fini(netstackid_t stackid, void *arg);
742 
743 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
744     zoneid_t);
745 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
746     void *dummy_arg);
747 
748 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
749 
750 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
751     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
752     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
753 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
754 
755 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
756 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
757     caddr_t, cred_t *);
758 extern int	ip_helper_stream_setup(queue_t *, dev_t *, int, int,
759     cred_t *, boolean_t);
760 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
761     caddr_t cp, cred_t *cr);
762 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
763     cred_t *);
764 static int	ip_squeue_switch(int);
765 
766 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
767 static void	ip_kstat_fini(netstackid_t, kstat_t *);
768 static int	ip_kstat_update(kstat_t *kp, int rw);
769 static void	*icmp_kstat_init(netstackid_t);
770 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
771 static int	icmp_kstat_update(kstat_t *kp, int rw);
772 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
773 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
774 
775 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
776 
777 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
778     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
779 
780 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
781     ipha_t *, ill_t *, boolean_t, boolean_t);
782 
783 static void ipobs_init(ip_stack_t *);
784 static void ipobs_fini(ip_stack_t *);
785 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
786 
787 /* How long, in seconds, we allow frags to hang around. */
788 #define	IP_FRAG_TIMEOUT	15
789 
790 /*
791  * Threshold which determines whether MDT should be used when
792  * generating IP fragments; payload size must be greater than
793  * this threshold for MDT to take place.
794  */
795 #define	IP_WPUT_FRAG_MDT_MIN	32768
796 
797 /* Setable in /etc/system only */
798 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
799 
800 static long ip_rput_pullups;
801 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
802 
803 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
804 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
805 
806 int	ip_debug;
807 
808 #ifdef DEBUG
809 uint32_t ipsechw_debug = 0;
810 #endif
811 
812 /*
813  * Multirouting/CGTP stuff
814  */
815 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
816 
817 /*
818  * XXX following really should only be in a header. Would need more
819  * header and .c clean up first.
820  */
821 extern optdb_obj_t	ip_opt_obj;
822 
823 ulong_t ip_squeue_enter_unbound = 0;
824 
825 /*
826  * Named Dispatch Parameter Table.
827  * All of these are alterable, within the min/max values given, at run time.
828  */
829 static ipparam_t	lcl_param_arr[] = {
830 	/* min	max	value	name */
831 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
832 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
833 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
834 	{  0,	1,	0,	"ip_respond_to_timestamp"},
835 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
836 	{  0,	1,	1,	"ip_send_redirects"},
837 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
838 	{  0,	10,	0,	"ip_mrtdebug"},
839 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
840 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
841 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
842 	{  1,	255,	255,	"ip_def_ttl" },
843 	{  0,	1,	0,	"ip_forward_src_routed"},
844 	{  0,	256,	32,	"ip_wroff_extra" },
845 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
846 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
847 	{  0,	1,	1,	"ip_path_mtu_discovery" },
848 	{  0,	240,	30,	"ip_ignore_delete_time" },
849 	{  0,	1,	0,	"ip_ignore_redirect" },
850 	{  0,	1,	1,	"ip_output_queue" },
851 	{  1,	254,	1,	"ip_broadcast_ttl" },
852 	{  0,	99999,	100,	"ip_icmp_err_interval" },
853 	{  1,	99999,	10,	"ip_icmp_err_burst" },
854 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
855 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
856 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
857 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
858 	{  0,	1,	1,	"icmp_accept_clear_messages" },
859 	{  0,	1,	1,	"igmp_accept_clear_messages" },
860 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
861 				"ip_ndp_delay_first_probe_time"},
862 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
863 				"ip_ndp_max_unicast_solicit"},
864 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
865 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
866 	{  0,	1,	0,	"ip6_forward_src_routed"},
867 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
868 	{  0,	1,	1,	"ip6_send_redirects"},
869 	{  0,	1,	0,	"ip6_ignore_redirect" },
870 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
871 
872 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
873 
874 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
875 
876 	{  0,	1,	1,	"pim_accept_clear_messages" },
877 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
878 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
879 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
880 	{  0,	15,	0,	"ip_policy_mask" },
881 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
882 	{  0,	255,	1,	"ip_multirt_ttl" },
883 	{  0,	1,	1,	"ip_multidata_outbound" },
884 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
885 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
886 	{  0,	1000,	1,	"ip_max_temp_defend" },
887 	{  0,	1000,	3,	"ip_max_defend" },
888 	{  0,	999999,	30,	"ip_defend_interval" },
889 	{  0,	3600000, 300000, "ip_dup_recovery" },
890 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
891 	{  0,	1,	1,	"ip_lso_outbound" },
892 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
893 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
894 	{ 68,	65535,	576,	"ip_pmtu_min" },
895 #ifdef DEBUG
896 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
897 #else
898 	{  0,	0,	0,	"" },
899 #endif
900 };
901 
902 /*
903  * Extended NDP table
904  * The addresses for the first two are filled in to be ips_ip_g_forward
905  * and ips_ipv6_forward at init time.
906  */
907 static ipndp_t	lcl_ndp_arr[] = {
908 	/* getf			setf		data			name */
909 #define	IPNDP_IP_FORWARDING_OFFSET	0
910 	{  ip_param_generic_get,	ip_forward_set,	NULL,
911 	    "ip_forwarding" },
912 #define	IPNDP_IP6_FORWARDING_OFFSET	1
913 	{  ip_param_generic_get,	ip_forward_set,	NULL,
914 	    "ip6_forwarding" },
915 	{  ip_ill_report,	NULL,		NULL,
916 	    "ip_ill_status" },
917 	{  ip_ipif_report,	NULL,		NULL,
918 	    "ip_ipif_status" },
919 	{  ip_conn_report,	NULL,		NULL,
920 	    "ip_conn_status" },
921 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
922 	    "ip_rput_pullups" },
923 	{  ip_srcid_report,	NULL,		NULL,
924 	    "ip_srcid_status" },
925 	{ ip_param_generic_get, ip_input_proc_set,
926 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
927 	{ ip_param_generic_get, ip_int_set,
928 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
929 #define	IPNDP_CGTP_FILTER_OFFSET	9
930 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
931 	    "ip_cgtp_filter" },
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 			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, msg_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 	/* Make sure we propagate the cred/label for TX */
3332 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3333 	if (mp1 == NULL) {
3334 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3335 		freemsg(ipsec_mp);
3336 		return;
3337 	}
3338 	mp1->b_cont = mp;
3339 	mp = mp1;
3340 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3341 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3342 	    io->ipsec_out_type == IPSEC_OUT);
3343 	ipsec_mp->b_cont = mp;
3344 
3345 	/*
3346 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3347 	 * node generates be accepted in peace by all on-host destinations.
3348 	 * If we do NOT assume that all on-host destinations trust
3349 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3350 	 * (Look for ipsec_out_icmp_loopback).
3351 	 */
3352 	io->ipsec_out_icmp_loopback = B_TRUE;
3353 
3354 	ipha = (ipha_t *)mp->b_rptr;
3355 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3356 	*ipha = icmp_ipha;
3357 	ipha->ipha_src = src;
3358 	ipha->ipha_dst = dst;
3359 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3360 	msg_len += sizeof (icmp_ipha) + len;
3361 	if (msg_len > IP_MAXPACKET) {
3362 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3363 		msg_len = IP_MAXPACKET;
3364 	}
3365 	ipha->ipha_length = htons((uint16_t)msg_len);
3366 	icmph = (icmph_t *)&ipha[1];
3367 	bcopy(stuff, icmph, len);
3368 	icmph->icmph_checksum = 0;
3369 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3370 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3371 	put(q, ipsec_mp);
3372 }
3373 
3374 /*
3375  * Determine if an ICMP error packet can be sent given the rate limit.
3376  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3377  * in milliseconds) and a burst size. Burst size number of packets can
3378  * be sent arbitrarely closely spaced.
3379  * The state is tracked using two variables to implement an approximate
3380  * token bucket filter:
3381  *	icmp_pkt_err_last - lbolt value when the last burst started
3382  *	icmp_pkt_err_sent - number of packets sent in current burst
3383  */
3384 boolean_t
3385 icmp_err_rate_limit(ip_stack_t *ipst)
3386 {
3387 	clock_t now = TICK_TO_MSEC(lbolt);
3388 	uint_t refilled; /* Number of packets refilled in tbf since last */
3389 	/* Guard against changes by loading into local variable */
3390 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3391 
3392 	if (err_interval == 0)
3393 		return (B_FALSE);
3394 
3395 	if (ipst->ips_icmp_pkt_err_last > now) {
3396 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3397 		ipst->ips_icmp_pkt_err_last = 0;
3398 		ipst->ips_icmp_pkt_err_sent = 0;
3399 	}
3400 	/*
3401 	 * If we are in a burst update the token bucket filter.
3402 	 * Update the "last" time to be close to "now" but make sure
3403 	 * we don't loose precision.
3404 	 */
3405 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3406 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3407 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3408 			ipst->ips_icmp_pkt_err_sent = 0;
3409 		} else {
3410 			ipst->ips_icmp_pkt_err_sent -= refilled;
3411 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3412 		}
3413 	}
3414 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3415 		/* Start of new burst */
3416 		ipst->ips_icmp_pkt_err_last = now;
3417 	}
3418 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3419 		ipst->ips_icmp_pkt_err_sent++;
3420 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3421 		    ipst->ips_icmp_pkt_err_sent));
3422 		return (B_FALSE);
3423 	}
3424 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3425 	return (B_TRUE);
3426 }
3427 
3428 /*
3429  * Check if it is ok to send an IPv4 ICMP error packet in
3430  * response to the IPv4 packet in mp.
3431  * Free the message and return null if no
3432  * ICMP error packet should be sent.
3433  */
3434 static mblk_t *
3435 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3436 {
3437 	icmph_t	*icmph;
3438 	ipha_t	*ipha;
3439 	uint_t	len_needed;
3440 	ire_t	*src_ire;
3441 	ire_t	*dst_ire;
3442 
3443 	if (!mp)
3444 		return (NULL);
3445 	ipha = (ipha_t *)mp->b_rptr;
3446 	if (ip_csum_hdr(ipha)) {
3447 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3448 		freemsg(mp);
3449 		return (NULL);
3450 	}
3451 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3452 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3453 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3454 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3455 	if (src_ire != NULL || dst_ire != NULL ||
3456 	    CLASSD(ipha->ipha_dst) ||
3457 	    CLASSD(ipha->ipha_src) ||
3458 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3459 		/* Note: only errors to the fragment with offset 0 */
3460 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3461 		freemsg(mp);
3462 		if (src_ire != NULL)
3463 			ire_refrele(src_ire);
3464 		if (dst_ire != NULL)
3465 			ire_refrele(dst_ire);
3466 		return (NULL);
3467 	}
3468 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3469 		/*
3470 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3471 		 * errors in response to any ICMP errors.
3472 		 */
3473 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3474 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3475 			if (!pullupmsg(mp, len_needed)) {
3476 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3477 				freemsg(mp);
3478 				return (NULL);
3479 			}
3480 			ipha = (ipha_t *)mp->b_rptr;
3481 		}
3482 		icmph = (icmph_t *)
3483 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3484 		switch (icmph->icmph_type) {
3485 		case ICMP_DEST_UNREACHABLE:
3486 		case ICMP_SOURCE_QUENCH:
3487 		case ICMP_TIME_EXCEEDED:
3488 		case ICMP_PARAM_PROBLEM:
3489 		case ICMP_REDIRECT:
3490 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3491 			freemsg(mp);
3492 			return (NULL);
3493 		default:
3494 			break;
3495 		}
3496 	}
3497 	/*
3498 	 * If this is a labeled system, then check to see if we're allowed to
3499 	 * send a response to this particular sender.  If not, then just drop.
3500 	 */
3501 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3502 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3503 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3504 		freemsg(mp);
3505 		return (NULL);
3506 	}
3507 	if (icmp_err_rate_limit(ipst)) {
3508 		/*
3509 		 * Only send ICMP error packets every so often.
3510 		 * This should be done on a per port/source basis,
3511 		 * but for now this will suffice.
3512 		 */
3513 		freemsg(mp);
3514 		return (NULL);
3515 	}
3516 	return (mp);
3517 }
3518 
3519 /*
3520  * Generate an ICMP redirect message.
3521  */
3522 static void
3523 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3524 {
3525 	icmph_t	icmph;
3526 
3527 	/*
3528 	 * We are called from ip_rput where we could
3529 	 * not have attached an IPSEC_IN.
3530 	 */
3531 	ASSERT(mp->b_datap->db_type == M_DATA);
3532 
3533 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3534 		return;
3535 	}
3536 
3537 	bzero(&icmph, sizeof (icmph_t));
3538 	icmph.icmph_type = ICMP_REDIRECT;
3539 	icmph.icmph_code = 1;
3540 	icmph.icmph_rd_gateway = gateway;
3541 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3542 	/* Redirects sent by router, and router is global zone */
3543 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3544 }
3545 
3546 /*
3547  * Generate an ICMP time exceeded message.
3548  */
3549 void
3550 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3551     ip_stack_t *ipst)
3552 {
3553 	icmph_t	icmph;
3554 	boolean_t mctl_present;
3555 	mblk_t *first_mp;
3556 
3557 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3558 
3559 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3560 		if (mctl_present)
3561 			freeb(first_mp);
3562 		return;
3563 	}
3564 
3565 	bzero(&icmph, sizeof (icmph_t));
3566 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3567 	icmph.icmph_code = code;
3568 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3569 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3570 	    ipst);
3571 }
3572 
3573 /*
3574  * Generate an ICMP unreachable message.
3575  */
3576 void
3577 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3578     ip_stack_t *ipst)
3579 {
3580 	icmph_t	icmph;
3581 	mblk_t *first_mp;
3582 	boolean_t mctl_present;
3583 
3584 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3585 
3586 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3587 		if (mctl_present)
3588 			freeb(first_mp);
3589 		return;
3590 	}
3591 
3592 	bzero(&icmph, sizeof (icmph_t));
3593 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3594 	icmph.icmph_code = code;
3595 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3596 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3597 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3598 	    zoneid, ipst);
3599 }
3600 
3601 /*
3602  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3603  * duplicate.  As long as someone else holds the address, the interface will
3604  * stay down.  When that conflict goes away, the interface is brought back up.
3605  * This is done so that accidental shutdowns of addresses aren't made
3606  * permanent.  Your server will recover from a failure.
3607  *
3608  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3609  * user space process (dhcpagent).
3610  *
3611  * Recovery completes if ARP reports that the address is now ours (via
3612  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3613  *
3614  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3615  */
3616 static void
3617 ipif_dup_recovery(void *arg)
3618 {
3619 	ipif_t *ipif = arg;
3620 	ill_t *ill = ipif->ipif_ill;
3621 	mblk_t *arp_add_mp;
3622 	mblk_t *arp_del_mp;
3623 	ip_stack_t *ipst = ill->ill_ipst;
3624 
3625 	ipif->ipif_recovery_id = 0;
3626 
3627 	/*
3628 	 * No lock needed for moving or condemned check, as this is just an
3629 	 * optimization.
3630 	 */
3631 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3632 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3633 	    (ipif->ipif_state_flags & (IPIF_CONDEMNED))) {
3634 		/* No reason to try to bring this address back. */
3635 		return;
3636 	}
3637 
3638 	/* ACE_F_UNVERIFIED restarts DAD */
3639 	if ((arp_add_mp = ipif_area_alloc(ipif, ACE_F_UNVERIFIED)) == NULL)
3640 		goto alloc_fail;
3641 
3642 	if (ipif->ipif_arp_del_mp == NULL) {
3643 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3644 			goto alloc_fail;
3645 		ipif->ipif_arp_del_mp = arp_del_mp;
3646 	}
3647 
3648 	putnext(ill->ill_rq, arp_add_mp);
3649 	return;
3650 
3651 alloc_fail:
3652 	/*
3653 	 * On allocation failure, just restart the timer.  Note that the ipif
3654 	 * is down here, so no other thread could be trying to start a recovery
3655 	 * timer.  The ill_lock protects the condemned flag and the recovery
3656 	 * timer ID.
3657 	 */
3658 	freemsg(arp_add_mp);
3659 	mutex_enter(&ill->ill_lock);
3660 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3661 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3662 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3663 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3664 	}
3665 	mutex_exit(&ill->ill_lock);
3666 }
3667 
3668 /*
3669  * This is for exclusive changes due to ARP.  Either tear down an interface due
3670  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3671  */
3672 /* ARGSUSED */
3673 static void
3674 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3675 {
3676 	ill_t	*ill = rq->q_ptr;
3677 	arh_t *arh;
3678 	ipaddr_t src;
3679 	ipif_t	*ipif;
3680 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3681 	char hbuf[MAC_STR_LEN];
3682 	char sbuf[INET_ADDRSTRLEN];
3683 	const char *failtype;
3684 	boolean_t bring_up;
3685 	ip_stack_t *ipst = ill->ill_ipst;
3686 
3687 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3688 	case AR_CN_READY:
3689 		failtype = NULL;
3690 		bring_up = B_TRUE;
3691 		break;
3692 	case AR_CN_FAILED:
3693 		failtype = "in use";
3694 		bring_up = B_FALSE;
3695 		break;
3696 	default:
3697 		failtype = "claimed";
3698 		bring_up = B_FALSE;
3699 		break;
3700 	}
3701 
3702 	arh = (arh_t *)mp->b_cont->b_rptr;
3703 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3704 
3705 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3706 	    sizeof (hbuf));
3707 	(void) ip_dot_addr(src, sbuf);
3708 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3709 
3710 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3711 		    ipif->ipif_lcl_addr != src) {
3712 			continue;
3713 		}
3714 
3715 		/*
3716 		 * If we failed on a recovery probe, then restart the timer to
3717 		 * try again later.
3718 		 */
3719 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3720 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3721 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3722 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3723 		    ipst->ips_ip_dup_recovery > 0 &&
3724 		    ipif->ipif_recovery_id == 0) {
3725 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3726 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3727 			continue;
3728 		}
3729 
3730 		/*
3731 		 * If what we're trying to do has already been done, then do
3732 		 * nothing.
3733 		 */
3734 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3735 			continue;
3736 
3737 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3738 
3739 		if (failtype == NULL) {
3740 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3741 			    ibuf);
3742 		} else {
3743 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3744 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3745 		}
3746 
3747 		if (bring_up) {
3748 			ASSERT(ill->ill_dl_up);
3749 			/*
3750 			 * Free up the ARP delete message so we can allocate
3751 			 * a fresh one through the normal path.
3752 			 */
3753 			freemsg(ipif->ipif_arp_del_mp);
3754 			ipif->ipif_arp_del_mp = NULL;
3755 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3756 			    EINPROGRESS) {
3757 				ipif->ipif_addr_ready = 1;
3758 				(void) ipif_up_done(ipif);
3759 				ASSERT(ill->ill_move_ipif == NULL);
3760 			}
3761 			continue;
3762 		}
3763 
3764 		mutex_enter(&ill->ill_lock);
3765 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3766 		ipif->ipif_flags |= IPIF_DUPLICATE;
3767 		ill->ill_ipif_dup_count++;
3768 		mutex_exit(&ill->ill_lock);
3769 		/*
3770 		 * Already exclusive on the ill; no need to handle deferred
3771 		 * processing here.
3772 		 */
3773 		(void) ipif_down(ipif, NULL, NULL);
3774 		ipif_down_tail(ipif);
3775 		mutex_enter(&ill->ill_lock);
3776 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3777 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3778 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3779 		    ipst->ips_ip_dup_recovery > 0) {
3780 			ASSERT(ipif->ipif_recovery_id == 0);
3781 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3782 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3783 		}
3784 		mutex_exit(&ill->ill_lock);
3785 	}
3786 	freemsg(mp);
3787 }
3788 
3789 /* ARGSUSED */
3790 static void
3791 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3792 {
3793 	ill_t	*ill = rq->q_ptr;
3794 	arh_t *arh;
3795 	ipaddr_t src;
3796 	ipif_t	*ipif;
3797 
3798 	arh = (arh_t *)mp->b_cont->b_rptr;
3799 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3800 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3801 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3802 			(void) ipif_resolver_up(ipif, Res_act_defend);
3803 	}
3804 	freemsg(mp);
3805 }
3806 
3807 /*
3808  * News from ARP.  ARP sends notification of interesting events down
3809  * to its clients using M_CTL messages with the interesting ARP packet
3810  * attached via b_cont.
3811  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3812  * queue as opposed to ARP sending the message to all the clients, i.e. all
3813  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3814  * table if a cache IRE is found to delete all the entries for the address in
3815  * the packet.
3816  */
3817 static void
3818 ip_arp_news(queue_t *q, mblk_t *mp)
3819 {
3820 	arcn_t		*arcn;
3821 	arh_t		*arh;
3822 	ire_t		*ire = NULL;
3823 	char		hbuf[MAC_STR_LEN];
3824 	char		sbuf[INET_ADDRSTRLEN];
3825 	ipaddr_t	src;
3826 	in6_addr_t	v6src;
3827 	boolean_t	isv6 = B_FALSE;
3828 	ipif_t		*ipif;
3829 	ill_t		*ill;
3830 	ip_stack_t	*ipst;
3831 
3832 	if (CONN_Q(q)) {
3833 		conn_t *connp = Q_TO_CONN(q);
3834 
3835 		ipst = connp->conn_netstack->netstack_ip;
3836 	} else {
3837 		ill_t *ill = (ill_t *)q->q_ptr;
3838 
3839 		ipst = ill->ill_ipst;
3840 	}
3841 
3842 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3843 		if (q->q_next) {
3844 			putnext(q, mp);
3845 		} else
3846 			freemsg(mp);
3847 		return;
3848 	}
3849 	arh = (arh_t *)mp->b_cont->b_rptr;
3850 	/* Is it one we are interested in? */
3851 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3852 		isv6 = B_TRUE;
3853 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3854 		    IPV6_ADDR_LEN);
3855 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3856 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3857 		    IP_ADDR_LEN);
3858 	} else {
3859 		freemsg(mp);
3860 		return;
3861 	}
3862 
3863 	ill = q->q_ptr;
3864 
3865 	arcn = (arcn_t *)mp->b_rptr;
3866 	switch (arcn->arcn_code) {
3867 	case AR_CN_BOGON:
3868 		/*
3869 		 * Someone is sending ARP packets with a source protocol
3870 		 * address that we have published and for which we believe our
3871 		 * entry is authoritative and (when ill_arp_extend is set)
3872 		 * verified to be unique on the network.
3873 		 *
3874 		 * The ARP module internally handles the cases where the sender
3875 		 * is just probing (for DAD) and where the hardware address of
3876 		 * a non-authoritative entry has changed.  Thus, these are the
3877 		 * real conflicts, and we have to do resolution.
3878 		 *
3879 		 * We back away quickly from the address if it's from DHCP or
3880 		 * otherwise temporary and hasn't been used recently (or at
3881 		 * all).  We'd like to include "deprecated" addresses here as
3882 		 * well (as there's no real reason to defend something we're
3883 		 * discarding), but IPMP "reuses" this flag to mean something
3884 		 * other than the standard meaning.
3885 		 *
3886 		 * If the ARP module above is not extended (meaning that it
3887 		 * doesn't know how to defend the address), then we just log
3888 		 * the problem as we always did and continue on.  It's not
3889 		 * right, but there's little else we can do, and those old ATM
3890 		 * users are going away anyway.
3891 		 */
3892 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3893 		    hbuf, sizeof (hbuf));
3894 		(void) ip_dot_addr(src, sbuf);
3895 		if (isv6) {
3896 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3897 			    ipst);
3898 		} else {
3899 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3900 		}
3901 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3902 			uint32_t now;
3903 			uint32_t maxage;
3904 			clock_t lused;
3905 			uint_t maxdefense;
3906 			uint_t defs;
3907 
3908 			/*
3909 			 * First, figure out if this address hasn't been used
3910 			 * in a while.  If it hasn't, then it's a better
3911 			 * candidate for abandoning.
3912 			 */
3913 			ipif = ire->ire_ipif;
3914 			ASSERT(ipif != NULL);
3915 			now = gethrestime_sec();
3916 			maxage = now - ire->ire_create_time;
3917 			if (maxage > ipst->ips_ip_max_temp_idle)
3918 				maxage = ipst->ips_ip_max_temp_idle;
3919 			lused = drv_hztousec(ddi_get_lbolt() -
3920 			    ire->ire_last_used_time) / MICROSEC + 1;
3921 			if (lused >= maxage && (ipif->ipif_flags &
3922 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
3923 				maxdefense = ipst->ips_ip_max_temp_defend;
3924 			else
3925 				maxdefense = ipst->ips_ip_max_defend;
3926 
3927 			/*
3928 			 * Now figure out how many times we've defended
3929 			 * ourselves.  Ignore defenses that happened long in
3930 			 * the past.
3931 			 */
3932 			mutex_enter(&ire->ire_lock);
3933 			if ((defs = ire->ire_defense_count) > 0 &&
3934 			    now - ire->ire_defense_time >
3935 			    ipst->ips_ip_defend_interval) {
3936 				ire->ire_defense_count = defs = 0;
3937 			}
3938 			ire->ire_defense_count++;
3939 			ire->ire_defense_time = now;
3940 			mutex_exit(&ire->ire_lock);
3941 			ill_refhold(ill);
3942 			ire_refrele(ire);
3943 
3944 			/*
3945 			 * If we've defended ourselves too many times already,
3946 			 * then give up and tear down the interface(s) using
3947 			 * this address.  Otherwise, defend by sending out a
3948 			 * gratuitous ARP.
3949 			 */
3950 			if (defs >= maxdefense && ill->ill_arp_extend) {
3951 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
3952 				    B_FALSE);
3953 			} else {
3954 				cmn_err(CE_WARN,
3955 				    "node %s is using our IP address %s on %s",
3956 				    hbuf, sbuf, ill->ill_name);
3957 				/*
3958 				 * If this is an old (ATM) ARP module, then
3959 				 * don't try to defend the address.  Remain
3960 				 * compatible with the old behavior.  Defend
3961 				 * only with new ARP.
3962 				 */
3963 				if (ill->ill_arp_extend) {
3964 					qwriter_ip(ill, q, mp, ip_arp_defend,
3965 					    NEW_OP, B_FALSE);
3966 				} else {
3967 					ill_refrele(ill);
3968 				}
3969 			}
3970 			return;
3971 		}
3972 		cmn_err(CE_WARN,
3973 		    "proxy ARP problem?  Node '%s' is using %s on %s",
3974 		    hbuf, sbuf, ill->ill_name);
3975 		if (ire != NULL)
3976 			ire_refrele(ire);
3977 		break;
3978 	case AR_CN_ANNOUNCE:
3979 		if (isv6) {
3980 			/*
3981 			 * For XRESOLV interfaces.
3982 			 * Delete the IRE cache entry and NCE for this
3983 			 * v6 address
3984 			 */
3985 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
3986 			/*
3987 			 * If v6src is a non-zero, it's a router address
3988 			 * as below. Do the same sort of thing to clean
3989 			 * out off-net IRE_CACHE entries that go through
3990 			 * the router.
3991 			 */
3992 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
3993 				ire_walk_v6(ire_delete_cache_gw_v6,
3994 				    (char *)&v6src, ALL_ZONES, ipst);
3995 			}
3996 		} else {
3997 			nce_hw_map_t hwm;
3998 
3999 			/*
4000 			 * ARP gives us a copy of any packet where it thinks
4001 			 * the address has changed, so that we can update our
4002 			 * caches.  We're responsible for caching known answers
4003 			 * in the current design.  We check whether the
4004 			 * hardware address really has changed in all of our
4005 			 * entries that have cached this mapping, and if so, we
4006 			 * blow them away.  This way we will immediately pick
4007 			 * up the rare case of a host changing hardware
4008 			 * address.
4009 			 */
4010 			if (src == 0)
4011 				break;
4012 			hwm.hwm_addr = src;
4013 			hwm.hwm_hwlen = arh->arh_hlen;
4014 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4015 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4016 			ndp_walk_common(ipst->ips_ndp4, NULL,
4017 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4018 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4019 		}
4020 		break;
4021 	case AR_CN_READY:
4022 		/* No external v6 resolver has a contract to use this */
4023 		if (isv6)
4024 			break;
4025 		/* If the link is down, we'll retry this later */
4026 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4027 			break;
4028 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4029 		    NULL, NULL, ipst);
4030 		if (ipif != NULL) {
4031 			/*
4032 			 * If this is a duplicate recovery, then we now need to
4033 			 * go exclusive to bring this thing back up.
4034 			 */
4035 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4036 			    IPIF_DUPLICATE) {
4037 				ipif_refrele(ipif);
4038 				ill_refhold(ill);
4039 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4040 				    B_FALSE);
4041 				return;
4042 			}
4043 			/*
4044 			 * If this is the first notice that this address is
4045 			 * ready, then let the user know now.
4046 			 */
4047 			if ((ipif->ipif_flags & IPIF_UP) &&
4048 			    !ipif->ipif_addr_ready) {
4049 				ipif_mask_reply(ipif);
4050 				ipif_up_notify(ipif);
4051 			}
4052 			ipif->ipif_addr_ready = 1;
4053 			ipif_refrele(ipif);
4054 		}
4055 		ire = ire_cache_lookup(src, ALL_ZONES, msg_getlabel(mp), ipst);
4056 		if (ire != NULL) {
4057 			ire->ire_defense_count = 0;
4058 			ire_refrele(ire);
4059 		}
4060 		break;
4061 	case AR_CN_FAILED:
4062 		/* No external v6 resolver has a contract to use this */
4063 		if (isv6)
4064 			break;
4065 		ill_refhold(ill);
4066 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4067 		return;
4068 	}
4069 	freemsg(mp);
4070 }
4071 
4072 /*
4073  * Create a mblk suitable for carrying the interface index and/or source link
4074  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4075  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4076  * application.
4077  */
4078 mblk_t *
4079 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4080     ip_stack_t *ipst)
4081 {
4082 	mblk_t		*mp;
4083 	ip_pktinfo_t	*pinfo;
4084 	ipha_t 		*ipha;
4085 	struct ether_header *pether;
4086 	boolean_t	ipmp_ill_held = B_FALSE;
4087 
4088 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4089 	if (mp == NULL) {
4090 		ip1dbg(("ip_add_info: allocation failure.\n"));
4091 		return (data_mp);
4092 	}
4093 
4094 	ipha = (ipha_t *)data_mp->b_rptr;
4095 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4096 	bzero(pinfo, sizeof (ip_pktinfo_t));
4097 	pinfo->ip_pkt_flags = (uchar_t)flags;
4098 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4099 
4100 	pether = (struct ether_header *)((char *)ipha
4101 	    - sizeof (struct ether_header));
4102 
4103 	/*
4104 	 * Make sure the interface is an ethernet type, since this option
4105 	 * is currently supported only on this type of interface. Also make
4106 	 * sure we are pointing correctly above db_base.
4107 	 */
4108 	if ((flags & IPF_RECVSLLA) &&
4109 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4110 	    (ill->ill_type == IFT_ETHER) &&
4111 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4112 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4113 		bcopy(pether->ether_shost.ether_addr_octet,
4114 		    pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4115 	} else {
4116 		/*
4117 		 * Clear the bit. Indicate to upper layer that IP is not
4118 		 * sending this ancillary info.
4119 		 */
4120 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4121 	}
4122 
4123 	/*
4124 	 * If `ill' is in an IPMP group, use the IPMP ill to determine
4125 	 * IPF_RECVIF and IPF_RECVADDR.  (This currently assumes that
4126 	 * IPF_RECVADDR support on test addresses is not needed.)
4127 	 *
4128 	 * Note that `ill' may already be an IPMP ill if e.g. we're
4129 	 * processing a packet looped back to an IPMP data address
4130 	 * (since those IRE_LOCALs are tied to IPMP ills).
4131 	 */
4132 	if (IS_UNDER_IPMP(ill)) {
4133 		if ((ill = ipmp_ill_hold_ipmp_ill(ill)) == NULL) {
4134 			ip1dbg(("ip_add_info: cannot hold IPMP ill.\n"));
4135 			freemsg(mp);
4136 			return (data_mp);
4137 		}
4138 		ipmp_ill_held = B_TRUE;
4139 	}
4140 
4141 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4142 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4143 	if (flags & IPF_RECVADDR) {
4144 		ipif_t	*ipif;
4145 		ire_t	*ire;
4146 
4147 		/*
4148 		 * Only valid for V4
4149 		 */
4150 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4151 		    (IPV4_VERSION << 4));
4152 
4153 		ipif = ipif_get_next_ipif(NULL, ill);
4154 		if (ipif != NULL) {
4155 			/*
4156 			 * Since a decision has already been made to deliver the
4157 			 * packet, there is no need to test for SECATTR and
4158 			 * ZONEONLY.
4159 			 * When a multicast packet is transmitted
4160 			 * a cache entry is created for the multicast address.
4161 			 * When delivering a copy of the packet or when new
4162 			 * packets are received we do not want to match on the
4163 			 * cached entry so explicitly match on
4164 			 * IRE_LOCAL and IRE_LOOPBACK
4165 			 */
4166 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4167 			    IRE_LOCAL | IRE_LOOPBACK,
4168 			    ipif, zoneid, NULL,
4169 			    MATCH_IRE_TYPE | MATCH_IRE_ILL, ipst);
4170 			if (ire == NULL) {
4171 				/*
4172 				 * packet must have come on a different
4173 				 * interface.
4174 				 * Since a decision has already been made to
4175 				 * deliver the packet, there is no need to test
4176 				 * for SECATTR and ZONEONLY.
4177 				 * Only match on local and broadcast ire's.
4178 				 * See detailed comment above.
4179 				 */
4180 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4181 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4182 				    NULL, MATCH_IRE_TYPE, ipst);
4183 			}
4184 
4185 			if (ire == NULL) {
4186 				/*
4187 				 * This is either a multicast packet or
4188 				 * the address has been removed since
4189 				 * the packet was received.
4190 				 * Return INADDR_ANY so that normal source
4191 				 * selection occurs for the response.
4192 				 */
4193 
4194 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4195 			} else {
4196 				pinfo->ip_pkt_match_addr.s_addr =
4197 				    ire->ire_src_addr;
4198 				ire_refrele(ire);
4199 			}
4200 			ipif_refrele(ipif);
4201 		} else {
4202 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4203 		}
4204 	}
4205 
4206 	if (ipmp_ill_held)
4207 		ill_refrele(ill);
4208 
4209 	mp->b_datap->db_type = M_CTL;
4210 	mp->b_wptr += sizeof (ip_pktinfo_t);
4211 	mp->b_cont = data_mp;
4212 
4213 	return (mp);
4214 }
4215 
4216 /*
4217  * Used to determine the most accurate cred_t to use for TX.
4218  * First priority is SCM_UCRED having set the label in the message,
4219  * which is used for MLP on UDP. Second priority is the peers label (aka
4220  * conn_peercred), which is needed for MLP on TCP/SCTP. Last priority is the
4221  * open credentials.
4222  */
4223 cred_t *
4224 ip_best_cred(mblk_t *mp, conn_t *connp)
4225 {
4226 	cred_t *cr;
4227 
4228 	cr = msg_getcred(mp, NULL);
4229 	if (cr != NULL && crgetlabel(cr) != NULL)
4230 		return (cr);
4231 	return (CONN_CRED(connp));
4232 }
4233 
4234 /*
4235  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4236  * part of the bind request.
4237  */
4238 
4239 boolean_t
4240 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4241 {
4242 	ipsec_in_t *ii;
4243 
4244 	ASSERT(policy_mp != NULL);
4245 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4246 
4247 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4248 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4249 
4250 	connp->conn_policy = ii->ipsec_in_policy;
4251 	ii->ipsec_in_policy = NULL;
4252 
4253 	if (ii->ipsec_in_action != NULL) {
4254 		if (connp->conn_latch == NULL) {
4255 			connp->conn_latch = iplatch_create();
4256 			if (connp->conn_latch == NULL)
4257 				return (B_FALSE);
4258 		}
4259 		ipsec_latch_inbound(connp->conn_latch, ii);
4260 	}
4261 	return (B_TRUE);
4262 }
4263 
4264 static void
4265 ip_bind_post_handling(conn_t *connp, mblk_t *mp, boolean_t ire_requested)
4266 {
4267 	/*
4268 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4269 	 * We can't do this in ip_bind_get_ire because the policy
4270 	 * may not have been inherited at that point in time and hence
4271 	 * conn_out_enforce_policy may not be set.
4272 	 */
4273 	if (ire_requested && connp->conn_out_enforce_policy &&
4274 	    mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE) {
4275 		ire_t *ire = (ire_t *)mp->b_rptr;
4276 		ASSERT(MBLKL(mp) >= sizeof (ire_t));
4277 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4278 	}
4279 }
4280 
4281 /*
4282  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4283  * and to arrange for power-fanout assist.  The ULP is identified by
4284  * adding a single byte at the end of the original bind message.
4285  * A ULP other than UDP or TCP that wishes to be recognized passes
4286  * down a bind with a zero length address.
4287  *
4288  * The binding works as follows:
4289  * - A zero byte address means just bind to the protocol.
4290  * - A four byte address is treated as a request to validate
4291  *   that the address is a valid local address, appropriate for
4292  *   an application to bind to. This does not affect any fanout
4293  *   information in IP.
4294  * - A sizeof sin_t byte address is used to bind to only the local address
4295  *   and port.
4296  * - A sizeof ipa_conn_t byte address contains complete fanout information
4297  *   consisting of local and remote addresses and ports.  In
4298  *   this case, the addresses are both validated as appropriate
4299  *   for this operation, and, if so, the information is retained
4300  *   for use in the inbound fanout.
4301  *
4302  * The ULP (except in the zero-length bind) can append an
4303  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4304  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4305  * a copy of the source or destination IRE (source for local bind;
4306  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4307  * policy information contained should be copied on to the conn.
4308  *
4309  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4310  */
4311 mblk_t *
4312 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4313 {
4314 	ssize_t		len;
4315 	struct T_bind_req	*tbr;
4316 	sin_t		*sin;
4317 	ipa_conn_t	*ac;
4318 	uchar_t		*ucp;
4319 	mblk_t		*mp1;
4320 	boolean_t	ire_requested;
4321 	int		error = 0;
4322 	int		protocol;
4323 	ipa_conn_x_t	*acx;
4324 	cred_t		*cr;
4325 
4326 	/*
4327 	 * All Solaris components should pass a db_credp
4328 	 * for this TPI message, hence we ASSERT.
4329 	 * But in case there is some other M_PROTO that looks
4330 	 * like a TPI message sent by some other kernel
4331 	 * component, we check and return an error.
4332 	 */
4333 	cr = msg_getcred(mp, NULL);
4334 	ASSERT(cr != NULL);
4335 	if (cr == NULL) {
4336 		error = EINVAL;
4337 		goto bad_addr;
4338 	}
4339 
4340 	ASSERT(!connp->conn_af_isv6);
4341 	connp->conn_pkt_isv6 = B_FALSE;
4342 
4343 	len = MBLKL(mp);
4344 	if (len < (sizeof (*tbr) + 1)) {
4345 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4346 		    "ip_bind: bogus msg, len %ld", len);
4347 		/* XXX: Need to return something better */
4348 		goto bad_addr;
4349 	}
4350 	/* Back up and extract the protocol identifier. */
4351 	mp->b_wptr--;
4352 	protocol = *mp->b_wptr & 0xFF;
4353 	tbr = (struct T_bind_req *)mp->b_rptr;
4354 	/* Reset the message type in preparation for shipping it back. */
4355 	DB_TYPE(mp) = M_PCPROTO;
4356 
4357 	connp->conn_ulp = (uint8_t)protocol;
4358 
4359 	/*
4360 	 * Check for a zero length address.  This is from a protocol that
4361 	 * wants to register to receive all packets of its type.
4362 	 */
4363 	if (tbr->ADDR_length == 0) {
4364 		/*
4365 		 * These protocols are now intercepted in ip_bind_v6().
4366 		 * Reject protocol-level binds here for now.
4367 		 *
4368 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4369 		 * so that the protocol type cannot be SCTP.
4370 		 */
4371 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4372 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4373 			goto bad_addr;
4374 		}
4375 
4376 		/*
4377 		 *
4378 		 * The udp module never sends down a zero-length address,
4379 		 * and allowing this on a labeled system will break MLP
4380 		 * functionality.
4381 		 */
4382 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4383 			goto bad_addr;
4384 
4385 		if (connp->conn_mac_exempt)
4386 			goto bad_addr;
4387 
4388 		/* No hash here really.  The table is big enough. */
4389 		connp->conn_srcv6 = ipv6_all_zeros;
4390 
4391 		ipcl_proto_insert(connp, protocol);
4392 
4393 		tbr->PRIM_type = T_BIND_ACK;
4394 		return (mp);
4395 	}
4396 
4397 	/* Extract the address pointer from the message. */
4398 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4399 	    tbr->ADDR_length);
4400 	if (ucp == NULL) {
4401 		ip1dbg(("ip_bind: no address\n"));
4402 		goto bad_addr;
4403 	}
4404 	if (!OK_32PTR(ucp)) {
4405 		ip1dbg(("ip_bind: unaligned address\n"));
4406 		goto bad_addr;
4407 	}
4408 	/*
4409 	 * Check for trailing mps.
4410 	 */
4411 
4412 	mp1 = mp->b_cont;
4413 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4414 
4415 	switch (tbr->ADDR_length) {
4416 	default:
4417 		ip1dbg(("ip_bind: bad address length %d\n",
4418 		    (int)tbr->ADDR_length));
4419 		goto bad_addr;
4420 
4421 	case IP_ADDR_LEN:
4422 		/* Verification of local address only */
4423 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4424 		    *(ipaddr_t *)ucp, 0, B_FALSE);
4425 		break;
4426 
4427 	case sizeof (sin_t):
4428 		sin = (sin_t *)ucp;
4429 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4430 		    sin->sin_addr.s_addr, sin->sin_port, B_TRUE);
4431 		break;
4432 
4433 	case sizeof (ipa_conn_t):
4434 		ac = (ipa_conn_t *)ucp;
4435 		/* For raw socket, the local port is not set. */
4436 		if (ac->ac_lport == 0)
4437 			ac->ac_lport = connp->conn_lport;
4438 		/* Always verify destination reachability. */
4439 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4440 		    &ac->ac_laddr, ac->ac_lport, ac->ac_faddr, ac->ac_fport,
4441 		    B_TRUE, B_TRUE, cr);
4442 		break;
4443 
4444 	case sizeof (ipa_conn_x_t):
4445 		acx = (ipa_conn_x_t *)ucp;
4446 		/*
4447 		 * Whether or not to verify destination reachability depends
4448 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4449 		 */
4450 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4451 		    &acx->acx_conn.ac_laddr, acx->acx_conn.ac_lport,
4452 		    acx->acx_conn.ac_faddr, acx->acx_conn.ac_fport,
4453 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0, cr);
4454 		break;
4455 	}
4456 	ASSERT(error != EINPROGRESS);
4457 	if (error != 0)
4458 		goto bad_addr;
4459 
4460 	ip_bind_post_handling(connp, mp->b_cont, ire_requested);
4461 
4462 	/* Send it home. */
4463 	mp->b_datap->db_type = M_PCPROTO;
4464 	tbr->PRIM_type = T_BIND_ACK;
4465 	return (mp);
4466 
4467 bad_addr:
4468 	/*
4469 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4470 	 * a unix errno.
4471 	 */
4472 	if (error > 0)
4473 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4474 	else
4475 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4476 	return (mp);
4477 }
4478 
4479 /*
4480  * Here address is verified to be a valid local address.
4481  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4482  * address is also considered a valid local address.
4483  * In the case of a broadcast/multicast address, however, the
4484  * upper protocol is expected to reset the src address
4485  * to 0 if it sees a IRE_BROADCAST type returned so that
4486  * no packets are emitted with broadcast/multicast address as
4487  * source address (that violates hosts requirements RFC 1122)
4488  * The addresses valid for bind are:
4489  *	(1) - INADDR_ANY (0)
4490  *	(2) - IP address of an UP interface
4491  *	(3) - IP address of a DOWN interface
4492  *	(4) - valid local IP broadcast addresses. In this case
4493  *	the conn will only receive packets destined to
4494  *	the specified broadcast address.
4495  *	(5) - a multicast address. In this case
4496  *	the conn will only receive packets destined to
4497  *	the specified multicast address. Note: the
4498  *	application still has to issue an
4499  *	IP_ADD_MEMBERSHIP socket option.
4500  *
4501  * On error, return -1 for TBADADDR otherwise pass the
4502  * errno with TSYSERR reply.
4503  *
4504  * In all the above cases, the bound address must be valid in the current zone.
4505  * When the address is loopback, multicast or broadcast, there might be many
4506  * matching IREs so bind has to look up based on the zone.
4507  *
4508  * Note: lport is in network byte order.
4509  *
4510  */
4511 int
4512 ip_bind_laddr_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4513     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4514 {
4515 	int		error = 0;
4516 	ire_t		*src_ire;
4517 	zoneid_t	zoneid;
4518 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4519 	mblk_t		*mp = NULL;
4520 	boolean_t	ire_requested = B_FALSE;
4521 	boolean_t	ipsec_policy_set = B_FALSE;
4522 
4523 	if (mpp)
4524 		mp = *mpp;
4525 
4526 	if (mp != NULL) {
4527 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4528 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4529 	}
4530 
4531 	/*
4532 	 * If it was previously connected, conn_fully_bound would have
4533 	 * been set.
4534 	 */
4535 	connp->conn_fully_bound = B_FALSE;
4536 
4537 	src_ire = NULL;
4538 
4539 	zoneid = IPCL_ZONEID(connp);
4540 
4541 	if (src_addr) {
4542 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4543 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4544 		/*
4545 		 * If an address other than 0.0.0.0 is requested,
4546 		 * we verify that it is a valid address for bind
4547 		 * Note: Following code is in if-else-if form for
4548 		 * readability compared to a condition check.
4549 		 */
4550 		/* LINTED - statement has no consequence */
4551 		if (IRE_IS_LOCAL(src_ire)) {
4552 			/*
4553 			 * (2) Bind to address of local UP interface
4554 			 */
4555 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4556 			/*
4557 			 * (4) Bind to broadcast address
4558 			 * Note: permitted only from transports that
4559 			 * request IRE
4560 			 */
4561 			if (!ire_requested)
4562 				error = EADDRNOTAVAIL;
4563 		} else {
4564 			/*
4565 			 * (3) Bind to address of local DOWN interface
4566 			 * (ipif_lookup_addr() looks up all interfaces
4567 			 * but we do not get here for UP interfaces
4568 			 * - case (2) above)
4569 			 */
4570 			/* LINTED - statement has no consequent */
4571 			if (ip_addr_exists(src_addr, zoneid, ipst)) {
4572 				/* The address exists */
4573 			} else if (CLASSD(src_addr)) {
4574 				error = 0;
4575 				if (src_ire != NULL)
4576 					ire_refrele(src_ire);
4577 				/*
4578 				 * (5) bind to multicast address.
4579 				 * Fake out the IRE returned to upper
4580 				 * layer to be a broadcast IRE.
4581 				 */
4582 				src_ire = ire_ctable_lookup(
4583 				    INADDR_BROADCAST, INADDR_ANY,
4584 				    IRE_BROADCAST, NULL, zoneid, NULL,
4585 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4586 				    ipst);
4587 				if (src_ire == NULL || !ire_requested)
4588 					error = EADDRNOTAVAIL;
4589 			} else {
4590 				/*
4591 				 * Not a valid address for bind
4592 				 */
4593 				error = EADDRNOTAVAIL;
4594 			}
4595 		}
4596 		if (error) {
4597 			/* Red Alert!  Attempting to be a bogon! */
4598 			ip1dbg(("ip_bind_laddr_v4: bad src address 0x%x\n",
4599 			    ntohl(src_addr)));
4600 			goto bad_addr;
4601 		}
4602 	}
4603 
4604 	/*
4605 	 * Allow setting new policies. For example, disconnects come
4606 	 * down as ipa_t bind. As we would have set conn_policy_cached
4607 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4608 	 * can change after the disconnect.
4609 	 */
4610 	connp->conn_policy_cached = B_FALSE;
4611 
4612 	/*
4613 	 * If not fanout_insert this was just an address verification
4614 	 */
4615 	if (fanout_insert) {
4616 		/*
4617 		 * The addresses have been verified. Time to insert in
4618 		 * the correct fanout list.
4619 		 */
4620 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4621 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4622 		connp->conn_lport = lport;
4623 		connp->conn_fport = 0;
4624 		/*
4625 		 * Do we need to add a check to reject Multicast packets
4626 		 */
4627 		error = ipcl_bind_insert(connp, protocol, src_addr, lport);
4628 	}
4629 
4630 	if (error == 0) {
4631 		if (ire_requested) {
4632 			if (!ip_bind_get_ire_v4(mpp, src_ire, NULL, ipst)) {
4633 				error = -1;
4634 				/* Falls through to bad_addr */
4635 			}
4636 		} else if (ipsec_policy_set) {
4637 			if (!ip_bind_ipsec_policy_set(connp, mp)) {
4638 				error = -1;
4639 				/* Falls through to bad_addr */
4640 			}
4641 		}
4642 	}
4643 bad_addr:
4644 	if (error != 0) {
4645 		if (connp->conn_anon_port) {
4646 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4647 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4648 			    B_FALSE);
4649 		}
4650 		connp->conn_mlp_type = mlptSingle;
4651 	}
4652 	if (src_ire != NULL)
4653 		IRE_REFRELE(src_ire);
4654 	return (error);
4655 }
4656 
4657 int
4658 ip_proto_bind_laddr_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
4659     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4660 {
4661 	int error;
4662 	mblk_t	*mp = NULL;
4663 	boolean_t ire_requested;
4664 
4665 	if (ire_mpp)
4666 		mp = *ire_mpp;
4667 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4668 
4669 	ASSERT(!connp->conn_af_isv6);
4670 	connp->conn_pkt_isv6 = B_FALSE;
4671 	connp->conn_ulp = protocol;
4672 
4673 	error = ip_bind_laddr_v4(connp, ire_mpp, protocol, src_addr, lport,
4674 	    fanout_insert);
4675 	if (error == 0) {
4676 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
4677 		    ire_requested);
4678 	} else if (error < 0) {
4679 		error = -TBADADDR;
4680 	}
4681 	return (error);
4682 }
4683 
4684 /*
4685  * Verify that both the source and destination addresses
4686  * are valid.  If verify_dst is false, then the destination address may be
4687  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4688  * destination reachability, while tunnels do not.
4689  * Note that we allow connect to broadcast and multicast
4690  * addresses when ire_requested is set. Thus the ULP
4691  * has to check for IRE_BROADCAST and multicast.
4692  *
4693  * Returns zero if ok.
4694  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4695  * (for use with TSYSERR reply).
4696  *
4697  * Note: lport and fport are in network byte order.
4698  */
4699 int
4700 ip_bind_connected_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4701     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4702     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
4703 {
4704 
4705 	ire_t		*src_ire;
4706 	ire_t		*dst_ire;
4707 	int		error = 0;
4708 	ire_t		*sire = NULL;
4709 	ire_t		*md_dst_ire = NULL;
4710 	ire_t		*lso_dst_ire = NULL;
4711 	ill_t		*ill = NULL;
4712 	zoneid_t	zoneid;
4713 	ipaddr_t	src_addr = *src_addrp;
4714 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4715 	mblk_t		*mp = NULL;
4716 	boolean_t	ire_requested = B_FALSE;
4717 	boolean_t	ipsec_policy_set = B_FALSE;
4718 	ts_label_t	*tsl = NULL;
4719 
4720 	if (mpp)
4721 		mp = *mpp;
4722 
4723 	if (mp != NULL) {
4724 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4725 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4726 	}
4727 	if (cr != NULL)
4728 		tsl = crgetlabel(cr);
4729 
4730 	src_ire = dst_ire = NULL;
4731 
4732 	/*
4733 	 * If we never got a disconnect before, clear it now.
4734 	 */
4735 	connp->conn_fully_bound = B_FALSE;
4736 
4737 	zoneid = IPCL_ZONEID(connp);
4738 
4739 	if (CLASSD(dst_addr)) {
4740 		/* Pick up an IRE_BROADCAST */
4741 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4742 		    NULL, zoneid, tsl,
4743 		    (MATCH_IRE_RECURSIVE |
4744 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4745 		    MATCH_IRE_SECATTR), ipst);
4746 	} else {
4747 		/*
4748 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4749 		 * and onlink ipif is not found set ENETUNREACH error.
4750 		 */
4751 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4752 			ipif_t *ipif;
4753 
4754 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4755 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4756 			if (ipif == NULL) {
4757 				error = ENETUNREACH;
4758 				goto bad_addr;
4759 			}
4760 			ipif_refrele(ipif);
4761 		}
4762 
4763 		if (connp->conn_nexthop_set) {
4764 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4765 			    0, 0, NULL, NULL, zoneid, tsl,
4766 			    MATCH_IRE_SECATTR, ipst);
4767 		} else {
4768 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4769 			    &sire, zoneid, tsl,
4770 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4771 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4772 			    MATCH_IRE_SECATTR), ipst);
4773 		}
4774 	}
4775 	/*
4776 	 * dst_ire can't be a broadcast when not ire_requested.
4777 	 * We also prevent ire's with src address INADDR_ANY to
4778 	 * be used, which are created temporarily for
4779 	 * sending out packets from endpoints that have
4780 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4781 	 * reachable.  If verify_dst is false, the destination needn't be
4782 	 * reachable.
4783 	 *
4784 	 * If we match on a reject or black hole, then we've got a
4785 	 * local failure.  May as well fail out the connect() attempt,
4786 	 * since it's never going to succeed.
4787 	 */
4788 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4789 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4790 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4791 		/*
4792 		 * If we're verifying destination reachability, we always want
4793 		 * to complain here.
4794 		 *
4795 		 * If we're not verifying destination reachability but the
4796 		 * destination has a route, we still want to fail on the
4797 		 * temporary address and broadcast address tests.
4798 		 */
4799 		if (verify_dst || (dst_ire != NULL)) {
4800 			if (ip_debug > 2) {
4801 				pr_addr_dbg("ip_bind_connected_v4:"
4802 				    "bad connected dst %s\n",
4803 				    AF_INET, &dst_addr);
4804 			}
4805 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4806 				error = ENETUNREACH;
4807 			else
4808 				error = EHOSTUNREACH;
4809 			goto bad_addr;
4810 		}
4811 	}
4812 
4813 	/*
4814 	 * We now know that routing will allow us to reach the destination.
4815 	 * Check whether Trusted Solaris policy allows communication with this
4816 	 * host, and pretend that the destination is unreachable if not.
4817 	 *
4818 	 * This is never a problem for TCP, since that transport is known to
4819 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4820 	 * handling.  If the remote is unreachable, it will be detected at that
4821 	 * point, so there's no reason to check it here.
4822 	 *
4823 	 * Note that for sendto (and other datagram-oriented friends), this
4824 	 * check is done as part of the data path label computation instead.
4825 	 * The check here is just to make non-TCP connect() report the right
4826 	 * error.
4827 	 */
4828 	if (dst_ire != NULL && is_system_labeled() &&
4829 	    !IPCL_IS_TCP(connp) &&
4830 	    tsol_compute_label(cr, dst_addr, NULL,
4831 	    connp->conn_mac_exempt, ipst) != 0) {
4832 		error = EHOSTUNREACH;
4833 		if (ip_debug > 2) {
4834 			pr_addr_dbg("ip_bind_connected_v4:"
4835 			    " no label for dst %s\n",
4836 			    AF_INET, &dst_addr);
4837 		}
4838 		goto bad_addr;
4839 	}
4840 
4841 	/*
4842 	 * If the app does a connect(), it means that it will most likely
4843 	 * send more than 1 packet to the destination.  It makes sense
4844 	 * to clear the temporary flag.
4845 	 */
4846 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4847 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4848 		irb_t *irb = dst_ire->ire_bucket;
4849 
4850 		rw_enter(&irb->irb_lock, RW_WRITER);
4851 		/*
4852 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4853 		 * the lock to guarantee irb_tmp_ire_cnt.
4854 		 */
4855 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4856 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4857 			irb->irb_tmp_ire_cnt--;
4858 		}
4859 		rw_exit(&irb->irb_lock);
4860 	}
4861 
4862 	/*
4863 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4864 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4865 	 * eligibility tests for passive connects are handled separately
4866 	 * through tcp_adapt_ire().  We do this before the source address
4867 	 * selection, because dst_ire may change after a call to
4868 	 * ipif_select_source().  This is a best-effort check, as the
4869 	 * packet for this connection may not actually go through
4870 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4871 	 * calling ip_newroute().  This is why we further check on the
4872 	 * IRE during LSO/Multidata packet transmission in
4873 	 * tcp_lsosend()/tcp_multisend().
4874 	 */
4875 	if (!ipsec_policy_set && dst_ire != NULL &&
4876 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4877 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4878 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4879 			lso_dst_ire = dst_ire;
4880 			IRE_REFHOLD(lso_dst_ire);
4881 		} else if (ipst->ips_ip_multidata_outbound &&
4882 		    ILL_MDT_CAPABLE(ill)) {
4883 			md_dst_ire = dst_ire;
4884 			IRE_REFHOLD(md_dst_ire);
4885 		}
4886 	}
4887 
4888 	if (dst_ire != NULL && dst_ire->ire_type == IRE_LOCAL &&
4889 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4890 		/*
4891 		 * If the IRE belongs to a different zone, look for a matching
4892 		 * route in the forwarding table and use the source address from
4893 		 * that route.
4894 		 */
4895 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4896 		    zoneid, 0, NULL,
4897 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4898 		    MATCH_IRE_RJ_BHOLE, ipst);
4899 		if (src_ire == NULL) {
4900 			error = EHOSTUNREACH;
4901 			goto bad_addr;
4902 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4903 			if (!(src_ire->ire_type & IRE_HOST))
4904 				error = ENETUNREACH;
4905 			else
4906 				error = EHOSTUNREACH;
4907 			goto bad_addr;
4908 		}
4909 		if (src_addr == INADDR_ANY)
4910 			src_addr = src_ire->ire_src_addr;
4911 		ire_refrele(src_ire);
4912 		src_ire = NULL;
4913 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4914 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4915 			src_addr = sire->ire_src_addr;
4916 			ire_refrele(dst_ire);
4917 			dst_ire = sire;
4918 			sire = NULL;
4919 		} else {
4920 			/*
4921 			 * Pick a source address so that a proper inbound
4922 			 * load spreading would happen.
4923 			 */
4924 			ill_t *ire_ill = dst_ire->ire_ipif->ipif_ill;
4925 			ipif_t *src_ipif = NULL;
4926 			ire_t *ipif_ire;
4927 
4928 			/*
4929 			 * Supply a local source address such that inbound
4930 			 * load spreading happens.
4931 			 *
4932 			 * Determine the best source address on this ill for
4933 			 * the destination.
4934 			 *
4935 			 * 1) For broadcast, we should return a broadcast ire
4936 			 *    found above so that upper layers know that the
4937 			 *    destination address is a broadcast address.
4938 			 *
4939 			 * 2) If the ipif is DEPRECATED, select a better
4940 			 *    source address.  Similarly, if the ipif is on
4941 			 *    the IPMP meta-interface, pick a source address
4942 			 *    at random to improve inbound load spreading.
4943 			 *
4944 			 * 3) If the outgoing interface is part of a usesrc
4945 			 *    group, then try selecting a source address from
4946 			 *    the usesrc ILL.
4947 			 */
4948 			if ((dst_ire->ire_zoneid != zoneid &&
4949 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4950 			    (!(dst_ire->ire_flags & RTF_SETSRC)) &&
4951 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4952 			    (IS_IPMP(ire_ill) ||
4953 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4954 			    (ire_ill->ill_usesrc_ifindex != 0)))) {
4955 				/*
4956 				 * If the destination is reachable via a
4957 				 * given gateway, the selected source address
4958 				 * should be in the same subnet as the gateway.
4959 				 * Otherwise, the destination is not reachable.
4960 				 *
4961 				 * If there are no interfaces on the same subnet
4962 				 * as the destination, ipif_select_source gives
4963 				 * first non-deprecated interface which might be
4964 				 * on a different subnet than the gateway.
4965 				 * This is not desirable. Hence pass the dst_ire
4966 				 * source address to ipif_select_source.
4967 				 * It is sure that the destination is reachable
4968 				 * with the dst_ire source address subnet.
4969 				 * So passing dst_ire source address to
4970 				 * ipif_select_source will make sure that the
4971 				 * selected source will be on the same subnet
4972 				 * as dst_ire source address.
4973 				 */
4974 				ipaddr_t saddr =
4975 				    dst_ire->ire_ipif->ipif_src_addr;
4976 				src_ipif = ipif_select_source(ire_ill,
4977 				    saddr, zoneid);
4978 				if (src_ipif != NULL) {
4979 					if (IS_VNI(src_ipif->ipif_ill)) {
4980 						/*
4981 						 * For VNI there is no
4982 						 * interface route
4983 						 */
4984 						src_addr =
4985 						    src_ipif->ipif_src_addr;
4986 					} else {
4987 						ipif_ire =
4988 						    ipif_to_ire(src_ipif);
4989 						if (ipif_ire != NULL) {
4990 							IRE_REFRELE(dst_ire);
4991 							dst_ire = ipif_ire;
4992 						}
4993 						src_addr =
4994 						    dst_ire->ire_src_addr;
4995 					}
4996 					ipif_refrele(src_ipif);
4997 				} else {
4998 					src_addr = dst_ire->ire_src_addr;
4999 				}
5000 			} else {
5001 				src_addr = dst_ire->ire_src_addr;
5002 			}
5003 		}
5004 	}
5005 
5006 	/*
5007 	 * We do ire_route_lookup() here (and not
5008 	 * interface lookup as we assert that
5009 	 * src_addr should only come from an
5010 	 * UP interface for hard binding.
5011 	 */
5012 	ASSERT(src_ire == NULL);
5013 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5014 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5015 	/* src_ire must be a local|loopback */
5016 	if (!IRE_IS_LOCAL(src_ire)) {
5017 		if (ip_debug > 2) {
5018 			pr_addr_dbg("ip_bind_connected_v4: bad connected "
5019 			    "src %s\n", AF_INET, &src_addr);
5020 		}
5021 		error = EADDRNOTAVAIL;
5022 		goto bad_addr;
5023 	}
5024 
5025 	/*
5026 	 * If the source address is a loopback address, the
5027 	 * destination had best be local or multicast.
5028 	 * The transports that can't handle multicast will reject
5029 	 * those addresses.
5030 	 */
5031 	if (src_ire->ire_type == IRE_LOOPBACK &&
5032 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5033 		ip1dbg(("ip_bind_connected_v4: bad connected loopback\n"));
5034 		error = -1;
5035 		goto bad_addr;
5036 	}
5037 
5038 	/*
5039 	 * Allow setting new policies. For example, disconnects come
5040 	 * down as ipa_t bind. As we would have set conn_policy_cached
5041 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5042 	 * can change after the disconnect.
5043 	 */
5044 	connp->conn_policy_cached = B_FALSE;
5045 
5046 	/*
5047 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5048 	 * can handle their passed-in conn's.
5049 	 */
5050 
5051 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5052 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5053 	connp->conn_lport = lport;
5054 	connp->conn_fport = fport;
5055 	*src_addrp = src_addr;
5056 
5057 	ASSERT(!(ipsec_policy_set && ire_requested));
5058 	if (ire_requested) {
5059 		iulp_t *ulp_info = NULL;
5060 
5061 		/*
5062 		 * Note that sire will not be NULL if this is an off-link
5063 		 * connection and there is not cache for that dest yet.
5064 		 *
5065 		 * XXX Because of an existing bug, if there are multiple
5066 		 * default routes, the IRE returned now may not be the actual
5067 		 * default route used (default routes are chosen in a
5068 		 * round robin fashion).  So if the metrics for different
5069 		 * default routes are different, we may return the wrong
5070 		 * metrics.  This will not be a problem if the existing
5071 		 * bug is fixed.
5072 		 */
5073 		if (sire != NULL) {
5074 			ulp_info = &(sire->ire_uinfo);
5075 		}
5076 		if (!ip_bind_get_ire_v4(mpp, dst_ire, ulp_info, ipst)) {
5077 			error = -1;
5078 			goto bad_addr;
5079 		}
5080 		mp = *mpp;
5081 	} else if (ipsec_policy_set) {
5082 		if (!ip_bind_ipsec_policy_set(connp, mp)) {
5083 			error = -1;
5084 			goto bad_addr;
5085 		}
5086 	}
5087 
5088 	/*
5089 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5090 	 * we'll cache that.  If we don't, we'll inherit global policy.
5091 	 *
5092 	 * We can't insert until the conn reflects the policy. Note that
5093 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5094 	 * connections where we don't have a policy. This is to prevent
5095 	 * global policy lookups in the inbound path.
5096 	 *
5097 	 * If we insert before we set conn_policy_cached,
5098 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5099 	 * because global policy cound be non-empty. We normally call
5100 	 * ipsec_check_policy() for conn_policy_cached connections only if
5101 	 * ipc_in_enforce_policy is set. But in this case,
5102 	 * conn_policy_cached can get set anytime since we made the
5103 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5104 	 * called, which will make the above assumption false.  Thus, we
5105 	 * need to insert after we set conn_policy_cached.
5106 	 */
5107 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5108 		goto bad_addr;
5109 
5110 	if (fanout_insert) {
5111 		/*
5112 		 * The addresses have been verified. Time to insert in
5113 		 * the correct fanout list.
5114 		 */
5115 		error = ipcl_conn_insert(connp, protocol, src_addr,
5116 		    dst_addr, connp->conn_ports);
5117 	}
5118 
5119 	if (error == 0) {
5120 		connp->conn_fully_bound = B_TRUE;
5121 		/*
5122 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5123 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5124 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5125 		 * ip_xxinfo_return(), which performs further checks
5126 		 * against them and upon success, returns the LSO/MDT info
5127 		 * mblk which we will attach to the bind acknowledgment.
5128 		 */
5129 		if (lso_dst_ire != NULL) {
5130 			mblk_t *lsoinfo_mp;
5131 
5132 			ASSERT(ill->ill_lso_capab != NULL);
5133 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5134 			    ill->ill_name, ill->ill_lso_capab)) != NULL) {
5135 				if (mp == NULL) {
5136 					*mpp = lsoinfo_mp;
5137 				} else {
5138 					linkb(mp, lsoinfo_mp);
5139 				}
5140 			}
5141 		} else if (md_dst_ire != NULL) {
5142 			mblk_t *mdinfo_mp;
5143 
5144 			ASSERT(ill->ill_mdt_capab != NULL);
5145 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5146 			    ill->ill_name, ill->ill_mdt_capab)) != NULL) {
5147 				if (mp == NULL) {
5148 					*mpp = mdinfo_mp;
5149 				} else {
5150 					linkb(mp, mdinfo_mp);
5151 				}
5152 			}
5153 		}
5154 	}
5155 bad_addr:
5156 	if (ipsec_policy_set) {
5157 		ASSERT(mp != NULL);
5158 		freeb(mp);
5159 		/*
5160 		 * As of now assume that nothing else accompanies
5161 		 * IPSEC_POLICY_SET.
5162 		 */
5163 		*mpp = NULL;
5164 	}
5165 	if (src_ire != NULL)
5166 		IRE_REFRELE(src_ire);
5167 	if (dst_ire != NULL)
5168 		IRE_REFRELE(dst_ire);
5169 	if (sire != NULL)
5170 		IRE_REFRELE(sire);
5171 	if (md_dst_ire != NULL)
5172 		IRE_REFRELE(md_dst_ire);
5173 	if (lso_dst_ire != NULL)
5174 		IRE_REFRELE(lso_dst_ire);
5175 	return (error);
5176 }
5177 
5178 int
5179 ip_proto_bind_connected_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
5180     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
5181     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
5182 {
5183 	int error;
5184 	mblk_t	*mp = NULL;
5185 	boolean_t ire_requested;
5186 
5187 	if (ire_mpp)
5188 		mp = *ire_mpp;
5189 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
5190 
5191 	ASSERT(!connp->conn_af_isv6);
5192 	connp->conn_pkt_isv6 = B_FALSE;
5193 	connp->conn_ulp = protocol;
5194 
5195 	/* For raw socket, the local port is not set. */
5196 	if (lport == 0)
5197 		lport = connp->conn_lport;
5198 	error = ip_bind_connected_v4(connp, ire_mpp, protocol,
5199 	    src_addrp, lport, dst_addr, fport, fanout_insert, verify_dst, cr);
5200 	if (error == 0) {
5201 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
5202 		    ire_requested);
5203 	} else if (error < 0) {
5204 		error = -TBADADDR;
5205 	}
5206 	return (error);
5207 }
5208 
5209 /*
5210  * Get the ire in *mpp. Returns false if it fails (due to lack of space).
5211  * Prefers dst_ire over src_ire.
5212  */
5213 static boolean_t
5214 ip_bind_get_ire_v4(mblk_t **mpp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5215 {
5216 	mblk_t	*mp = *mpp;
5217 	ire_t	*ret_ire;
5218 
5219 	ASSERT(mp != NULL);
5220 
5221 	if (ire != NULL) {
5222 		/*
5223 		 * mp initialized above to IRE_DB_REQ_TYPE
5224 		 * appended mblk. Its <upper protocol>'s
5225 		 * job to make sure there is room.
5226 		 */
5227 		if ((mp->b_datap->db_lim - mp->b_rptr) < sizeof (ire_t))
5228 			return (B_FALSE);
5229 
5230 		mp->b_datap->db_type = IRE_DB_TYPE;
5231 		mp->b_wptr = mp->b_rptr + sizeof (ire_t);
5232 		bcopy(ire, mp->b_rptr, sizeof (ire_t));
5233 		ret_ire = (ire_t *)mp->b_rptr;
5234 		/*
5235 		 * Pass the latest setting of the ip_path_mtu_discovery and
5236 		 * copy the ulp info if any.
5237 		 */
5238 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5239 		    IPH_DF : 0;
5240 		if (ulp_info != NULL) {
5241 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5242 			    sizeof (iulp_t));
5243 		}
5244 		ret_ire->ire_mp = mp;
5245 	} else {
5246 		/*
5247 		 * No IRE was found. Remove IRE mblk.
5248 		 */
5249 		*mpp = mp->b_cont;
5250 		freeb(mp);
5251 	}
5252 	return (B_TRUE);
5253 }
5254 
5255 /*
5256  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5257  * the final piece where we don't.  Return a pointer to the first mblk in the
5258  * result, and update the pointer to the next mblk to chew on.  If anything
5259  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5260  * NULL pointer.
5261  */
5262 mblk_t *
5263 ip_carve_mp(mblk_t **mpp, ssize_t len)
5264 {
5265 	mblk_t	*mp0;
5266 	mblk_t	*mp1;
5267 	mblk_t	*mp2;
5268 
5269 	if (!len || !mpp || !(mp0 = *mpp))
5270 		return (NULL);
5271 	/* If we aren't going to consume the first mblk, we need a dup. */
5272 	if (mp0->b_wptr - mp0->b_rptr > len) {
5273 		mp1 = dupb(mp0);
5274 		if (mp1) {
5275 			/* Partition the data between the two mblks. */
5276 			mp1->b_wptr = mp1->b_rptr + len;
5277 			mp0->b_rptr = mp1->b_wptr;
5278 			/*
5279 			 * after adjustments if mblk not consumed is now
5280 			 * unaligned, try to align it. If this fails free
5281 			 * all messages and let upper layer recover.
5282 			 */
5283 			if (!OK_32PTR(mp0->b_rptr)) {
5284 				if (!pullupmsg(mp0, -1)) {
5285 					freemsg(mp0);
5286 					freemsg(mp1);
5287 					*mpp = NULL;
5288 					return (NULL);
5289 				}
5290 			}
5291 		}
5292 		return (mp1);
5293 	}
5294 	/* Eat through as many mblks as we need to get len bytes. */
5295 	len -= mp0->b_wptr - mp0->b_rptr;
5296 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5297 		if (mp2->b_wptr - mp2->b_rptr > len) {
5298 			/*
5299 			 * We won't consume the entire last mblk.  Like
5300 			 * above, dup and partition it.
5301 			 */
5302 			mp1->b_cont = dupb(mp2);
5303 			mp1 = mp1->b_cont;
5304 			if (!mp1) {
5305 				/*
5306 				 * Trouble.  Rather than go to a lot of
5307 				 * trouble to clean up, we free the messages.
5308 				 * This won't be any worse than losing it on
5309 				 * the wire.
5310 				 */
5311 				freemsg(mp0);
5312 				freemsg(mp2);
5313 				*mpp = NULL;
5314 				return (NULL);
5315 			}
5316 			mp1->b_wptr = mp1->b_rptr + len;
5317 			mp2->b_rptr = mp1->b_wptr;
5318 			/*
5319 			 * after adjustments if mblk not consumed is now
5320 			 * unaligned, try to align it. If this fails free
5321 			 * all messages and let upper layer recover.
5322 			 */
5323 			if (!OK_32PTR(mp2->b_rptr)) {
5324 				if (!pullupmsg(mp2, -1)) {
5325 					freemsg(mp0);
5326 					freemsg(mp2);
5327 					*mpp = NULL;
5328 					return (NULL);
5329 				}
5330 			}
5331 			*mpp = mp2;
5332 			return (mp0);
5333 		}
5334 		/* Decrement len by the amount we just got. */
5335 		len -= mp2->b_wptr - mp2->b_rptr;
5336 	}
5337 	/*
5338 	 * len should be reduced to zero now.  If not our caller has
5339 	 * screwed up.
5340 	 */
5341 	if (len) {
5342 		/* Shouldn't happen! */
5343 		freemsg(mp0);
5344 		*mpp = NULL;
5345 		return (NULL);
5346 	}
5347 	/*
5348 	 * We consumed up to exactly the end of an mblk.  Detach the part
5349 	 * we are returning from the rest of the chain.
5350 	 */
5351 	mp1->b_cont = NULL;
5352 	*mpp = mp2;
5353 	return (mp0);
5354 }
5355 
5356 /* The ill stream is being unplumbed. Called from ip_close */
5357 int
5358 ip_modclose(ill_t *ill)
5359 {
5360 	boolean_t success;
5361 	ipsq_t	*ipsq;
5362 	ipif_t	*ipif;
5363 	queue_t	*q = ill->ill_rq;
5364 	ip_stack_t	*ipst = ill->ill_ipst;
5365 
5366 	/*
5367 	 * The punlink prior to this may have initiated a capability
5368 	 * negotiation. But ipsq_enter will block until that finishes or
5369 	 * times out.
5370 	 */
5371 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
5372 
5373 	/*
5374 	 * Open/close/push/pop is guaranteed to be single threaded
5375 	 * per stream by STREAMS. FS guarantees that all references
5376 	 * from top are gone before close is called. So there can't
5377 	 * be another close thread that has set CONDEMNED on this ill.
5378 	 * and cause ipsq_enter to return failure.
5379 	 */
5380 	ASSERT(success);
5381 	ipsq = ill->ill_phyint->phyint_ipsq;
5382 
5383 	/*
5384 	 * Mark it condemned. No new reference will be made to this ill.
5385 	 * Lookup functions will return an error. Threads that try to
5386 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5387 	 * that the refcnt will drop down to zero.
5388 	 */
5389 	mutex_enter(&ill->ill_lock);
5390 	ill->ill_state_flags |= ILL_CONDEMNED;
5391 	for (ipif = ill->ill_ipif; ipif != NULL;
5392 	    ipif = ipif->ipif_next) {
5393 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5394 	}
5395 	/*
5396 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5397 	 * returns  error if ILL_CONDEMNED is set
5398 	 */
5399 	cv_broadcast(&ill->ill_cv);
5400 	mutex_exit(&ill->ill_lock);
5401 
5402 	/*
5403 	 * Send all the deferred DLPI messages downstream which came in
5404 	 * during the small window right before ipsq_enter(). We do this
5405 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5406 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5407 	 */
5408 	ill_dlpi_send_deferred(ill);
5409 
5410 	/*
5411 	 * Shut down fragmentation reassembly.
5412 	 * ill_frag_timer won't start a timer again.
5413 	 * Now cancel any existing timer
5414 	 */
5415 	(void) untimeout(ill->ill_frag_timer_id);
5416 	(void) ill_frag_timeout(ill, 0);
5417 
5418 	/*
5419 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5420 	 * this ill. Then wait for the refcnts to drop to zero.
5421 	 * ill_is_freeable checks whether the ill is really quiescent.
5422 	 * Then make sure that threads that are waiting to enter the
5423 	 * ipsq have seen the error returned by ipsq_enter and have
5424 	 * gone away. Then we call ill_delete_tail which does the
5425 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5426 	 */
5427 	ill_delete(ill);
5428 	mutex_enter(&ill->ill_lock);
5429 	while (!ill_is_freeable(ill))
5430 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5431 	while (ill->ill_waiters)
5432 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5433 
5434 	mutex_exit(&ill->ill_lock);
5435 
5436 	/*
5437 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5438 	 * it held until the end of the function since the cleanup
5439 	 * below needs to be able to use the ip_stack_t.
5440 	 */
5441 	netstack_hold(ipst->ips_netstack);
5442 
5443 	/* qprocsoff is done via ill_delete_tail */
5444 	ill_delete_tail(ill);
5445 	ASSERT(ill->ill_ipst == NULL);
5446 
5447 	/*
5448 	 * Walk through all upper (conn) streams and qenable
5449 	 * those that have queued data.
5450 	 * close synchronization needs this to
5451 	 * be done to ensure that all upper layers blocked
5452 	 * due to flow control to the closing device
5453 	 * get unblocked.
5454 	 */
5455 	ip1dbg(("ip_wsrv: walking\n"));
5456 	conn_walk_drain(ipst);
5457 
5458 	mutex_enter(&ipst->ips_ip_mi_lock);
5459 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5460 	mutex_exit(&ipst->ips_ip_mi_lock);
5461 
5462 	/*
5463 	 * credp could be null if the open didn't succeed and ip_modopen
5464 	 * itself calls ip_close.
5465 	 */
5466 	if (ill->ill_credp != NULL)
5467 		crfree(ill->ill_credp);
5468 
5469 	/*
5470 	 * Now we are done with the module close pieces that
5471 	 * need the netstack_t.
5472 	 */
5473 	netstack_rele(ipst->ips_netstack);
5474 
5475 	mi_close_free((IDP)ill);
5476 	q->q_ptr = WR(q)->q_ptr = NULL;
5477 
5478 	ipsq_exit(ipsq);
5479 
5480 	return (0);
5481 }
5482 
5483 /*
5484  * This is called as part of close() for IP, UDP, ICMP, and RTS
5485  * in order to quiesce the conn.
5486  */
5487 void
5488 ip_quiesce_conn(conn_t *connp)
5489 {
5490 	boolean_t	drain_cleanup_reqd = B_FALSE;
5491 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5492 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5493 	ip_stack_t	*ipst;
5494 
5495 	ASSERT(!IPCL_IS_TCP(connp));
5496 	ipst = connp->conn_netstack->netstack_ip;
5497 
5498 	/*
5499 	 * Mark the conn as closing, and this conn must not be
5500 	 * inserted in future into any list. Eg. conn_drain_insert(),
5501 	 * won't insert this conn into the conn_drain_list.
5502 	 * Similarly ill_pending_mp_add() will not add any mp to
5503 	 * the pending mp list, after this conn has started closing.
5504 	 *
5505 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5506 	 * cannot get set henceforth.
5507 	 */
5508 	mutex_enter(&connp->conn_lock);
5509 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5510 	connp->conn_state_flags |= CONN_CLOSING;
5511 	if (connp->conn_idl != NULL)
5512 		drain_cleanup_reqd = B_TRUE;
5513 	if (connp->conn_oper_pending_ill != NULL)
5514 		conn_ioctl_cleanup_reqd = B_TRUE;
5515 	if (connp->conn_dhcpinit_ill != NULL) {
5516 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5517 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5518 		connp->conn_dhcpinit_ill = NULL;
5519 	}
5520 	if (connp->conn_ilg_inuse != 0)
5521 		ilg_cleanup_reqd = B_TRUE;
5522 	mutex_exit(&connp->conn_lock);
5523 
5524 	if (conn_ioctl_cleanup_reqd)
5525 		conn_ioctl_cleanup(connp);
5526 
5527 	if (is_system_labeled() && connp->conn_anon_port) {
5528 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5529 		    connp->conn_mlp_type, connp->conn_ulp,
5530 		    ntohs(connp->conn_lport), B_FALSE);
5531 		connp->conn_anon_port = 0;
5532 	}
5533 	connp->conn_mlp_type = mlptSingle;
5534 
5535 	/*
5536 	 * Remove this conn from any fanout list it is on.
5537 	 * and then wait for any threads currently operating
5538 	 * on this endpoint to finish
5539 	 */
5540 	ipcl_hash_remove(connp);
5541 
5542 	/*
5543 	 * Remove this conn from the drain list, and do
5544 	 * any other cleanup that may be required.
5545 	 * (Only non-tcp streams may have a non-null conn_idl.
5546 	 * TCP streams are never flow controlled, and
5547 	 * conn_idl will be null)
5548 	 */
5549 	if (drain_cleanup_reqd)
5550 		conn_drain_tail(connp, B_TRUE);
5551 
5552 	if (connp == ipst->ips_ip_g_mrouter)
5553 		(void) ip_mrouter_done(NULL, ipst);
5554 
5555 	if (ilg_cleanup_reqd)
5556 		ilg_delete_all(connp);
5557 
5558 	conn_delete_ire(connp, NULL);
5559 
5560 	/*
5561 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5562 	 * callers from write side can't be there now because close
5563 	 * is in progress. The only other caller is ipcl_walk
5564 	 * which checks for the condemned flag.
5565 	 */
5566 	mutex_enter(&connp->conn_lock);
5567 	connp->conn_state_flags |= CONN_CONDEMNED;
5568 	while (connp->conn_ref != 1)
5569 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5570 	connp->conn_state_flags |= CONN_QUIESCED;
5571 	mutex_exit(&connp->conn_lock);
5572 }
5573 
5574 /* ARGSUSED */
5575 int
5576 ip_close(queue_t *q, int flags)
5577 {
5578 	conn_t		*connp;
5579 
5580 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5581 
5582 	/*
5583 	 * Call the appropriate delete routine depending on whether this is
5584 	 * a module or device.
5585 	 */
5586 	if (WR(q)->q_next != NULL) {
5587 		/* This is a module close */
5588 		return (ip_modclose((ill_t *)q->q_ptr));
5589 	}
5590 
5591 	connp = q->q_ptr;
5592 	ip_quiesce_conn(connp);
5593 
5594 	qprocsoff(q);
5595 
5596 	/*
5597 	 * Now we are truly single threaded on this stream, and can
5598 	 * delete the things hanging off the connp, and finally the connp.
5599 	 * We removed this connp from the fanout list, it cannot be
5600 	 * accessed thru the fanouts, and we already waited for the
5601 	 * conn_ref to drop to 0. We are already in close, so
5602 	 * there cannot be any other thread from the top. qprocsoff
5603 	 * has completed, and service has completed or won't run in
5604 	 * future.
5605 	 */
5606 	ASSERT(connp->conn_ref == 1);
5607 
5608 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5609 
5610 	connp->conn_ref--;
5611 	ipcl_conn_destroy(connp);
5612 
5613 	q->q_ptr = WR(q)->q_ptr = NULL;
5614 	return (0);
5615 }
5616 
5617 /*
5618  * Wapper around putnext() so that ip_rts_request can merely use
5619  * conn_recv.
5620  */
5621 /*ARGSUSED2*/
5622 static void
5623 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5624 {
5625 	conn_t *connp = (conn_t *)arg1;
5626 
5627 	putnext(connp->conn_rq, mp);
5628 }
5629 
5630 /*
5631  * Called when the module is about to be unloaded
5632  */
5633 void
5634 ip_ddi_destroy(void)
5635 {
5636 	tnet_fini();
5637 
5638 	icmp_ddi_g_destroy();
5639 	rts_ddi_g_destroy();
5640 	udp_ddi_g_destroy();
5641 	sctp_ddi_g_destroy();
5642 	tcp_ddi_g_destroy();
5643 	ipsec_policy_g_destroy();
5644 	ipcl_g_destroy();
5645 	ip_net_g_destroy();
5646 	ip_ire_g_fini();
5647 	inet_minor_destroy(ip_minor_arena_sa);
5648 #if defined(_LP64)
5649 	inet_minor_destroy(ip_minor_arena_la);
5650 #endif
5651 
5652 #ifdef DEBUG
5653 	list_destroy(&ip_thread_list);
5654 	rw_destroy(&ip_thread_rwlock);
5655 	tsd_destroy(&ip_thread_data);
5656 #endif
5657 
5658 	netstack_unregister(NS_IP);
5659 }
5660 
5661 /*
5662  * First step in cleanup.
5663  */
5664 /* ARGSUSED */
5665 static void
5666 ip_stack_shutdown(netstackid_t stackid, void *arg)
5667 {
5668 	ip_stack_t *ipst = (ip_stack_t *)arg;
5669 
5670 #ifdef NS_DEBUG
5671 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5672 #endif
5673 
5674 	/* Get rid of loopback interfaces and their IREs */
5675 	ip_loopback_cleanup(ipst);
5676 
5677 	/*
5678 	 * The *_hook_shutdown()s start the process of notifying any
5679 	 * consumers that things are going away.... nothing is destroyed.
5680 	 */
5681 	ipv4_hook_shutdown(ipst);
5682 	ipv6_hook_shutdown(ipst);
5683 
5684 	mutex_enter(&ipst->ips_capab_taskq_lock);
5685 	ipst->ips_capab_taskq_quit = B_TRUE;
5686 	cv_signal(&ipst->ips_capab_taskq_cv);
5687 	mutex_exit(&ipst->ips_capab_taskq_lock);
5688 
5689 	mutex_enter(&ipst->ips_mrt_lock);
5690 	ipst->ips_mrt_flags |= IP_MRT_STOP;
5691 	cv_signal(&ipst->ips_mrt_cv);
5692 	mutex_exit(&ipst->ips_mrt_lock);
5693 }
5694 
5695 /*
5696  * Free the IP stack instance.
5697  */
5698 static void
5699 ip_stack_fini(netstackid_t stackid, void *arg)
5700 {
5701 	ip_stack_t *ipst = (ip_stack_t *)arg;
5702 	int ret;
5703 
5704 #ifdef NS_DEBUG
5705 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5706 #endif
5707 	/*
5708 	 * At this point, all of the notifications that the events and
5709 	 * protocols are going away have been run, meaning that we can
5710 	 * now set about starting to clean things up.
5711 	 */
5712 	ipv4_hook_destroy(ipst);
5713 	ipv6_hook_destroy(ipst);
5714 	ip_net_destroy(ipst);
5715 
5716 	mutex_destroy(&ipst->ips_capab_taskq_lock);
5717 	cv_destroy(&ipst->ips_capab_taskq_cv);
5718 	list_destroy(&ipst->ips_capab_taskq_list);
5719 
5720 	mutex_enter(&ipst->ips_mrt_lock);
5721 	while (!(ipst->ips_mrt_flags & IP_MRT_DONE))
5722 		cv_wait(&ipst->ips_mrt_done_cv, &ipst->ips_mrt_lock);
5723 	mutex_destroy(&ipst->ips_mrt_lock);
5724 	cv_destroy(&ipst->ips_mrt_cv);
5725 	cv_destroy(&ipst->ips_mrt_done_cv);
5726 
5727 	ipmp_destroy(ipst);
5728 	rw_destroy(&ipst->ips_srcid_lock);
5729 
5730 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5731 	ipst->ips_ip_mibkp = NULL;
5732 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5733 	ipst->ips_icmp_mibkp = NULL;
5734 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5735 	ipst->ips_ip_kstat = NULL;
5736 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5737 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5738 	ipst->ips_ip6_kstat = NULL;
5739 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5740 
5741 	nd_free(&ipst->ips_ip_g_nd);
5742 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5743 	ipst->ips_param_arr = NULL;
5744 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5745 	ipst->ips_ndp_arr = NULL;
5746 
5747 	ip_mrouter_stack_destroy(ipst);
5748 
5749 	mutex_destroy(&ipst->ips_ip_mi_lock);
5750 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5751 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5752 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5753 
5754 	ret = untimeout(ipst->ips_igmp_timeout_id);
5755 	if (ret == -1) {
5756 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5757 	} else {
5758 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5759 		ipst->ips_igmp_timeout_id = 0;
5760 	}
5761 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5762 	if (ret == -1) {
5763 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5764 	} else {
5765 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5766 		ipst->ips_igmp_slowtimeout_id = 0;
5767 	}
5768 	ret = untimeout(ipst->ips_mld_timeout_id);
5769 	if (ret == -1) {
5770 		ASSERT(ipst->ips_mld_timeout_id == 0);
5771 	} else {
5772 		ASSERT(ipst->ips_mld_timeout_id != 0);
5773 		ipst->ips_mld_timeout_id = 0;
5774 	}
5775 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5776 	if (ret == -1) {
5777 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5778 	} else {
5779 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5780 		ipst->ips_mld_slowtimeout_id = 0;
5781 	}
5782 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5783 	if (ret == -1) {
5784 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5785 	} else {
5786 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5787 		ipst->ips_ip_ire_expire_id = 0;
5788 	}
5789 
5790 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5791 	mutex_destroy(&ipst->ips_mld_timer_lock);
5792 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5793 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5794 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5795 	rw_destroy(&ipst->ips_ill_g_lock);
5796 
5797 	ipobs_fini(ipst);
5798 	ip_ire_fini(ipst);
5799 	ip6_asp_free(ipst);
5800 	conn_drain_fini(ipst);
5801 	ipcl_destroy(ipst);
5802 
5803 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5804 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5805 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5806 	ipst->ips_ndp4 = NULL;
5807 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5808 	ipst->ips_ndp6 = NULL;
5809 
5810 	if (ipst->ips_loopback_ksp != NULL) {
5811 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5812 		ipst->ips_loopback_ksp = NULL;
5813 	}
5814 
5815 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5816 	ipst->ips_phyint_g_list = NULL;
5817 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5818 	ipst->ips_ill_g_heads = NULL;
5819 
5820 	ldi_ident_release(ipst->ips_ldi_ident);
5821 	kmem_free(ipst, sizeof (*ipst));
5822 }
5823 
5824 /*
5825  * This function is called from the TSD destructor, and is used to debug
5826  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5827  * details.
5828  */
5829 static void
5830 ip_thread_exit(void *phash)
5831 {
5832 	th_hash_t *thh = phash;
5833 
5834 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5835 	list_remove(&ip_thread_list, thh);
5836 	rw_exit(&ip_thread_rwlock);
5837 	mod_hash_destroy_hash(thh->thh_hash);
5838 	kmem_free(thh, sizeof (*thh));
5839 }
5840 
5841 /*
5842  * Called when the IP kernel module is loaded into the kernel
5843  */
5844 void
5845 ip_ddi_init(void)
5846 {
5847 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
5848 
5849 	/*
5850 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5851 	 * initial devices: ip, ip6, tcp, tcp6.
5852 	 */
5853 	/*
5854 	 * If this is a 64-bit kernel, then create two separate arenas -
5855 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5856 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5857 	 */
5858 	ip_minor_arena_la = NULL;
5859 	ip_minor_arena_sa = NULL;
5860 #if defined(_LP64)
5861 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5862 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5863 		cmn_err(CE_PANIC,
5864 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5865 	}
5866 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5867 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5868 		cmn_err(CE_PANIC,
5869 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5870 	}
5871 #else
5872 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5873 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5874 		cmn_err(CE_PANIC,
5875 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5876 	}
5877 #endif
5878 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5879 
5880 	ipcl_g_init();
5881 	ip_ire_g_init();
5882 	ip_net_g_init();
5883 
5884 #ifdef DEBUG
5885 	tsd_create(&ip_thread_data, ip_thread_exit);
5886 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5887 	list_create(&ip_thread_list, sizeof (th_hash_t),
5888 	    offsetof(th_hash_t, thh_link));
5889 #endif
5890 
5891 	/*
5892 	 * We want to be informed each time a stack is created or
5893 	 * destroyed in the kernel, so we can maintain the
5894 	 * set of udp_stack_t's.
5895 	 */
5896 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5897 	    ip_stack_fini);
5898 
5899 	ipsec_policy_g_init();
5900 	tcp_ddi_g_init();
5901 	sctp_ddi_g_init();
5902 
5903 	tnet_init();
5904 
5905 	udp_ddi_g_init();
5906 	rts_ddi_g_init();
5907 	icmp_ddi_g_init();
5908 }
5909 
5910 /*
5911  * Initialize the IP stack instance.
5912  */
5913 static void *
5914 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5915 {
5916 	ip_stack_t	*ipst;
5917 	ipparam_t	*pa;
5918 	ipndp_t		*na;
5919 	major_t		major;
5920 
5921 #ifdef NS_DEBUG
5922 	printf("ip_stack_init(stack %d)\n", stackid);
5923 #endif
5924 
5925 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5926 	ipst->ips_netstack = ns;
5927 
5928 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5929 	    KM_SLEEP);
5930 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5931 	    KM_SLEEP);
5932 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5933 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5934 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5935 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5936 
5937 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5938 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5939 	ipst->ips_igmp_deferred_next = INFINITY;
5940 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5941 	ipst->ips_mld_deferred_next = INFINITY;
5942 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5943 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5944 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5945 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5946 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5947 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5948 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5949 
5950 	ipcl_init(ipst);
5951 	ip_ire_init(ipst);
5952 	ip6_asp_init(ipst);
5953 	ipif_init(ipst);
5954 	conn_drain_init(ipst);
5955 	ip_mrouter_stack_init(ipst);
5956 
5957 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
5958 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
5959 
5960 	ipst->ips_ip_multirt_log_interval = 1000;
5961 
5962 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
5963 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
5964 	ipst->ips_ill_index = 1;
5965 
5966 	ipst->ips_saved_ip_g_forward = -1;
5967 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
5968 
5969 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
5970 	ipst->ips_param_arr = pa;
5971 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
5972 
5973 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
5974 	ipst->ips_ndp_arr = na;
5975 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5976 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
5977 	    (caddr_t)&ipst->ips_ip_g_forward;
5978 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
5979 	    (caddr_t)&ipst->ips_ipv6_forward;
5980 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
5981 	    "ip_cgtp_filter") == 0);
5982 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
5983 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
5984 
5985 	(void) ip_param_register(&ipst->ips_ip_g_nd,
5986 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
5987 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
5988 
5989 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
5990 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
5991 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
5992 	ipst->ips_ip6_kstat =
5993 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
5994 
5995 	ipst->ips_ip_src_id = 1;
5996 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
5997 
5998 	ipobs_init(ipst);
5999 	ip_net_init(ipst, ns);
6000 	ipv4_hook_init(ipst);
6001 	ipv6_hook_init(ipst);
6002 	ipmp_init(ipst);
6003 
6004 	/*
6005 	 * Create the taskq dispatcher thread and initialize related stuff.
6006 	 */
6007 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
6008 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
6009 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
6010 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
6011 	list_create(&ipst->ips_capab_taskq_list, sizeof (mblk_t),
6012 	    offsetof(mblk_t, b_next));
6013 
6014 	/*
6015 	 * Create the mcast_restart_timers_thread() worker thread.
6016 	 */
6017 	mutex_init(&ipst->ips_mrt_lock, NULL, MUTEX_DEFAULT, NULL);
6018 	cv_init(&ipst->ips_mrt_cv, NULL, CV_DEFAULT, NULL);
6019 	cv_init(&ipst->ips_mrt_done_cv, NULL, CV_DEFAULT, NULL);
6020 	ipst->ips_mrt_thread = thread_create(NULL, 0,
6021 	    mcast_restart_timers_thread, ipst, 0, &p0, TS_RUN, minclsyspri);
6022 
6023 	major = mod_name_to_major(INET_NAME);
6024 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
6025 	return (ipst);
6026 }
6027 
6028 /*
6029  * Allocate and initialize a DLPI template of the specified length.  (May be
6030  * called as writer.)
6031  */
6032 mblk_t *
6033 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6034 {
6035 	mblk_t	*mp;
6036 
6037 	mp = allocb(len, BPRI_MED);
6038 	if (!mp)
6039 		return (NULL);
6040 
6041 	/*
6042 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6043 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6044 	 * that other DLPI are M_PROTO.
6045 	 */
6046 	if (prim == DL_INFO_REQ) {
6047 		mp->b_datap->db_type = M_PCPROTO;
6048 	} else {
6049 		mp->b_datap->db_type = M_PROTO;
6050 	}
6051 
6052 	mp->b_wptr = mp->b_rptr + len;
6053 	bzero(mp->b_rptr, len);
6054 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6055 	return (mp);
6056 }
6057 
6058 /*
6059  * Allocate and initialize a DLPI notification.  (May be called as writer.)
6060  */
6061 mblk_t *
6062 ip_dlnotify_alloc(uint_t notification, uint_t data)
6063 {
6064 	dl_notify_ind_t	*notifyp;
6065 	mblk_t		*mp;
6066 
6067 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
6068 		return (NULL);
6069 
6070 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
6071 	notifyp->dl_notification = notification;
6072 	notifyp->dl_data = data;
6073 	return (mp);
6074 }
6075 
6076 /*
6077  * Debug formatting routine.  Returns a character string representation of the
6078  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6079  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6080  *
6081  * Once the ndd table-printing interfaces are removed, this can be changed to
6082  * standard dotted-decimal form.
6083  */
6084 char *
6085 ip_dot_addr(ipaddr_t addr, char *buf)
6086 {
6087 	uint8_t *ap = (uint8_t *)&addr;
6088 
6089 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6090 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6091 	return (buf);
6092 }
6093 
6094 /*
6095  * Write the given MAC address as a printable string in the usual colon-
6096  * separated format.
6097  */
6098 const char *
6099 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6100 {
6101 	char *bp;
6102 
6103 	if (alen == 0 || buflen < 4)
6104 		return ("?");
6105 	bp = buf;
6106 	for (;;) {
6107 		/*
6108 		 * If there are more MAC address bytes available, but we won't
6109 		 * have any room to print them, then add "..." to the string
6110 		 * instead.  See below for the 'magic number' explanation.
6111 		 */
6112 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6113 			(void) strcpy(bp, "...");
6114 			break;
6115 		}
6116 		(void) sprintf(bp, "%02x", *addr++);
6117 		bp += 2;
6118 		if (--alen == 0)
6119 			break;
6120 		*bp++ = ':';
6121 		buflen -= 3;
6122 		/*
6123 		 * At this point, based on the first 'if' statement above,
6124 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6125 		 * buflen >= 4.  The first case leaves room for the final "xx"
6126 		 * number and trailing NUL byte.  The second leaves room for at
6127 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6128 		 * that statement.
6129 		 */
6130 	}
6131 	return (buf);
6132 }
6133 
6134 /*
6135  * Send an ICMP error after patching up the packet appropriately.  Returns
6136  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6137  */
6138 static boolean_t
6139 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6140     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6141     zoneid_t zoneid, ip_stack_t *ipst)
6142 {
6143 	ipha_t *ipha;
6144 	mblk_t *first_mp;
6145 	boolean_t secure;
6146 	unsigned char db_type;
6147 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6148 
6149 	first_mp = mp;
6150 	if (mctl_present) {
6151 		mp = mp->b_cont;
6152 		secure = ipsec_in_is_secure(first_mp);
6153 		ASSERT(mp != NULL);
6154 	} else {
6155 		/*
6156 		 * If this is an ICMP error being reported - which goes
6157 		 * up as M_CTLs, we need to convert them to M_DATA till
6158 		 * we finish checking with global policy because
6159 		 * ipsec_check_global_policy() assumes M_DATA as clear
6160 		 * and M_CTL as secure.
6161 		 */
6162 		db_type = DB_TYPE(mp);
6163 		DB_TYPE(mp) = M_DATA;
6164 		secure = B_FALSE;
6165 	}
6166 	/*
6167 	 * We are generating an icmp error for some inbound packet.
6168 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6169 	 * Before we generate an error, check with global policy
6170 	 * to see whether this is allowed to enter the system. As
6171 	 * there is no "conn", we are checking with global policy.
6172 	 */
6173 	ipha = (ipha_t *)mp->b_rptr;
6174 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6175 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6176 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6177 		if (first_mp == NULL)
6178 			return (B_FALSE);
6179 	}
6180 
6181 	if (!mctl_present)
6182 		DB_TYPE(mp) = db_type;
6183 
6184 	if (flags & IP_FF_SEND_ICMP) {
6185 		if (flags & IP_FF_HDR_COMPLETE) {
6186 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6187 				freemsg(first_mp);
6188 				return (B_TRUE);
6189 			}
6190 		}
6191 		if (flags & IP_FF_CKSUM) {
6192 			/*
6193 			 * Have to correct checksum since
6194 			 * the packet might have been
6195 			 * fragmented and the reassembly code in ip_rput
6196 			 * does not restore the IP checksum.
6197 			 */
6198 			ipha->ipha_hdr_checksum = 0;
6199 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6200 		}
6201 		switch (icmp_type) {
6202 		case ICMP_DEST_UNREACHABLE:
6203 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6204 			    ipst);
6205 			break;
6206 		default:
6207 			freemsg(first_mp);
6208 			break;
6209 		}
6210 	} else {
6211 		freemsg(first_mp);
6212 		return (B_FALSE);
6213 	}
6214 
6215 	return (B_TRUE);
6216 }
6217 
6218 /*
6219  * Used to send an ICMP error message when a packet is received for
6220  * a protocol that is not supported. The mblk passed as argument
6221  * is consumed by this function.
6222  */
6223 void
6224 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6225     ip_stack_t *ipst)
6226 {
6227 	mblk_t *mp;
6228 	ipha_t *ipha;
6229 	ill_t *ill;
6230 	ipsec_in_t *ii;
6231 
6232 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6233 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6234 
6235 	mp = ipsec_mp->b_cont;
6236 	ipsec_mp->b_cont = NULL;
6237 	ipha = (ipha_t *)mp->b_rptr;
6238 	/* Get ill from index in ipsec_in_t. */
6239 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6240 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6241 	    ipst);
6242 	if (ill != NULL) {
6243 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6244 			if (ip_fanout_send_icmp(q, mp, flags,
6245 			    ICMP_DEST_UNREACHABLE,
6246 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6247 				BUMP_MIB(ill->ill_ip_mib,
6248 				    ipIfStatsInUnknownProtos);
6249 			}
6250 		} else {
6251 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6252 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6253 			    0, B_FALSE, zoneid, ipst)) {
6254 				BUMP_MIB(ill->ill_ip_mib,
6255 				    ipIfStatsInUnknownProtos);
6256 			}
6257 		}
6258 		ill_refrele(ill);
6259 	} else { /* re-link for the freemsg() below. */
6260 		ipsec_mp->b_cont = mp;
6261 	}
6262 
6263 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6264 	freemsg(ipsec_mp);
6265 }
6266 
6267 /*
6268  * See if the inbound datagram has had IPsec processing applied to it.
6269  */
6270 boolean_t
6271 ipsec_in_is_secure(mblk_t *ipsec_mp)
6272 {
6273 	ipsec_in_t *ii;
6274 
6275 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6276 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6277 
6278 	if (ii->ipsec_in_loopback) {
6279 		return (ii->ipsec_in_secure);
6280 	} else {
6281 		return (ii->ipsec_in_ah_sa != NULL ||
6282 		    ii->ipsec_in_esp_sa != NULL ||
6283 		    ii->ipsec_in_decaps);
6284 	}
6285 }
6286 
6287 /*
6288  * Handle protocols with which IP is less intimate.  There
6289  * can be more than one stream bound to a particular
6290  * protocol.  When this is the case, normally each one gets a copy
6291  * of any incoming packets.
6292  *
6293  * IPsec NOTE :
6294  *
6295  * Don't allow a secure packet going up a non-secure connection.
6296  * We don't allow this because
6297  *
6298  * 1) Reply might go out in clear which will be dropped at
6299  *    the sending side.
6300  * 2) If the reply goes out in clear it will give the
6301  *    adversary enough information for getting the key in
6302  *    most of the cases.
6303  *
6304  * Moreover getting a secure packet when we expect clear
6305  * implies that SA's were added without checking for
6306  * policy on both ends. This should not happen once ISAKMP
6307  * is used to negotiate SAs as SAs will be added only after
6308  * verifying the policy.
6309  *
6310  * NOTE : If the packet was tunneled and not multicast we only send
6311  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6312  * back to delivering packets to AF_INET6 raw sockets.
6313  *
6314  * IPQoS Notes:
6315  * Once we have determined the client, invoke IPPF processing.
6316  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6317  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6318  * ip_policy will be false.
6319  *
6320  * Zones notes:
6321  * Currently only applications in the global zone can create raw sockets for
6322  * protocols other than ICMP. So unlike the broadcast / multicast case of
6323  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6324  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6325  */
6326 static void
6327 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6328     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6329     zoneid_t zoneid)
6330 {
6331 	queue_t	*rq;
6332 	mblk_t	*mp1, *first_mp1;
6333 	uint_t	protocol = ipha->ipha_protocol;
6334 	ipaddr_t dst;
6335 	boolean_t one_only;
6336 	mblk_t *first_mp = mp;
6337 	boolean_t secure;
6338 	uint32_t ill_index;
6339 	conn_t	*connp, *first_connp, *next_connp;
6340 	connf_t	*connfp;
6341 	boolean_t shared_addr;
6342 	mib2_ipIfStatsEntry_t *mibptr;
6343 	ip_stack_t *ipst = recv_ill->ill_ipst;
6344 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6345 
6346 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6347 	if (mctl_present) {
6348 		mp = first_mp->b_cont;
6349 		secure = ipsec_in_is_secure(first_mp);
6350 		ASSERT(mp != NULL);
6351 	} else {
6352 		secure = B_FALSE;
6353 	}
6354 	dst = ipha->ipha_dst;
6355 	/*
6356 	 * If the packet was tunneled and not multicast we only send to it
6357 	 * the first match.
6358 	 */
6359 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6360 	    !CLASSD(dst));
6361 
6362 	shared_addr = (zoneid == ALL_ZONES);
6363 	if (shared_addr) {
6364 		/*
6365 		 * We don't allow multilevel ports for raw IP, so no need to
6366 		 * check for that here.
6367 		 */
6368 		zoneid = tsol_packet_to_zoneid(mp);
6369 	}
6370 
6371 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6372 	mutex_enter(&connfp->connf_lock);
6373 	connp = connfp->connf_head;
6374 	for (connp = connfp->connf_head; connp != NULL;
6375 	    connp = connp->conn_next) {
6376 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6377 		    zoneid) &&
6378 		    (!is_system_labeled() ||
6379 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6380 		    connp))) {
6381 			break;
6382 		}
6383 	}
6384 
6385 	if (connp == NULL) {
6386 		/*
6387 		 * No one bound to these addresses.  Is
6388 		 * there a client that wants all
6389 		 * unclaimed datagrams?
6390 		 */
6391 		mutex_exit(&connfp->connf_lock);
6392 		/*
6393 		 * Check for IPPROTO_ENCAP...
6394 		 */
6395 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6396 			/*
6397 			 * If an IPsec mblk is here on a multicast
6398 			 * tunnel (using ip_mroute stuff), check policy here,
6399 			 * THEN ship off to ip_mroute_decap().
6400 			 *
6401 			 * BTW,  If I match a configured IP-in-IP
6402 			 * tunnel, this path will not be reached, and
6403 			 * ip_mroute_decap will never be called.
6404 			 */
6405 			first_mp = ipsec_check_global_policy(first_mp, connp,
6406 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6407 			if (first_mp != NULL) {
6408 				if (mctl_present)
6409 					freeb(first_mp);
6410 				ip_mroute_decap(q, mp, ill);
6411 			} /* Else we already freed everything! */
6412 		} else {
6413 			/*
6414 			 * Otherwise send an ICMP protocol unreachable.
6415 			 */
6416 			if (ip_fanout_send_icmp(q, first_mp, flags,
6417 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6418 			    mctl_present, zoneid, ipst)) {
6419 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6420 			}
6421 		}
6422 		return;
6423 	}
6424 
6425 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
6426 
6427 	CONN_INC_REF(connp);
6428 	first_connp = connp;
6429 
6430 	/*
6431 	 * Only send message to one tunnel driver by immediately
6432 	 * terminating the loop.
6433 	 */
6434 	connp = one_only ? NULL : connp->conn_next;
6435 
6436 	for (;;) {
6437 		while (connp != NULL) {
6438 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6439 			    flags, zoneid) &&
6440 			    (!is_system_labeled() ||
6441 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6442 			    shared_addr, connp)))
6443 				break;
6444 			connp = connp->conn_next;
6445 		}
6446 
6447 		/*
6448 		 * Copy the packet.
6449 		 */
6450 		if (connp == NULL ||
6451 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6452 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6453 			/*
6454 			 * No more interested clients or memory
6455 			 * allocation failed
6456 			 */
6457 			connp = first_connp;
6458 			break;
6459 		}
6460 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
6461 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6462 		CONN_INC_REF(connp);
6463 		mutex_exit(&connfp->connf_lock);
6464 		rq = connp->conn_rq;
6465 
6466 		/*
6467 		 * Check flow control
6468 		 */
6469 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6470 		    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6471 			if (flags & IP_FF_RAWIP) {
6472 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6473 			} else {
6474 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6475 			}
6476 
6477 			freemsg(first_mp1);
6478 		} else {
6479 			/*
6480 			 * Don't enforce here if we're an actual tunnel -
6481 			 * let "tun" do it instead.
6482 			 */
6483 			if (!IPCL_IS_IPTUN(connp) &&
6484 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6485 			    secure)) {
6486 				first_mp1 = ipsec_check_inbound_policy
6487 				    (first_mp1, connp, ipha, NULL,
6488 				    mctl_present);
6489 			}
6490 			if (first_mp1 != NULL) {
6491 				int in_flags = 0;
6492 				/*
6493 				 * ip_fanout_proto also gets called from
6494 				 * icmp_inbound_error_fanout, in which case
6495 				 * the msg type is M_CTL.  Don't add info
6496 				 * in this case for the time being. In future
6497 				 * when there is a need for knowing the
6498 				 * inbound iface index for ICMP error msgs,
6499 				 * then this can be changed.
6500 				 */
6501 				if (connp->conn_recvif)
6502 					in_flags = IPF_RECVIF;
6503 				/*
6504 				 * The ULP may support IP_RECVPKTINFO for both
6505 				 * IP v4 and v6 so pass the appropriate argument
6506 				 * based on conn IP version.
6507 				 */
6508 				if (connp->conn_ip_recvpktinfo) {
6509 					if (connp->conn_af_isv6) {
6510 						/*
6511 						 * V6 only needs index
6512 						 */
6513 						in_flags |= IPF_RECVIF;
6514 					} else {
6515 						/*
6516 						 * V4 needs index +
6517 						 * matching address.
6518 						 */
6519 						in_flags |= IPF_RECVADDR;
6520 					}
6521 				}
6522 				if ((in_flags != 0) &&
6523 				    (mp->b_datap->db_type != M_CTL)) {
6524 					/*
6525 					 * the actual data will be
6526 					 * contained in b_cont upon
6527 					 * successful return of the
6528 					 * following call else
6529 					 * original mblk is returned
6530 					 */
6531 					ASSERT(recv_ill != NULL);
6532 					mp1 = ip_add_info(mp1, recv_ill,
6533 					    in_flags, IPCL_ZONEID(connp), ipst);
6534 				}
6535 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6536 				if (mctl_present)
6537 					freeb(first_mp1);
6538 				(connp->conn_recv)(connp, mp1, NULL);
6539 			}
6540 		}
6541 		mutex_enter(&connfp->connf_lock);
6542 		/* Follow the next pointer before releasing the conn. */
6543 		next_connp = connp->conn_next;
6544 		CONN_DEC_REF(connp);
6545 		connp = next_connp;
6546 	}
6547 
6548 	/* Last one.  Send it upstream. */
6549 	mutex_exit(&connfp->connf_lock);
6550 
6551 	/*
6552 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6553 	 * will be set to false.
6554 	 */
6555 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6556 		ill_index = ill->ill_phyint->phyint_ifindex;
6557 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6558 		if (mp == NULL) {
6559 			CONN_DEC_REF(connp);
6560 			if (mctl_present) {
6561 				freeb(first_mp);
6562 			}
6563 			return;
6564 		}
6565 	}
6566 
6567 	rq = connp->conn_rq;
6568 	/*
6569 	 * Check flow control
6570 	 */
6571 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6572 	    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6573 		if (flags & IP_FF_RAWIP) {
6574 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6575 		} else {
6576 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6577 		}
6578 
6579 		freemsg(first_mp);
6580 	} else {
6581 		if (IPCL_IS_IPTUN(connp)) {
6582 			/*
6583 			 * Tunneled packet.  We enforce policy in the tunnel
6584 			 * module itself.
6585 			 *
6586 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6587 			 * a policy check.
6588 			 * FIXME to use conn_recv for tun later.
6589 			 */
6590 			putnext(rq, first_mp);
6591 			CONN_DEC_REF(connp);
6592 			return;
6593 		}
6594 
6595 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6596 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6597 			    ipha, NULL, mctl_present);
6598 		}
6599 
6600 		if (first_mp != NULL) {
6601 			int in_flags = 0;
6602 
6603 			/*
6604 			 * ip_fanout_proto also gets called
6605 			 * from icmp_inbound_error_fanout, in
6606 			 * which case the msg type is M_CTL.
6607 			 * Don't add info in this case for time
6608 			 * being. In future when there is a
6609 			 * need for knowing the inbound iface
6610 			 * index for ICMP error msgs, then this
6611 			 * can be changed
6612 			 */
6613 			if (connp->conn_recvif)
6614 				in_flags = IPF_RECVIF;
6615 			if (connp->conn_ip_recvpktinfo) {
6616 				if (connp->conn_af_isv6) {
6617 					/*
6618 					 * V6 only needs index
6619 					 */
6620 					in_flags |= IPF_RECVIF;
6621 				} else {
6622 					/*
6623 					 * V4 needs index +
6624 					 * matching address.
6625 					 */
6626 					in_flags |= IPF_RECVADDR;
6627 				}
6628 			}
6629 			if ((in_flags != 0) &&
6630 			    (mp->b_datap->db_type != M_CTL)) {
6631 
6632 				/*
6633 				 * the actual data will be contained in
6634 				 * b_cont upon successful return
6635 				 * of the following call else original
6636 				 * mblk is returned
6637 				 */
6638 				ASSERT(recv_ill != NULL);
6639 				mp = ip_add_info(mp, recv_ill,
6640 				    in_flags, IPCL_ZONEID(connp), ipst);
6641 			}
6642 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6643 			(connp->conn_recv)(connp, mp, NULL);
6644 			if (mctl_present)
6645 				freeb(first_mp);
6646 		}
6647 	}
6648 	CONN_DEC_REF(connp);
6649 }
6650 
6651 /*
6652  * Fanout for TCP packets
6653  * The caller puts <fport, lport> in the ports parameter.
6654  *
6655  * IPQoS Notes
6656  * Before sending it to the client, invoke IPPF processing.
6657  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6658  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6659  * ip_policy is false.
6660  */
6661 static void
6662 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6663     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6664 {
6665 	mblk_t  *first_mp;
6666 	boolean_t secure;
6667 	uint32_t ill_index;
6668 	int	ip_hdr_len;
6669 	tcph_t	*tcph;
6670 	boolean_t syn_present = B_FALSE;
6671 	conn_t	*connp;
6672 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6673 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6674 
6675 	ASSERT(recv_ill != NULL);
6676 
6677 	first_mp = mp;
6678 	if (mctl_present) {
6679 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6680 		mp = first_mp->b_cont;
6681 		secure = ipsec_in_is_secure(first_mp);
6682 		ASSERT(mp != NULL);
6683 	} else {
6684 		secure = B_FALSE;
6685 	}
6686 
6687 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6688 
6689 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6690 	    zoneid, ipst)) == NULL) {
6691 		/*
6692 		 * No connected connection or listener. Send a
6693 		 * TH_RST via tcp_xmit_listeners_reset.
6694 		 */
6695 
6696 		/* Initiate IPPf processing, if needed. */
6697 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6698 			uint32_t ill_index;
6699 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6700 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6701 			if (first_mp == NULL)
6702 				return;
6703 		}
6704 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6705 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6706 		    zoneid));
6707 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6708 		    ipst->ips_netstack->netstack_tcp, NULL);
6709 		return;
6710 	}
6711 
6712 	/*
6713 	 * Allocate the SYN for the TCP connection here itself
6714 	 */
6715 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6716 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6717 		if (IPCL_IS_TCP(connp)) {
6718 			squeue_t *sqp;
6719 
6720 			/*
6721 			 * For fused tcp loopback, assign the eager's
6722 			 * squeue to be that of the active connect's.
6723 			 * Note that we don't check for IP_FF_LOOPBACK
6724 			 * here since this routine gets called only
6725 			 * for loopback (unlike the IPv6 counterpart).
6726 			 */
6727 			ASSERT(Q_TO_CONN(q) != NULL);
6728 			if (do_tcp_fusion &&
6729 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6730 			    !secure &&
6731 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6732 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6733 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6734 				sqp = Q_TO_CONN(q)->conn_sqp;
6735 			} else {
6736 				sqp = IP_SQUEUE_GET(lbolt);
6737 			}
6738 
6739 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6740 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6741 			syn_present = B_TRUE;
6742 		}
6743 	}
6744 
6745 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6746 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6747 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6748 		if ((flags & TH_RST) || (flags & TH_URG)) {
6749 			CONN_DEC_REF(connp);
6750 			freemsg(first_mp);
6751 			return;
6752 		}
6753 		if (flags & TH_ACK) {
6754 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6755 			    ipst->ips_netstack->netstack_tcp, connp);
6756 			CONN_DEC_REF(connp);
6757 			return;
6758 		}
6759 
6760 		CONN_DEC_REF(connp);
6761 		freemsg(first_mp);
6762 		return;
6763 	}
6764 
6765 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6766 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6767 		    NULL, mctl_present);
6768 		if (first_mp == NULL) {
6769 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6770 			CONN_DEC_REF(connp);
6771 			return;
6772 		}
6773 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6774 			ASSERT(syn_present);
6775 			if (mctl_present) {
6776 				ASSERT(first_mp != mp);
6777 				first_mp->b_datap->db_struioflag |=
6778 				    STRUIO_POLICY;
6779 			} else {
6780 				ASSERT(first_mp == mp);
6781 				mp->b_datap->db_struioflag &=
6782 				    ~STRUIO_EAGER;
6783 				mp->b_datap->db_struioflag |=
6784 				    STRUIO_POLICY;
6785 			}
6786 		} else {
6787 			/*
6788 			 * Discard first_mp early since we're dealing with a
6789 			 * fully-connected conn_t and tcp doesn't do policy in
6790 			 * this case.
6791 			 */
6792 			if (mctl_present) {
6793 				freeb(first_mp);
6794 				mctl_present = B_FALSE;
6795 			}
6796 			first_mp = mp;
6797 		}
6798 	}
6799 
6800 	/*
6801 	 * Initiate policy processing here if needed. If we get here from
6802 	 * icmp_inbound_error_fanout, ip_policy is false.
6803 	 */
6804 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6805 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6806 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6807 		if (mp == NULL) {
6808 			CONN_DEC_REF(connp);
6809 			if (mctl_present)
6810 				freeb(first_mp);
6811 			return;
6812 		} else if (mctl_present) {
6813 			ASSERT(first_mp != mp);
6814 			first_mp->b_cont = mp;
6815 		} else {
6816 			first_mp = mp;
6817 		}
6818 	}
6819 
6820 	/* Handle socket options. */
6821 	if (!syn_present &&
6822 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6823 		/* Add header */
6824 		ASSERT(recv_ill != NULL);
6825 		/*
6826 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6827 		 * IPF_RECVIF.
6828 		 */
6829 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6830 		    ipst);
6831 		if (mp == NULL) {
6832 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6833 			CONN_DEC_REF(connp);
6834 			if (mctl_present)
6835 				freeb(first_mp);
6836 			return;
6837 		} else if (mctl_present) {
6838 			/*
6839 			 * ip_add_info might return a new mp.
6840 			 */
6841 			ASSERT(first_mp != mp);
6842 			first_mp->b_cont = mp;
6843 		} else {
6844 			first_mp = mp;
6845 		}
6846 	}
6847 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6848 	if (IPCL_IS_TCP(connp)) {
6849 		/* do not drain, certain use cases can blow the stack */
6850 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, connp->conn_recv,
6851 		    connp, ip_squeue_flag, SQTAG_IP_FANOUT_TCP);
6852 	} else {
6853 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6854 		(connp->conn_recv)(connp, first_mp, NULL);
6855 		CONN_DEC_REF(connp);
6856 	}
6857 }
6858 
6859 /*
6860  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6861  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6862  * is not consumed.
6863  *
6864  * One of four things can happen, all of which affect the passed-in mblk:
6865  *
6866  * 1.) ICMP messages that go through here just get returned TRUE.
6867  *
6868  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6869  *
6870  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6871  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6872  *
6873  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6874  */
6875 static boolean_t
6876 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6877     ipsec_stack_t *ipss)
6878 {
6879 	int shift, plen, iph_len;
6880 	ipha_t *ipha;
6881 	udpha_t *udpha;
6882 	uint32_t *spi;
6883 	uint32_t esp_ports;
6884 	uint8_t *orptr;
6885 	boolean_t free_ire;
6886 
6887 	if (DB_TYPE(mp) == M_CTL) {
6888 		/*
6889 		 * ICMP message with UDP inside.  Don't bother stripping, just
6890 		 * send it up.
6891 		 *
6892 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6893 		 * to ignore errors set by ICMP anyway ('cause they might be
6894 		 * forged), but that's the app's decision, not ours.
6895 		 */
6896 
6897 		/* Bunch of reality checks for DEBUG kernels... */
6898 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6899 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6900 
6901 		return (B_TRUE);
6902 	}
6903 
6904 	ipha = (ipha_t *)mp->b_rptr;
6905 	iph_len = IPH_HDR_LENGTH(ipha);
6906 	plen = ntohs(ipha->ipha_length);
6907 
6908 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6909 		/*
6910 		 * Most likely a keepalive for the benefit of an intervening
6911 		 * NAT.  These aren't for us, per se, so drop it.
6912 		 *
6913 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6914 		 * byte packets (keepalives are 1-byte), but we'll drop them
6915 		 * also.
6916 		 */
6917 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6918 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6919 		return (B_FALSE);
6920 	}
6921 
6922 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6923 		/* might as well pull it all up - it might be ESP. */
6924 		if (!pullupmsg(mp, -1)) {
6925 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6926 			    DROPPER(ipss, ipds_esp_nomem),
6927 			    &ipss->ipsec_dropper);
6928 			return (B_FALSE);
6929 		}
6930 
6931 		ipha = (ipha_t *)mp->b_rptr;
6932 	}
6933 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6934 	if (*spi == 0) {
6935 		/* UDP packet - remove 0-spi. */
6936 		shift = sizeof (uint32_t);
6937 	} else {
6938 		/* ESP-in-UDP packet - reduce to ESP. */
6939 		ipha->ipha_protocol = IPPROTO_ESP;
6940 		shift = sizeof (udpha_t);
6941 	}
6942 
6943 	/* Fix IP header */
6944 	ipha->ipha_length = htons(plen - shift);
6945 	ipha->ipha_hdr_checksum = 0;
6946 
6947 	orptr = mp->b_rptr;
6948 	mp->b_rptr += shift;
6949 
6950 	udpha = (udpha_t *)(orptr + iph_len);
6951 	if (*spi == 0) {
6952 		ASSERT((uint8_t *)ipha == orptr);
6953 		udpha->uha_length = htons(plen - shift - iph_len);
6954 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
6955 		esp_ports = 0;
6956 	} else {
6957 		esp_ports = *((uint32_t *)udpha);
6958 		ASSERT(esp_ports != 0);
6959 	}
6960 	ovbcopy(orptr, orptr + shift, iph_len);
6961 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
6962 		ipha = (ipha_t *)(orptr + shift);
6963 
6964 		free_ire = (ire == NULL);
6965 		if (free_ire) {
6966 			/* Re-acquire ire. */
6967 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
6968 			    ipss->ipsec_netstack->netstack_ip);
6969 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
6970 				if (ire != NULL)
6971 					ire_refrele(ire);
6972 				/*
6973 				 * Do a regular freemsg(), as this is an IP
6974 				 * error (no local route) not an IPsec one.
6975 				 */
6976 				freemsg(mp);
6977 			}
6978 		}
6979 
6980 		ip_proto_input(q, mp, ipha, ire, recv_ill, esp_ports);
6981 		if (free_ire)
6982 			ire_refrele(ire);
6983 	}
6984 
6985 	return (esp_ports == 0);
6986 }
6987 
6988 /*
6989  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6990  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6991  * Caller is responsible for dropping references to the conn, and freeing
6992  * first_mp.
6993  *
6994  * IPQoS Notes
6995  * Before sending it to the client, invoke IPPF processing. Policy processing
6996  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6997  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6998  * ip_wput_local, ip_policy is false.
6999  */
7000 static void
7001 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7002     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7003     boolean_t ip_policy)
7004 {
7005 	boolean_t	mctl_present = (first_mp != NULL);
7006 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7007 	uint32_t	ill_index;
7008 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7009 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7010 
7011 	ASSERT(ill != NULL);
7012 
7013 	if (mctl_present)
7014 		first_mp->b_cont = mp;
7015 	else
7016 		first_mp = mp;
7017 
7018 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
7019 	    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
7020 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7021 		freemsg(first_mp);
7022 		return;
7023 	}
7024 
7025 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7026 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7027 		    NULL, mctl_present);
7028 		/* Freed by ipsec_check_inbound_policy(). */
7029 		if (first_mp == NULL) {
7030 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7031 			return;
7032 		}
7033 	}
7034 	if (mctl_present)
7035 		freeb(first_mp);
7036 
7037 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7038 	if (connp->conn_udp->udp_nat_t_endpoint) {
7039 		if (mctl_present) {
7040 			/* mctl_present *shouldn't* happen. */
7041 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7042 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7043 			    &ipss->ipsec_dropper);
7044 			return;
7045 		}
7046 
7047 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7048 			return;
7049 	}
7050 
7051 	/* Handle options. */
7052 	if (connp->conn_recvif)
7053 		in_flags = IPF_RECVIF;
7054 	/*
7055 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7056 	 * passed to ip_add_info is based on IP version of connp.
7057 	 */
7058 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7059 		if (connp->conn_af_isv6) {
7060 			/*
7061 			 * V6 only needs index
7062 			 */
7063 			in_flags |= IPF_RECVIF;
7064 		} else {
7065 			/*
7066 			 * V4 needs index + matching address.
7067 			 */
7068 			in_flags |= IPF_RECVADDR;
7069 		}
7070 	}
7071 
7072 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7073 		in_flags |= IPF_RECVSLLA;
7074 
7075 	/*
7076 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7077 	 * freed if the packet is dropped. The caller will do so.
7078 	 */
7079 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7080 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7081 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7082 		if (mp == NULL) {
7083 			return;
7084 		}
7085 	}
7086 	if ((in_flags != 0) &&
7087 	    (mp->b_datap->db_type != M_CTL)) {
7088 		/*
7089 		 * The actual data will be contained in b_cont
7090 		 * upon successful return of the following call
7091 		 * else original mblk is returned
7092 		 */
7093 		ASSERT(recv_ill != NULL);
7094 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7095 		    ipst);
7096 	}
7097 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7098 	/* Send it upstream */
7099 	(connp->conn_recv)(connp, mp, NULL);
7100 }
7101 
7102 /*
7103  * Fanout for UDP packets.
7104  * The caller puts <fport, lport> in the ports parameter.
7105  *
7106  * If SO_REUSEADDR is set all multicast and broadcast packets
7107  * will be delivered to all streams bound to the same port.
7108  *
7109  * Zones notes:
7110  * Multicast and broadcast packets will be distributed to streams in all zones.
7111  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7112  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7113  * packets. To maintain this behavior with multiple zones, the conns are grouped
7114  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7115  * each zone. If unset, all the following conns in the same zone are skipped.
7116  */
7117 static void
7118 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7119     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7120     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7121 {
7122 	uint32_t	dstport, srcport;
7123 	ipaddr_t	dst;
7124 	mblk_t		*first_mp;
7125 	boolean_t	secure;
7126 	in6_addr_t	v6src;
7127 	conn_t		*connp;
7128 	connf_t		*connfp;
7129 	conn_t		*first_connp;
7130 	conn_t		*next_connp;
7131 	mblk_t		*mp1, *first_mp1;
7132 	ipaddr_t	src;
7133 	zoneid_t	last_zoneid;
7134 	boolean_t	reuseaddr;
7135 	boolean_t	shared_addr;
7136 	boolean_t	unlabeled;
7137 	ip_stack_t	*ipst;
7138 
7139 	ASSERT(recv_ill != NULL);
7140 	ipst = recv_ill->ill_ipst;
7141 
7142 	first_mp = mp;
7143 	if (mctl_present) {
7144 		mp = first_mp->b_cont;
7145 		first_mp->b_cont = NULL;
7146 		secure = ipsec_in_is_secure(first_mp);
7147 		ASSERT(mp != NULL);
7148 	} else {
7149 		first_mp = NULL;
7150 		secure = B_FALSE;
7151 	}
7152 
7153 	/* Extract ports in net byte order */
7154 	dstport = htons(ntohl(ports) & 0xFFFF);
7155 	srcport = htons(ntohl(ports) >> 16);
7156 	dst = ipha->ipha_dst;
7157 	src = ipha->ipha_src;
7158 
7159 	unlabeled = B_FALSE;
7160 	if (is_system_labeled())
7161 		/* Cred cannot be null on IPv4 */
7162 		unlabeled = (msg_getlabel(mp)->tsl_flags &
7163 		    TSLF_UNLABELED) != 0;
7164 	shared_addr = (zoneid == ALL_ZONES);
7165 	if (shared_addr) {
7166 		/*
7167 		 * No need to handle exclusive-stack zones since ALL_ZONES
7168 		 * only applies to the shared stack.
7169 		 */
7170 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7171 		/*
7172 		 * If no shared MLP is found, tsol_mlp_findzone returns
7173 		 * ALL_ZONES.  In that case, we assume it's SLP, and
7174 		 * search for the zone based on the packet label.
7175 		 *
7176 		 * If there is such a zone, we prefer to find a
7177 		 * connection in it.  Otherwise, we look for a
7178 		 * MAC-exempt connection in any zone whose label
7179 		 * dominates the default label on the packet.
7180 		 */
7181 		if (zoneid == ALL_ZONES)
7182 			zoneid = tsol_packet_to_zoneid(mp);
7183 		else
7184 			unlabeled = B_FALSE;
7185 	}
7186 
7187 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7188 	mutex_enter(&connfp->connf_lock);
7189 	connp = connfp->connf_head;
7190 	if (!broadcast && !CLASSD(dst)) {
7191 		/*
7192 		 * Not broadcast or multicast. Send to the one (first)
7193 		 * client we find. No need to check conn_wantpacket()
7194 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7195 		 * IPv4 unicast packets.
7196 		 */
7197 		while ((connp != NULL) &&
7198 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7199 		    (!IPCL_ZONE_MATCH(connp, zoneid) &&
7200 		    !(unlabeled && connp->conn_mac_exempt)))) {
7201 			/*
7202 			 * We keep searching since the conn did not match,
7203 			 * or its zone did not match and it is not either
7204 			 * an allzones conn or a mac exempt conn (if the
7205 			 * sender is unlabeled.)
7206 			 */
7207 			connp = connp->conn_next;
7208 		}
7209 
7210 		if (connp == NULL ||
7211 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7212 			goto notfound;
7213 
7214 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7215 
7216 		if (is_system_labeled() &&
7217 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7218 		    connp))
7219 			goto notfound;
7220 
7221 		CONN_INC_REF(connp);
7222 		mutex_exit(&connfp->connf_lock);
7223 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7224 		    flags, recv_ill, ip_policy);
7225 		IP_STAT(ipst, ip_udp_fannorm);
7226 		CONN_DEC_REF(connp);
7227 		return;
7228 	}
7229 
7230 	/*
7231 	 * Broadcast and multicast case
7232 	 *
7233 	 * Need to check conn_wantpacket().
7234 	 * If SO_REUSEADDR has been set on the first we send the
7235 	 * packet to all clients that have joined the group and
7236 	 * match the port.
7237 	 */
7238 
7239 	while (connp != NULL) {
7240 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7241 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7242 		    (!is_system_labeled() ||
7243 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7244 		    connp)))
7245 			break;
7246 		connp = connp->conn_next;
7247 	}
7248 
7249 	if (connp == NULL ||
7250 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7251 		goto notfound;
7252 
7253 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7254 
7255 	first_connp = connp;
7256 	/*
7257 	 * When SO_REUSEADDR is not set, send the packet only to the first
7258 	 * matching connection in its zone by keeping track of the zoneid.
7259 	 */
7260 	reuseaddr = first_connp->conn_reuseaddr;
7261 	last_zoneid = first_connp->conn_zoneid;
7262 
7263 	CONN_INC_REF(connp);
7264 	connp = connp->conn_next;
7265 	for (;;) {
7266 		while (connp != NULL) {
7267 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7268 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7269 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7270 			    (!is_system_labeled() ||
7271 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7272 			    shared_addr, connp)))
7273 				break;
7274 			connp = connp->conn_next;
7275 		}
7276 		/*
7277 		 * Just copy the data part alone. The mctl part is
7278 		 * needed just for verifying policy and it is never
7279 		 * sent up.
7280 		 */
7281 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7282 		    ((mp1 = copymsg(mp)) == NULL))) {
7283 			/*
7284 			 * No more interested clients or memory
7285 			 * allocation failed
7286 			 */
7287 			connp = first_connp;
7288 			break;
7289 		}
7290 		if (connp->conn_zoneid != last_zoneid) {
7291 			/*
7292 			 * Update the zoneid so that the packet isn't sent to
7293 			 * any more conns in the same zone unless SO_REUSEADDR
7294 			 * is set.
7295 			 */
7296 			reuseaddr = connp->conn_reuseaddr;
7297 			last_zoneid = connp->conn_zoneid;
7298 		}
7299 		if (first_mp != NULL) {
7300 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7301 			    ipsec_info_type == IPSEC_IN);
7302 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7303 			    ipst->ips_netstack);
7304 			if (first_mp1 == NULL) {
7305 				freemsg(mp1);
7306 				connp = first_connp;
7307 				break;
7308 			}
7309 		} else {
7310 			first_mp1 = NULL;
7311 		}
7312 		CONN_INC_REF(connp);
7313 		mutex_exit(&connfp->connf_lock);
7314 		/*
7315 		 * IPQoS notes: We don't send the packet for policy
7316 		 * processing here, will do it for the last one (below).
7317 		 * i.e. we do it per-packet now, but if we do policy
7318 		 * processing per-conn, then we would need to do it
7319 		 * here too.
7320 		 */
7321 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7322 		    ipha, flags, recv_ill, B_FALSE);
7323 		mutex_enter(&connfp->connf_lock);
7324 		/* Follow the next pointer before releasing the conn. */
7325 		next_connp = connp->conn_next;
7326 		IP_STAT(ipst, ip_udp_fanmb);
7327 		CONN_DEC_REF(connp);
7328 		connp = next_connp;
7329 	}
7330 
7331 	/* Last one.  Send it upstream. */
7332 	mutex_exit(&connfp->connf_lock);
7333 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7334 	    recv_ill, ip_policy);
7335 	IP_STAT(ipst, ip_udp_fanmb);
7336 	CONN_DEC_REF(connp);
7337 	return;
7338 
7339 notfound:
7340 
7341 	mutex_exit(&connfp->connf_lock);
7342 	IP_STAT(ipst, ip_udp_fanothers);
7343 	/*
7344 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7345 	 * have already been matched above, since they live in the IPv4
7346 	 * fanout tables. This implies we only need to
7347 	 * check for IPv6 in6addr_any endpoints here.
7348 	 * Thus we compare using ipv6_all_zeros instead of the destination
7349 	 * address, except for the multicast group membership lookup which
7350 	 * uses the IPv4 destination.
7351 	 */
7352 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7353 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7354 	mutex_enter(&connfp->connf_lock);
7355 	connp = connfp->connf_head;
7356 	if (!broadcast && !CLASSD(dst)) {
7357 		while (connp != NULL) {
7358 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7359 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7360 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7361 			    !connp->conn_ipv6_v6only)
7362 				break;
7363 			connp = connp->conn_next;
7364 		}
7365 
7366 		if (connp != NULL && is_system_labeled() &&
7367 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7368 		    connp))
7369 			connp = NULL;
7370 
7371 		if (connp == NULL ||
7372 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7373 			/*
7374 			 * No one bound to this port.  Is
7375 			 * there a client that wants all
7376 			 * unclaimed datagrams?
7377 			 */
7378 			mutex_exit(&connfp->connf_lock);
7379 
7380 			if (mctl_present)
7381 				first_mp->b_cont = mp;
7382 			else
7383 				first_mp = mp;
7384 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7385 			    connf_head != NULL) {
7386 				ip_fanout_proto(q, first_mp, ill, ipha,
7387 				    flags | IP_FF_RAWIP, mctl_present,
7388 				    ip_policy, recv_ill, zoneid);
7389 			} else {
7390 				if (ip_fanout_send_icmp(q, first_mp, flags,
7391 				    ICMP_DEST_UNREACHABLE,
7392 				    ICMP_PORT_UNREACHABLE,
7393 				    mctl_present, zoneid, ipst)) {
7394 					BUMP_MIB(ill->ill_ip_mib,
7395 					    udpIfStatsNoPorts);
7396 				}
7397 			}
7398 			return;
7399 		}
7400 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7401 
7402 		CONN_INC_REF(connp);
7403 		mutex_exit(&connfp->connf_lock);
7404 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7405 		    flags, recv_ill, ip_policy);
7406 		CONN_DEC_REF(connp);
7407 		return;
7408 	}
7409 	/*
7410 	 * IPv4 multicast packet being delivered to an AF_INET6
7411 	 * in6addr_any endpoint.
7412 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7413 	 * and not conn_wantpacket_v6() since any multicast membership is
7414 	 * for an IPv4-mapped multicast address.
7415 	 * The packet is sent to all clients in all zones that have joined the
7416 	 * group and match the port.
7417 	 */
7418 	while (connp != NULL) {
7419 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7420 		    srcport, v6src) &&
7421 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7422 		    (!is_system_labeled() ||
7423 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7424 		    connp)))
7425 			break;
7426 		connp = connp->conn_next;
7427 	}
7428 
7429 	if (connp == NULL ||
7430 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7431 		/*
7432 		 * No one bound to this port.  Is
7433 		 * there a client that wants all
7434 		 * unclaimed datagrams?
7435 		 */
7436 		mutex_exit(&connfp->connf_lock);
7437 
7438 		if (mctl_present)
7439 			first_mp->b_cont = mp;
7440 		else
7441 			first_mp = mp;
7442 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7443 		    NULL) {
7444 			ip_fanout_proto(q, first_mp, ill, ipha,
7445 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7446 			    recv_ill, zoneid);
7447 		} else {
7448 			/*
7449 			 * We used to attempt to send an icmp error here, but
7450 			 * since this is known to be a multicast packet
7451 			 * and we don't send icmp errors in response to
7452 			 * multicast, just drop the packet and give up sooner.
7453 			 */
7454 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7455 			freemsg(first_mp);
7456 		}
7457 		return;
7458 	}
7459 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7460 
7461 	first_connp = connp;
7462 
7463 	CONN_INC_REF(connp);
7464 	connp = connp->conn_next;
7465 	for (;;) {
7466 		while (connp != NULL) {
7467 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7468 			    ipv6_all_zeros, srcport, v6src) &&
7469 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7470 			    (!is_system_labeled() ||
7471 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7472 			    shared_addr, connp)))
7473 				break;
7474 			connp = connp->conn_next;
7475 		}
7476 		/*
7477 		 * Just copy the data part alone. The mctl part is
7478 		 * needed just for verifying policy and it is never
7479 		 * sent up.
7480 		 */
7481 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7482 		    ((mp1 = copymsg(mp)) == NULL))) {
7483 			/*
7484 			 * No more intested clients or memory
7485 			 * allocation failed
7486 			 */
7487 			connp = first_connp;
7488 			break;
7489 		}
7490 		if (first_mp != NULL) {
7491 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7492 			    ipsec_info_type == IPSEC_IN);
7493 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7494 			    ipst->ips_netstack);
7495 			if (first_mp1 == NULL) {
7496 				freemsg(mp1);
7497 				connp = first_connp;
7498 				break;
7499 			}
7500 		} else {
7501 			first_mp1 = NULL;
7502 		}
7503 		CONN_INC_REF(connp);
7504 		mutex_exit(&connfp->connf_lock);
7505 		/*
7506 		 * IPQoS notes: We don't send the packet for policy
7507 		 * processing here, will do it for the last one (below).
7508 		 * i.e. we do it per-packet now, but if we do policy
7509 		 * processing per-conn, then we would need to do it
7510 		 * here too.
7511 		 */
7512 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7513 		    ipha, flags, recv_ill, B_FALSE);
7514 		mutex_enter(&connfp->connf_lock);
7515 		/* Follow the next pointer before releasing the conn. */
7516 		next_connp = connp->conn_next;
7517 		CONN_DEC_REF(connp);
7518 		connp = next_connp;
7519 	}
7520 
7521 	/* Last one.  Send it upstream. */
7522 	mutex_exit(&connfp->connf_lock);
7523 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7524 	    recv_ill, ip_policy);
7525 	CONN_DEC_REF(connp);
7526 }
7527 
7528 /*
7529  * Complete the ip_wput header so that it
7530  * is possible to generate ICMP
7531  * errors.
7532  */
7533 int
7534 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7535 {
7536 	ire_t *ire;
7537 
7538 	if (ipha->ipha_src == INADDR_ANY) {
7539 		ire = ire_lookup_local(zoneid, ipst);
7540 		if (ire == NULL) {
7541 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7542 			return (1);
7543 		}
7544 		ipha->ipha_src = ire->ire_addr;
7545 		ire_refrele(ire);
7546 	}
7547 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7548 	ipha->ipha_hdr_checksum = 0;
7549 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7550 	return (0);
7551 }
7552 
7553 /*
7554  * Nobody should be sending
7555  * packets up this stream
7556  */
7557 static void
7558 ip_lrput(queue_t *q, mblk_t *mp)
7559 {
7560 	mblk_t *mp1;
7561 
7562 	switch (mp->b_datap->db_type) {
7563 	case M_FLUSH:
7564 		/* Turn around */
7565 		if (*mp->b_rptr & FLUSHW) {
7566 			*mp->b_rptr &= ~FLUSHR;
7567 			qreply(q, mp);
7568 			return;
7569 		}
7570 		break;
7571 	}
7572 	/* Could receive messages that passed through ar_rput */
7573 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7574 		mp1->b_prev = mp1->b_next = NULL;
7575 	freemsg(mp);
7576 }
7577 
7578 /* Nobody should be sending packets down this stream */
7579 /* ARGSUSED */
7580 void
7581 ip_lwput(queue_t *q, mblk_t *mp)
7582 {
7583 	freemsg(mp);
7584 }
7585 
7586 /*
7587  * Move the first hop in any source route to ipha_dst and remove that part of
7588  * the source route.  Called by other protocols.  Errors in option formatting
7589  * are ignored - will be handled by ip_wput_options Return the final
7590  * destination (either ipha_dst or the last entry in a source route.)
7591  */
7592 ipaddr_t
7593 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7594 {
7595 	ipoptp_t	opts;
7596 	uchar_t		*opt;
7597 	uint8_t		optval;
7598 	uint8_t		optlen;
7599 	ipaddr_t	dst;
7600 	int		i;
7601 	ire_t		*ire;
7602 	ip_stack_t	*ipst = ns->netstack_ip;
7603 
7604 	ip2dbg(("ip_massage_options\n"));
7605 	dst = ipha->ipha_dst;
7606 	for (optval = ipoptp_first(&opts, ipha);
7607 	    optval != IPOPT_EOL;
7608 	    optval = ipoptp_next(&opts)) {
7609 		opt = opts.ipoptp_cur;
7610 		switch (optval) {
7611 			uint8_t off;
7612 		case IPOPT_SSRR:
7613 		case IPOPT_LSRR:
7614 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7615 				ip1dbg(("ip_massage_options: bad src route\n"));
7616 				break;
7617 			}
7618 			optlen = opts.ipoptp_len;
7619 			off = opt[IPOPT_OFFSET];
7620 			off--;
7621 		redo_srr:
7622 			if (optlen < IP_ADDR_LEN ||
7623 			    off > optlen - IP_ADDR_LEN) {
7624 				/* End of source route */
7625 				ip1dbg(("ip_massage_options: end of SR\n"));
7626 				break;
7627 			}
7628 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7629 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7630 			    ntohl(dst)));
7631 			/*
7632 			 * Check if our address is present more than
7633 			 * once as consecutive hops in source route.
7634 			 * XXX verify per-interface ip_forwarding
7635 			 * for source route?
7636 			 */
7637 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7638 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7639 			if (ire != NULL) {
7640 				ire_refrele(ire);
7641 				off += IP_ADDR_LEN;
7642 				goto redo_srr;
7643 			}
7644 			if (dst == htonl(INADDR_LOOPBACK)) {
7645 				ip1dbg(("ip_massage_options: loopback addr in "
7646 				    "source route!\n"));
7647 				break;
7648 			}
7649 			/*
7650 			 * Update ipha_dst to be the first hop and remove the
7651 			 * first hop from the source route (by overwriting
7652 			 * part of the option with NOP options).
7653 			 */
7654 			ipha->ipha_dst = dst;
7655 			/* Put the last entry in dst */
7656 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7657 			    3;
7658 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7659 
7660 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7661 			    ntohl(dst)));
7662 			/* Move down and overwrite */
7663 			opt[IP_ADDR_LEN] = opt[0];
7664 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7665 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7666 			for (i = 0; i < IP_ADDR_LEN; i++)
7667 				opt[i] = IPOPT_NOP;
7668 			break;
7669 		}
7670 	}
7671 	return (dst);
7672 }
7673 
7674 /*
7675  * Return the network mask
7676  * associated with the specified address.
7677  */
7678 ipaddr_t
7679 ip_net_mask(ipaddr_t addr)
7680 {
7681 	uchar_t	*up = (uchar_t *)&addr;
7682 	ipaddr_t mask = 0;
7683 	uchar_t	*maskp = (uchar_t *)&mask;
7684 
7685 #if defined(__i386) || defined(__amd64)
7686 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7687 #endif
7688 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7689 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7690 #endif
7691 	if (CLASSD(addr)) {
7692 		maskp[0] = 0xF0;
7693 		return (mask);
7694 	}
7695 
7696 	/* We assume Class E default netmask to be 32 */
7697 	if (CLASSE(addr))
7698 		return (0xffffffffU);
7699 
7700 	if (addr == 0)
7701 		return (0);
7702 	maskp[0] = 0xFF;
7703 	if ((up[0] & 0x80) == 0)
7704 		return (mask);
7705 
7706 	maskp[1] = 0xFF;
7707 	if ((up[0] & 0xC0) == 0x80)
7708 		return (mask);
7709 
7710 	maskp[2] = 0xFF;
7711 	if ((up[0] & 0xE0) == 0xC0)
7712 		return (mask);
7713 
7714 	/* Otherwise return no mask */
7715 	return ((ipaddr_t)0);
7716 }
7717 
7718 /*
7719  * Helper ill lookup function used by IPsec.
7720  */
7721 ill_t *
7722 ip_grab_ill(mblk_t *first_mp, int ifindex, boolean_t isv6, ip_stack_t *ipst)
7723 {
7724 	ill_t *ret_ill;
7725 
7726 	ASSERT(ifindex != 0);
7727 
7728 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7729 	    ipst);
7730 	if (ret_ill == NULL) {
7731 		if (isv6) {
7732 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
7733 			ip1dbg(("ip_grab_ill (IPv6): bad ifindex %d.\n",
7734 			    ifindex));
7735 		} else {
7736 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
7737 			ip1dbg(("ip_grab_ill (IPv4): bad ifindex %d.\n",
7738 			    ifindex));
7739 		}
7740 		freemsg(first_mp);
7741 		return (NULL);
7742 	}
7743 	return (ret_ill);
7744 }
7745 
7746 /*
7747  * IPv4 -
7748  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7749  * out a packet to a destination address for which we do not have specific
7750  * (or sufficient) routing information.
7751  *
7752  * NOTE : These are the scopes of some of the variables that point at IRE,
7753  *	  which needs to be followed while making any future modifications
7754  *	  to avoid memory leaks.
7755  *
7756  *	- ire and sire are the entries looked up initially by
7757  *	  ire_ftable_lookup.
7758  *	- ipif_ire is used to hold the interface ire associated with
7759  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7760  *	  it before branching out to error paths.
7761  *	- save_ire is initialized before ire_create, so that ire returned
7762  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7763  *	  before breaking out of the switch.
7764  *
7765  *	Thus on failures, we have to REFRELE only ire and sire, if they
7766  *	are not NULL.
7767  */
7768 void
7769 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7770     zoneid_t zoneid, ip_stack_t *ipst)
7771 {
7772 	areq_t	*areq;
7773 	ipaddr_t gw = 0;
7774 	ire_t	*ire = NULL;
7775 	mblk_t	*res_mp;
7776 	ipaddr_t *addrp;
7777 	ipaddr_t nexthop_addr;
7778 	ipif_t  *src_ipif = NULL;
7779 	ill_t	*dst_ill = NULL;
7780 	ipha_t  *ipha;
7781 	ire_t	*sire = NULL;
7782 	mblk_t	*first_mp;
7783 	ire_t	*save_ire;
7784 	ushort_t ire_marks = 0;
7785 	boolean_t mctl_present;
7786 	ipsec_out_t *io;
7787 	mblk_t	*saved_mp;
7788 	ire_t	*first_sire = NULL;
7789 	mblk_t	*copy_mp = NULL;
7790 	mblk_t	*xmit_mp = NULL;
7791 	ipaddr_t save_dst;
7792 	uint32_t multirt_flags =
7793 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7794 	boolean_t multirt_is_resolvable;
7795 	boolean_t multirt_resolve_next;
7796 	boolean_t unspec_src;
7797 	boolean_t ip_nexthop = B_FALSE;
7798 	tsol_ire_gw_secattr_t *attrp = NULL;
7799 	tsol_gcgrp_t *gcgrp = NULL;
7800 	tsol_gcgrp_addr_t ga;
7801 
7802 	if (ip_debug > 2) {
7803 		/* ip1dbg */
7804 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7805 	}
7806 
7807 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7808 	if (mctl_present) {
7809 		io = (ipsec_out_t *)first_mp->b_rptr;
7810 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7811 		ASSERT(zoneid == io->ipsec_out_zoneid);
7812 		ASSERT(zoneid != ALL_ZONES);
7813 	}
7814 
7815 	ipha = (ipha_t *)mp->b_rptr;
7816 
7817 	/* All multicast lookups come through ip_newroute_ipif() */
7818 	if (CLASSD(dst)) {
7819 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7820 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7821 		freemsg(first_mp);
7822 		return;
7823 	}
7824 
7825 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7826 		ip_nexthop = B_TRUE;
7827 		nexthop_addr = io->ipsec_out_nexthop_addr;
7828 	}
7829 	/*
7830 	 * If this IRE is created for forwarding or it is not for
7831 	 * traffic for congestion controlled protocols, mark it as temporary.
7832 	 */
7833 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7834 		ire_marks |= IRE_MARK_TEMPORARY;
7835 
7836 	/*
7837 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7838 	 * chain until it gets the most specific information available.
7839 	 * For example, we know that there is no IRE_CACHE for this dest,
7840 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7841 	 * ire_ftable_lookup will look up the gateway, etc.
7842 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7843 	 * to the destination, of equal netmask length in the forward table,
7844 	 * will be recursively explored. If no information is available
7845 	 * for the final gateway of that route, we force the returned ire
7846 	 * to be equal to sire using MATCH_IRE_PARENT.
7847 	 * At least, in this case we have a starting point (in the buckets)
7848 	 * to look for other routes to the destination in the forward table.
7849 	 * This is actually used only for multirouting, where a list
7850 	 * of routes has to be processed in sequence.
7851 	 *
7852 	 * In the process of coming up with the most specific information,
7853 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7854 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7855 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7856 	 * Two caveats when handling incomplete ire's in ip_newroute:
7857 	 * - we should be careful when accessing its ire_nce (specifically
7858 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7859 	 * - not all legacy code path callers are prepared to handle
7860 	 *   incomplete ire's, so we should not create/add incomplete
7861 	 *   ire_cache entries here. (See discussion about temporary solution
7862 	 *   further below).
7863 	 *
7864 	 * In order to minimize packet dropping, and to preserve existing
7865 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7866 	 * gateway, and instead use the IF_RESOLVER ire to send out
7867 	 * another request to ARP (this is achieved by passing the
7868 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7869 	 * arp response comes back in ip_wput_nondata, we will create
7870 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7871 	 *
7872 	 * Note that this is a temporary solution; the correct solution is
7873 	 * to create an incomplete  per-dst ire_cache entry, and send the
7874 	 * packet out when the gw's nce is resolved. In order to achieve this,
7875 	 * all packet processing must have been completed prior to calling
7876 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7877 	 * to be modified to accomodate this solution.
7878 	 */
7879 	if (ip_nexthop) {
7880 		/*
7881 		 * The first time we come here, we look for an IRE_INTERFACE
7882 		 * entry for the specified nexthop, set the dst to be the
7883 		 * nexthop address and create an IRE_CACHE entry for the
7884 		 * nexthop. The next time around, we are able to find an
7885 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7886 		 * nexthop address and create an IRE_CACHE entry for the
7887 		 * destination address via the specified nexthop.
7888 		 */
7889 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7890 		    msg_getlabel(mp), ipst);
7891 		if (ire != NULL) {
7892 			gw = nexthop_addr;
7893 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7894 		} else {
7895 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7896 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7897 			    msg_getlabel(mp),
7898 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7899 			    ipst);
7900 			if (ire != NULL) {
7901 				dst = nexthop_addr;
7902 			}
7903 		}
7904 	} else {
7905 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7906 		    NULL, &sire, zoneid, 0, msg_getlabel(mp),
7907 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7908 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7909 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7910 		    ipst);
7911 	}
7912 
7913 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7914 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7915 
7916 	/*
7917 	 * This loop is run only once in most cases.
7918 	 * We loop to resolve further routes only when the destination
7919 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7920 	 */
7921 	do {
7922 		/* Clear the previous iteration's values */
7923 		if (src_ipif != NULL) {
7924 			ipif_refrele(src_ipif);
7925 			src_ipif = NULL;
7926 		}
7927 		if (dst_ill != NULL) {
7928 			ill_refrele(dst_ill);
7929 			dst_ill = NULL;
7930 		}
7931 
7932 		multirt_resolve_next = B_FALSE;
7933 		/*
7934 		 * We check if packets have to be multirouted.
7935 		 * In this case, given the current <ire, sire> couple,
7936 		 * we look for the next suitable <ire, sire>.
7937 		 * This check is done in ire_multirt_lookup(),
7938 		 * which applies various criteria to find the next route
7939 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7940 		 * unchanged if it detects it has not been tried yet.
7941 		 */
7942 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7943 			ip3dbg(("ip_newroute: starting next_resolution "
7944 			    "with first_mp %p, tag %d\n",
7945 			    (void *)first_mp,
7946 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7947 
7948 			ASSERT(sire != NULL);
7949 			multirt_is_resolvable =
7950 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7951 			    msg_getlabel(mp), ipst);
7952 
7953 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7954 			    "ire %p, sire %p\n",
7955 			    multirt_is_resolvable,
7956 			    (void *)ire, (void *)sire));
7957 
7958 			if (!multirt_is_resolvable) {
7959 				/*
7960 				 * No more multirt route to resolve; give up
7961 				 * (all routes resolved or no more
7962 				 * resolvable routes).
7963 				 */
7964 				if (ire != NULL) {
7965 					ire_refrele(ire);
7966 					ire = NULL;
7967 				}
7968 			} else {
7969 				ASSERT(sire != NULL);
7970 				ASSERT(ire != NULL);
7971 				/*
7972 				 * We simply use first_sire as a flag that
7973 				 * indicates if a resolvable multirt route
7974 				 * has already been found.
7975 				 * If it is not the case, we may have to send
7976 				 * an ICMP error to report that the
7977 				 * destination is unreachable.
7978 				 * We do not IRE_REFHOLD first_sire.
7979 				 */
7980 				if (first_sire == NULL) {
7981 					first_sire = sire;
7982 				}
7983 			}
7984 		}
7985 		if (ire == NULL) {
7986 			if (ip_debug > 3) {
7987 				/* ip2dbg */
7988 				pr_addr_dbg("ip_newroute: "
7989 				    "can't resolve %s\n", AF_INET, &dst);
7990 			}
7991 			ip3dbg(("ip_newroute: "
7992 			    "ire %p, sire %p, first_sire %p\n",
7993 			    (void *)ire, (void *)sire, (void *)first_sire));
7994 
7995 			if (sire != NULL) {
7996 				ire_refrele(sire);
7997 				sire = NULL;
7998 			}
7999 
8000 			if (first_sire != NULL) {
8001 				/*
8002 				 * At least one multirt route has been found
8003 				 * in the same call to ip_newroute();
8004 				 * there is no need to report an ICMP error.
8005 				 * first_sire was not IRE_REFHOLDed.
8006 				 */
8007 				MULTIRT_DEBUG_UNTAG(first_mp);
8008 				freemsg(first_mp);
8009 				return;
8010 			}
8011 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8012 			    RTA_DST, ipst);
8013 			goto icmp_err_ret;
8014 		}
8015 
8016 		/*
8017 		 * Verify that the returned IRE does not have either
8018 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8019 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8020 		 */
8021 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8022 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8023 			goto icmp_err_ret;
8024 		}
8025 		/*
8026 		 * Increment the ire_ob_pkt_count field for ire if it is an
8027 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8028 		 * increment the same for the parent IRE, sire, if it is some
8029 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8030 		 */
8031 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8032 			UPDATE_OB_PKT_COUNT(ire);
8033 			ire->ire_last_used_time = lbolt;
8034 		}
8035 
8036 		if (sire != NULL) {
8037 			gw = sire->ire_gateway_addr;
8038 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8039 			    IRE_INTERFACE)) == 0);
8040 			UPDATE_OB_PKT_COUNT(sire);
8041 			sire->ire_last_used_time = lbolt;
8042 		}
8043 		/*
8044 		 * We have a route to reach the destination.  Find the
8045 		 * appropriate ill, then get a source address using
8046 		 * ipif_select_source().
8047 		 *
8048 		 * If we are here trying to create an IRE_CACHE for an offlink
8049 		 * destination and have an IRE_CACHE entry for VNI, then use
8050 		 * ire_stq instead since VNI's queue is a black hole.
8051 		 */
8052 		if ((ire->ire_type == IRE_CACHE) &&
8053 		    IS_VNI(ire->ire_ipif->ipif_ill)) {
8054 			dst_ill = ire->ire_stq->q_ptr;
8055 			ill_refhold(dst_ill);
8056 		} else {
8057 			ill_t *ill = ire->ire_ipif->ipif_ill;
8058 
8059 			if (IS_IPMP(ill)) {
8060 				dst_ill =
8061 				    ipmp_illgrp_hold_next_ill(ill->ill_grp);
8062 			} else {
8063 				dst_ill = ill;
8064 				ill_refhold(dst_ill);
8065 			}
8066 		}
8067 
8068 		if (dst_ill == NULL) {
8069 			if (ip_debug > 2) {
8070 				pr_addr_dbg("ip_newroute: no dst "
8071 				    "ill for dst %s\n", AF_INET, &dst);
8072 			}
8073 			goto icmp_err_ret;
8074 		}
8075 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8076 
8077 		/*
8078 		 * Pick the best source address from dst_ill.
8079 		 *
8080 		 * 1) Try to pick the source address from the destination
8081 		 *    route. Clustering assumes that when we have multiple
8082 		 *    prefixes hosted on an interface, the prefix of the
8083 		 *    source address matches the prefix of the destination
8084 		 *    route. We do this only if the address is not
8085 		 *    DEPRECATED.
8086 		 *
8087 		 * 2) If the conn is in a different zone than the ire, we
8088 		 *    need to pick a source address from the right zone.
8089 		 */
8090 		ASSERT(src_ipif == NULL);
8091 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8092 			/*
8093 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8094 			 * Check that the ipif matching the requested source
8095 			 * address still exists.
8096 			 */
8097 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8098 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8099 		}
8100 
8101 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8102 
8103 		if (src_ipif == NULL &&
8104 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8105 			ire_marks |= IRE_MARK_USESRC_CHECK;
8106 			if (!IS_UNDER_IPMP(ire->ire_ipif->ipif_ill) &&
8107 			    IS_IPMP(ire->ire_ipif->ipif_ill) ||
8108 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8109 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8110 			    ire->ire_zoneid != ALL_ZONES) ||
8111 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8112 				/*
8113 				 * If the destination is reachable via a
8114 				 * given gateway, the selected source address
8115 				 * should be in the same subnet as the gateway.
8116 				 * Otherwise, the destination is not reachable.
8117 				 *
8118 				 * If there are no interfaces on the same subnet
8119 				 * as the destination, ipif_select_source gives
8120 				 * first non-deprecated interface which might be
8121 				 * on a different subnet than the gateway.
8122 				 * This is not desirable. Hence pass the dst_ire
8123 				 * source address to ipif_select_source.
8124 				 * It is sure that the destination is reachable
8125 				 * with the dst_ire source address subnet.
8126 				 * So passing dst_ire source address to
8127 				 * ipif_select_source will make sure that the
8128 				 * selected source will be on the same subnet
8129 				 * as dst_ire source address.
8130 				 */
8131 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8132 
8133 				src_ipif = ipif_select_source(dst_ill, saddr,
8134 				    zoneid);
8135 				if (src_ipif == NULL) {
8136 					if (ip_debug > 2) {
8137 						pr_addr_dbg("ip_newroute: "
8138 						    "no src for dst %s ",
8139 						    AF_INET, &dst);
8140 						printf("on interface %s\n",
8141 						    dst_ill->ill_name);
8142 					}
8143 					goto icmp_err_ret;
8144 				}
8145 			} else {
8146 				src_ipif = ire->ire_ipif;
8147 				ASSERT(src_ipif != NULL);
8148 				/* hold src_ipif for uniformity */
8149 				ipif_refhold(src_ipif);
8150 			}
8151 		}
8152 
8153 		/*
8154 		 * Assign a source address while we have the conn.
8155 		 * We can't have ip_wput_ire pick a source address when the
8156 		 * packet returns from arp since we need to look at
8157 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8158 		 * going through arp.
8159 		 *
8160 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8161 		 *	  it uses ip6i to store this information.
8162 		 */
8163 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8164 			ipha->ipha_src = src_ipif->ipif_src_addr;
8165 
8166 		if (ip_debug > 3) {
8167 			/* ip2dbg */
8168 			pr_addr_dbg("ip_newroute: first hop %s\n",
8169 			    AF_INET, &gw);
8170 		}
8171 		ip2dbg(("\tire type %s (%d)\n",
8172 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8173 
8174 		/*
8175 		 * The TTL of multirouted packets is bounded by the
8176 		 * ip_multirt_ttl ndd variable.
8177 		 */
8178 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8179 			/* Force TTL of multirouted packets */
8180 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8181 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8182 				ip2dbg(("ip_newroute: forcing multirt TTL "
8183 				    "to %d (was %d), dst 0x%08x\n",
8184 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8185 				    ntohl(sire->ire_addr)));
8186 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8187 			}
8188 		}
8189 		/*
8190 		 * At this point in ip_newroute(), ire is either the
8191 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8192 		 * destination or an IRE_INTERFACE type that should be used
8193 		 * to resolve an on-subnet destination or an on-subnet
8194 		 * next-hop gateway.
8195 		 *
8196 		 * In the IRE_CACHE case, we have the following :
8197 		 *
8198 		 * 1) src_ipif - used for getting a source address.
8199 		 *
8200 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8201 		 *    means packets using this IRE_CACHE will go out on
8202 		 *    dst_ill.
8203 		 *
8204 		 * 3) The IRE sire will point to the prefix that is the
8205 		 *    longest  matching route for the destination. These
8206 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8207 		 *
8208 		 *    The newly created IRE_CACHE entry for the off-subnet
8209 		 *    destination is tied to both the prefix route and the
8210 		 *    interface route used to resolve the next-hop gateway
8211 		 *    via the ire_phandle and ire_ihandle fields,
8212 		 *    respectively.
8213 		 *
8214 		 * In the IRE_INTERFACE case, we have the following :
8215 		 *
8216 		 * 1) src_ipif - used for getting a source address.
8217 		 *
8218 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8219 		 *    means packets using the IRE_CACHE that we will build
8220 		 *    here will go out on dst_ill.
8221 		 *
8222 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8223 		 *    to be created will only be tied to the IRE_INTERFACE
8224 		 *    that was derived from the ire_ihandle field.
8225 		 *
8226 		 *    If sire is non-NULL, it means the destination is
8227 		 *    off-link and we will first create the IRE_CACHE for the
8228 		 *    gateway. Next time through ip_newroute, we will create
8229 		 *    the IRE_CACHE for the final destination as described
8230 		 *    above.
8231 		 *
8232 		 * In both cases, after the current resolution has been
8233 		 * completed (or possibly initialised, in the IRE_INTERFACE
8234 		 * case), the loop may be re-entered to attempt the resolution
8235 		 * of another RTF_MULTIRT route.
8236 		 *
8237 		 * When an IRE_CACHE entry for the off-subnet destination is
8238 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8239 		 * for further processing in emission loops.
8240 		 */
8241 		save_ire = ire;
8242 		switch (ire->ire_type) {
8243 		case IRE_CACHE: {
8244 			ire_t	*ipif_ire;
8245 
8246 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8247 			if (gw == 0)
8248 				gw = ire->ire_gateway_addr;
8249 			/*
8250 			 * We need 3 ire's to create a new cache ire for an
8251 			 * off-link destination from the cache ire of the
8252 			 * gateway.
8253 			 *
8254 			 *	1. The prefix ire 'sire' (Note that this does
8255 			 *	   not apply to the conn_nexthop_set case)
8256 			 *	2. The cache ire of the gateway 'ire'
8257 			 *	3. The interface ire 'ipif_ire'
8258 			 *
8259 			 * We have (1) and (2). We lookup (3) below.
8260 			 *
8261 			 * If there is no interface route to the gateway,
8262 			 * it is a race condition, where we found the cache
8263 			 * but the interface route has been deleted.
8264 			 */
8265 			if (ip_nexthop) {
8266 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8267 			} else {
8268 				ipif_ire =
8269 				    ire_ihandle_lookup_offlink(ire, sire);
8270 			}
8271 			if (ipif_ire == NULL) {
8272 				ip1dbg(("ip_newroute: "
8273 				    "ire_ihandle_lookup_offlink failed\n"));
8274 				goto icmp_err_ret;
8275 			}
8276 
8277 			/*
8278 			 * Check cached gateway IRE for any security
8279 			 * attributes; if found, associate the gateway
8280 			 * credentials group to the destination IRE.
8281 			 */
8282 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8283 				mutex_enter(&attrp->igsa_lock);
8284 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8285 					GCGRP_REFHOLD(gcgrp);
8286 				mutex_exit(&attrp->igsa_lock);
8287 			}
8288 
8289 			/*
8290 			 * XXX For the source of the resolver mp,
8291 			 * we are using the same DL_UNITDATA_REQ
8292 			 * (from save_ire->ire_nce->nce_res_mp)
8293 			 * though the save_ire is not pointing at the same ill.
8294 			 * This is incorrect. We need to send it up to the
8295 			 * resolver to get the right res_mp. For ethernets
8296 			 * this may be okay (ill_type == DL_ETHER).
8297 			 */
8298 
8299 			ire = ire_create(
8300 			    (uchar_t *)&dst,		/* dest address */
8301 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8302 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8303 			    (uchar_t *)&gw,		/* gateway address */
8304 			    &save_ire->ire_max_frag,
8305 			    save_ire->ire_nce,		/* src nce */
8306 			    dst_ill->ill_rq,		/* recv-from queue */
8307 			    dst_ill->ill_wq,		/* send-to queue */
8308 			    IRE_CACHE,			/* IRE type */
8309 			    src_ipif,
8310 			    (sire != NULL) ?
8311 			    sire->ire_mask : 0, 	/* Parent mask */
8312 			    (sire != NULL) ?
8313 			    sire->ire_phandle : 0,	/* Parent handle */
8314 			    ipif_ire->ire_ihandle,	/* Interface handle */
8315 			    (sire != NULL) ? (sire->ire_flags &
8316 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8317 			    (sire != NULL) ?
8318 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8319 			    NULL,
8320 			    gcgrp,
8321 			    ipst);
8322 
8323 			if (ire == NULL) {
8324 				if (gcgrp != NULL) {
8325 					GCGRP_REFRELE(gcgrp);
8326 					gcgrp = NULL;
8327 				}
8328 				ire_refrele(ipif_ire);
8329 				ire_refrele(save_ire);
8330 				break;
8331 			}
8332 
8333 			/* reference now held by IRE */
8334 			gcgrp = NULL;
8335 
8336 			ire->ire_marks |= ire_marks;
8337 
8338 			/*
8339 			 * Prevent sire and ipif_ire from getting deleted.
8340 			 * The newly created ire is tied to both of them via
8341 			 * the phandle and ihandle respectively.
8342 			 */
8343 			if (sire != NULL) {
8344 				IRB_REFHOLD(sire->ire_bucket);
8345 				/* Has it been removed already ? */
8346 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8347 					IRB_REFRELE(sire->ire_bucket);
8348 					ire_refrele(ipif_ire);
8349 					ire_refrele(save_ire);
8350 					break;
8351 				}
8352 			}
8353 
8354 			IRB_REFHOLD(ipif_ire->ire_bucket);
8355 			/* Has it been removed already ? */
8356 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8357 				IRB_REFRELE(ipif_ire->ire_bucket);
8358 				if (sire != NULL)
8359 					IRB_REFRELE(sire->ire_bucket);
8360 				ire_refrele(ipif_ire);
8361 				ire_refrele(save_ire);
8362 				break;
8363 			}
8364 
8365 			xmit_mp = first_mp;
8366 			/*
8367 			 * In the case of multirouting, a copy
8368 			 * of the packet is done before its sending.
8369 			 * The copy is used to attempt another
8370 			 * route resolution, in a next loop.
8371 			 */
8372 			if (ire->ire_flags & RTF_MULTIRT) {
8373 				copy_mp = copymsg(first_mp);
8374 				if (copy_mp != NULL) {
8375 					xmit_mp = copy_mp;
8376 					MULTIRT_DEBUG_TAG(first_mp);
8377 				}
8378 			}
8379 
8380 			ire_add_then_send(q, ire, xmit_mp);
8381 			ire_refrele(save_ire);
8382 
8383 			/* Assert that sire is not deleted yet. */
8384 			if (sire != NULL) {
8385 				ASSERT(sire->ire_ptpn != NULL);
8386 				IRB_REFRELE(sire->ire_bucket);
8387 			}
8388 
8389 			/* Assert that ipif_ire is not deleted yet. */
8390 			ASSERT(ipif_ire->ire_ptpn != NULL);
8391 			IRB_REFRELE(ipif_ire->ire_bucket);
8392 			ire_refrele(ipif_ire);
8393 
8394 			/*
8395 			 * If copy_mp is not NULL, multirouting was
8396 			 * requested. We loop to initiate a next
8397 			 * route resolution attempt, starting from sire.
8398 			 */
8399 			if (copy_mp != NULL) {
8400 				/*
8401 				 * Search for the next unresolved
8402 				 * multirt route.
8403 				 */
8404 				copy_mp = NULL;
8405 				ipif_ire = NULL;
8406 				ire = NULL;
8407 				multirt_resolve_next = B_TRUE;
8408 				continue;
8409 			}
8410 			if (sire != NULL)
8411 				ire_refrele(sire);
8412 			ipif_refrele(src_ipif);
8413 			ill_refrele(dst_ill);
8414 			return;
8415 		}
8416 		case IRE_IF_NORESOLVER: {
8417 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8418 			    dst_ill->ill_resolver_mp == NULL) {
8419 				ip1dbg(("ip_newroute: dst_ill %p "
8420 				    "for IRE_IF_NORESOLVER ire %p has "
8421 				    "no ill_resolver_mp\n",
8422 				    (void *)dst_ill, (void *)ire));
8423 				break;
8424 			}
8425 
8426 			/*
8427 			 * TSol note: We are creating the ire cache for the
8428 			 * destination 'dst'. If 'dst' is offlink, going
8429 			 * through the first hop 'gw', the security attributes
8430 			 * of 'dst' must be set to point to the gateway
8431 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8432 			 * is possible that 'dst' is a potential gateway that is
8433 			 * referenced by some route that has some security
8434 			 * attributes. Thus in the former case, we need to do a
8435 			 * gcgrp_lookup of 'gw' while in the latter case we
8436 			 * need to do gcgrp_lookup of 'dst' itself.
8437 			 */
8438 			ga.ga_af = AF_INET;
8439 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8440 			    &ga.ga_addr);
8441 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8442 
8443 			ire = ire_create(
8444 			    (uchar_t *)&dst,		/* dest address */
8445 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8446 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8447 			    (uchar_t *)&gw,		/* gateway address */
8448 			    &save_ire->ire_max_frag,
8449 			    NULL,			/* no src nce */
8450 			    dst_ill->ill_rq,		/* recv-from queue */
8451 			    dst_ill->ill_wq,		/* send-to queue */
8452 			    IRE_CACHE,
8453 			    src_ipif,
8454 			    save_ire->ire_mask,		/* Parent mask */
8455 			    (sire != NULL) ?		/* Parent handle */
8456 			    sire->ire_phandle : 0,
8457 			    save_ire->ire_ihandle,	/* Interface handle */
8458 			    (sire != NULL) ? sire->ire_flags &
8459 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8460 			    &(save_ire->ire_uinfo),
8461 			    NULL,
8462 			    gcgrp,
8463 			    ipst);
8464 
8465 			if (ire == NULL) {
8466 				if (gcgrp != NULL) {
8467 					GCGRP_REFRELE(gcgrp);
8468 					gcgrp = NULL;
8469 				}
8470 				ire_refrele(save_ire);
8471 				break;
8472 			}
8473 
8474 			/* reference now held by IRE */
8475 			gcgrp = NULL;
8476 
8477 			ire->ire_marks |= ire_marks;
8478 
8479 			/* Prevent save_ire from getting deleted */
8480 			IRB_REFHOLD(save_ire->ire_bucket);
8481 			/* Has it been removed already ? */
8482 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8483 				IRB_REFRELE(save_ire->ire_bucket);
8484 				ire_refrele(save_ire);
8485 				break;
8486 			}
8487 
8488 			/*
8489 			 * In the case of multirouting, a copy
8490 			 * of the packet is made before it is sent.
8491 			 * The copy is used in the next
8492 			 * loop to attempt another resolution.
8493 			 */
8494 			xmit_mp = first_mp;
8495 			if ((sire != NULL) &&
8496 			    (sire->ire_flags & RTF_MULTIRT)) {
8497 				copy_mp = copymsg(first_mp);
8498 				if (copy_mp != NULL) {
8499 					xmit_mp = copy_mp;
8500 					MULTIRT_DEBUG_TAG(first_mp);
8501 				}
8502 			}
8503 			ire_add_then_send(q, ire, xmit_mp);
8504 
8505 			/* Assert that it is not deleted yet. */
8506 			ASSERT(save_ire->ire_ptpn != NULL);
8507 			IRB_REFRELE(save_ire->ire_bucket);
8508 			ire_refrele(save_ire);
8509 
8510 			if (copy_mp != NULL) {
8511 				/*
8512 				 * If we found a (no)resolver, we ignore any
8513 				 * trailing top priority IRE_CACHE in further
8514 				 * loops. This ensures that we do not omit any
8515 				 * (no)resolver.
8516 				 * This IRE_CACHE, if any, will be processed
8517 				 * by another thread entering ip_newroute().
8518 				 * IRE_CACHE entries, if any, will be processed
8519 				 * by another thread entering ip_newroute(),
8520 				 * (upon resolver response, for instance).
8521 				 * This aims to force parallel multirt
8522 				 * resolutions as soon as a packet must be sent.
8523 				 * In the best case, after the tx of only one
8524 				 * packet, all reachable routes are resolved.
8525 				 * Otherwise, the resolution of all RTF_MULTIRT
8526 				 * routes would require several emissions.
8527 				 */
8528 				multirt_flags &= ~MULTIRT_CACHEGW;
8529 
8530 				/*
8531 				 * Search for the next unresolved multirt
8532 				 * route.
8533 				 */
8534 				copy_mp = NULL;
8535 				save_ire = NULL;
8536 				ire = NULL;
8537 				multirt_resolve_next = B_TRUE;
8538 				continue;
8539 			}
8540 
8541 			/*
8542 			 * Don't need sire anymore
8543 			 */
8544 			if (sire != NULL)
8545 				ire_refrele(sire);
8546 
8547 			ipif_refrele(src_ipif);
8548 			ill_refrele(dst_ill);
8549 			return;
8550 		}
8551 		case IRE_IF_RESOLVER:
8552 			/*
8553 			 * We can't build an IRE_CACHE yet, but at least we
8554 			 * found a resolver that can help.
8555 			 */
8556 			res_mp = dst_ill->ill_resolver_mp;
8557 			if (!OK_RESOLVER_MP(res_mp))
8558 				break;
8559 
8560 			/*
8561 			 * To be at this point in the code with a non-zero gw
8562 			 * means that dst is reachable through a gateway that
8563 			 * we have never resolved.  By changing dst to the gw
8564 			 * addr we resolve the gateway first.
8565 			 * When ire_add_then_send() tries to put the IP dg
8566 			 * to dst, it will reenter ip_newroute() at which
8567 			 * time we will find the IRE_CACHE for the gw and
8568 			 * create another IRE_CACHE in case IRE_CACHE above.
8569 			 */
8570 			if (gw != INADDR_ANY) {
8571 				/*
8572 				 * The source ipif that was determined above was
8573 				 * relative to the destination address, not the
8574 				 * gateway's. If src_ipif was not taken out of
8575 				 * the IRE_IF_RESOLVER entry, we'll need to call
8576 				 * ipif_select_source() again.
8577 				 */
8578 				if (src_ipif != ire->ire_ipif) {
8579 					ipif_refrele(src_ipif);
8580 					src_ipif = ipif_select_source(dst_ill,
8581 					    gw, zoneid);
8582 					if (src_ipif == NULL) {
8583 						if (ip_debug > 2) {
8584 							pr_addr_dbg(
8585 							    "ip_newroute: no "
8586 							    "src for gw %s ",
8587 							    AF_INET, &gw);
8588 							printf("on "
8589 							    "interface %s\n",
8590 							    dst_ill->ill_name);
8591 						}
8592 						goto icmp_err_ret;
8593 					}
8594 				}
8595 				save_dst = dst;
8596 				dst = gw;
8597 				gw = INADDR_ANY;
8598 			}
8599 
8600 			/*
8601 			 * We obtain a partial IRE_CACHE which we will pass
8602 			 * along with the resolver query.  When the response
8603 			 * comes back it will be there ready for us to add.
8604 			 * The ire_max_frag is atomically set under the
8605 			 * irebucket lock in ire_add_v[46].
8606 			 */
8607 
8608 			ire = ire_create_mp(
8609 			    (uchar_t *)&dst,		/* dest address */
8610 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8611 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8612 			    (uchar_t *)&gw,		/* gateway address */
8613 			    NULL,			/* ire_max_frag */
8614 			    NULL,			/* no src nce */
8615 			    dst_ill->ill_rq,		/* recv-from queue */
8616 			    dst_ill->ill_wq,		/* send-to queue */
8617 			    IRE_CACHE,
8618 			    src_ipif,			/* Interface ipif */
8619 			    save_ire->ire_mask,		/* Parent mask */
8620 			    0,
8621 			    save_ire->ire_ihandle,	/* Interface handle */
8622 			    0,				/* flags if any */
8623 			    &(save_ire->ire_uinfo),
8624 			    NULL,
8625 			    NULL,
8626 			    ipst);
8627 
8628 			if (ire == NULL) {
8629 				ire_refrele(save_ire);
8630 				break;
8631 			}
8632 
8633 			if ((sire != NULL) &&
8634 			    (sire->ire_flags & RTF_MULTIRT)) {
8635 				copy_mp = copymsg(first_mp);
8636 				if (copy_mp != NULL)
8637 					MULTIRT_DEBUG_TAG(copy_mp);
8638 			}
8639 
8640 			ire->ire_marks |= ire_marks;
8641 
8642 			/*
8643 			 * Construct message chain for the resolver
8644 			 * of the form:
8645 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8646 			 * Packet could contain a IPSEC_OUT mp.
8647 			 *
8648 			 * NOTE : ire will be added later when the response
8649 			 * comes back from ARP. If the response does not
8650 			 * come back, ARP frees the packet. For this reason,
8651 			 * we can't REFHOLD the bucket of save_ire to prevent
8652 			 * deletions. We may not be able to REFRELE the bucket
8653 			 * if the response never comes back. Thus, before
8654 			 * adding the ire, ire_add_v4 will make sure that the
8655 			 * interface route does not get deleted. This is the
8656 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8657 			 * where we can always prevent deletions because of
8658 			 * the synchronous nature of adding IRES i.e
8659 			 * ire_add_then_send is called after creating the IRE.
8660 			 */
8661 			ASSERT(ire->ire_mp != NULL);
8662 			ire->ire_mp->b_cont = first_mp;
8663 			/* Have saved_mp handy, for cleanup if canput fails */
8664 			saved_mp = mp;
8665 			mp = copyb(res_mp);
8666 			if (mp == NULL) {
8667 				/* Prepare for cleanup */
8668 				mp = saved_mp; /* pkt */
8669 				ire_delete(ire); /* ire_mp */
8670 				ire = NULL;
8671 				ire_refrele(save_ire);
8672 				if (copy_mp != NULL) {
8673 					MULTIRT_DEBUG_UNTAG(copy_mp);
8674 					freemsg(copy_mp);
8675 					copy_mp = NULL;
8676 				}
8677 				break;
8678 			}
8679 			linkb(mp, ire->ire_mp);
8680 
8681 			/*
8682 			 * Fill in the source and dest addrs for the resolver.
8683 			 * NOTE: this depends on memory layouts imposed by
8684 			 * ill_init().
8685 			 */
8686 			areq = (areq_t *)mp->b_rptr;
8687 			addrp = (ipaddr_t *)((char *)areq +
8688 			    areq->areq_sender_addr_offset);
8689 			*addrp = save_ire->ire_src_addr;
8690 
8691 			ire_refrele(save_ire);
8692 			addrp = (ipaddr_t *)((char *)areq +
8693 			    areq->areq_target_addr_offset);
8694 			*addrp = dst;
8695 			/* Up to the resolver. */
8696 			if (canputnext(dst_ill->ill_rq) &&
8697 			    !(dst_ill->ill_arp_closing)) {
8698 				putnext(dst_ill->ill_rq, mp);
8699 				ire = NULL;
8700 				if (copy_mp != NULL) {
8701 					/*
8702 					 * If we found a resolver, we ignore
8703 					 * any trailing top priority IRE_CACHE
8704 					 * in the further loops. This ensures
8705 					 * that we do not omit any resolver.
8706 					 * IRE_CACHE entries, if any, will be
8707 					 * processed next time we enter
8708 					 * ip_newroute().
8709 					 */
8710 					multirt_flags &= ~MULTIRT_CACHEGW;
8711 					/*
8712 					 * Search for the next unresolved
8713 					 * multirt route.
8714 					 */
8715 					first_mp = copy_mp;
8716 					copy_mp = NULL;
8717 					/* Prepare the next resolution loop. */
8718 					mp = first_mp;
8719 					EXTRACT_PKT_MP(mp, first_mp,
8720 					    mctl_present);
8721 					if (mctl_present)
8722 						io = (ipsec_out_t *)
8723 						    first_mp->b_rptr;
8724 					ipha = (ipha_t *)mp->b_rptr;
8725 
8726 					ASSERT(sire != NULL);
8727 
8728 					dst = save_dst;
8729 					multirt_resolve_next = B_TRUE;
8730 					continue;
8731 				}
8732 
8733 				if (sire != NULL)
8734 					ire_refrele(sire);
8735 
8736 				/*
8737 				 * The response will come back in ip_wput
8738 				 * with db_type IRE_DB_TYPE.
8739 				 */
8740 				ipif_refrele(src_ipif);
8741 				ill_refrele(dst_ill);
8742 				return;
8743 			} else {
8744 				/* Prepare for cleanup */
8745 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8746 				    mp);
8747 				mp->b_cont = NULL;
8748 				freeb(mp); /* areq */
8749 				/*
8750 				 * this is an ire that is not added to the
8751 				 * cache. ire_freemblk will handle the release
8752 				 * of any resources associated with the ire.
8753 				 */
8754 				ire_delete(ire); /* ire_mp */
8755 				mp = saved_mp; /* pkt */
8756 				ire = NULL;
8757 				if (copy_mp != NULL) {
8758 					MULTIRT_DEBUG_UNTAG(copy_mp);
8759 					freemsg(copy_mp);
8760 					copy_mp = NULL;
8761 				}
8762 				break;
8763 			}
8764 		default:
8765 			break;
8766 		}
8767 	} while (multirt_resolve_next);
8768 
8769 	ip1dbg(("ip_newroute: dropped\n"));
8770 	/* Did this packet originate externally? */
8771 	if (mp->b_prev) {
8772 		mp->b_next = NULL;
8773 		mp->b_prev = NULL;
8774 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8775 	} else {
8776 		if (dst_ill != NULL) {
8777 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8778 		} else {
8779 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8780 		}
8781 	}
8782 	ASSERT(copy_mp == NULL);
8783 	MULTIRT_DEBUG_UNTAG(first_mp);
8784 	freemsg(first_mp);
8785 	if (ire != NULL)
8786 		ire_refrele(ire);
8787 	if (sire != NULL)
8788 		ire_refrele(sire);
8789 	if (src_ipif != NULL)
8790 		ipif_refrele(src_ipif);
8791 	if (dst_ill != NULL)
8792 		ill_refrele(dst_ill);
8793 	return;
8794 
8795 icmp_err_ret:
8796 	ip1dbg(("ip_newroute: no route\n"));
8797 	if (src_ipif != NULL)
8798 		ipif_refrele(src_ipif);
8799 	if (dst_ill != NULL)
8800 		ill_refrele(dst_ill);
8801 	if (sire != NULL)
8802 		ire_refrele(sire);
8803 	/* Did this packet originate externally? */
8804 	if (mp->b_prev) {
8805 		mp->b_next = NULL;
8806 		mp->b_prev = NULL;
8807 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8808 		q = WR(q);
8809 	} else {
8810 		/*
8811 		 * There is no outgoing ill, so just increment the
8812 		 * system MIB.
8813 		 */
8814 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8815 		/*
8816 		 * Since ip_wput() isn't close to finished, we fill
8817 		 * in enough of the header for credible error reporting.
8818 		 */
8819 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8820 			/* Failed */
8821 			MULTIRT_DEBUG_UNTAG(first_mp);
8822 			freemsg(first_mp);
8823 			if (ire != NULL)
8824 				ire_refrele(ire);
8825 			return;
8826 		}
8827 	}
8828 
8829 	/*
8830 	 * At this point we will have ire only if RTF_BLACKHOLE
8831 	 * or RTF_REJECT flags are set on the IRE. It will not
8832 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8833 	 */
8834 	if (ire != NULL) {
8835 		if (ire->ire_flags & RTF_BLACKHOLE) {
8836 			ire_refrele(ire);
8837 			MULTIRT_DEBUG_UNTAG(first_mp);
8838 			freemsg(first_mp);
8839 			return;
8840 		}
8841 		ire_refrele(ire);
8842 	}
8843 	if (ip_source_routed(ipha, ipst)) {
8844 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8845 		    zoneid, ipst);
8846 		return;
8847 	}
8848 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8849 }
8850 
8851 ip_opt_info_t zero_info;
8852 
8853 /*
8854  * IPv4 -
8855  * ip_newroute_ipif is called by ip_wput_multicast and
8856  * ip_rput_forward_multicast whenever we need to send
8857  * out a packet to a destination address for which we do not have specific
8858  * routing information. It is used when the packet will be sent out
8859  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
8860  * socket option is set or icmp error message wants to go out on a particular
8861  * interface for a unicast packet.
8862  *
8863  * In most cases, the destination address is resolved thanks to the ipif
8864  * intrinsic resolver. However, there are some cases where the call to
8865  * ip_newroute_ipif must take into account the potential presence of
8866  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8867  * that uses the interface. This is specified through flags,
8868  * which can be a combination of:
8869  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8870  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8871  *   and flags. Additionally, the packet source address has to be set to
8872  *   the specified address. The caller is thus expected to set this flag
8873  *   if the packet has no specific source address yet.
8874  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8875  *   flag, the resulting ire will inherit the flag. All unresolved routes
8876  *   to the destination must be explored in the same call to
8877  *   ip_newroute_ipif().
8878  */
8879 static void
8880 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8881     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
8882 {
8883 	areq_t	*areq;
8884 	ire_t	*ire = NULL;
8885 	mblk_t	*res_mp;
8886 	ipaddr_t *addrp;
8887 	mblk_t *first_mp;
8888 	ire_t	*save_ire = NULL;
8889 	ipif_t	*src_ipif = NULL;
8890 	ushort_t ire_marks = 0;
8891 	ill_t	*dst_ill = NULL;
8892 	ipha_t *ipha;
8893 	mblk_t	*saved_mp;
8894 	ire_t   *fire = NULL;
8895 	mblk_t  *copy_mp = NULL;
8896 	boolean_t multirt_resolve_next;
8897 	boolean_t unspec_src;
8898 	ipaddr_t ipha_dst;
8899 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
8900 
8901 	/*
8902 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
8903 	 * here for uniformity
8904 	 */
8905 	ipif_refhold(ipif);
8906 
8907 	/*
8908 	 * This loop is run only once in most cases.
8909 	 * We loop to resolve further routes only when the destination
8910 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8911 	 */
8912 	do {
8913 		if (dst_ill != NULL) {
8914 			ill_refrele(dst_ill);
8915 			dst_ill = NULL;
8916 		}
8917 		if (src_ipif != NULL) {
8918 			ipif_refrele(src_ipif);
8919 			src_ipif = NULL;
8920 		}
8921 		multirt_resolve_next = B_FALSE;
8922 
8923 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
8924 		    ipif->ipif_ill->ill_name));
8925 
8926 		first_mp = mp;
8927 		if (DB_TYPE(mp) == M_CTL)
8928 			mp = mp->b_cont;
8929 		ipha = (ipha_t *)mp->b_rptr;
8930 
8931 		/*
8932 		 * Save the packet destination address, we may need it after
8933 		 * the packet has been consumed.
8934 		 */
8935 		ipha_dst = ipha->ipha_dst;
8936 
8937 		/*
8938 		 * If the interface is a pt-pt interface we look for an
8939 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
8940 		 * local_address and the pt-pt destination address. Otherwise
8941 		 * we just match the local address.
8942 		 * NOTE: dst could be different than ipha->ipha_dst in case
8943 		 * of sending igmp multicast packets over a point-to-point
8944 		 * connection.
8945 		 * Thus we must be careful enough to check ipha_dst to be a
8946 		 * multicast address, otherwise it will take xmit_if path for
8947 		 * multicast packets resulting into kernel stack overflow by
8948 		 * repeated calls to ip_newroute_ipif from ire_send().
8949 		 */
8950 		if (CLASSD(ipha_dst) &&
8951 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
8952 			goto err_ret;
8953 		}
8954 
8955 		/*
8956 		 * We check if an IRE_OFFSUBNET for the addr that goes through
8957 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
8958 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
8959 		 * propagate its flags to the new ire.
8960 		 */
8961 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
8962 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
8963 			ip2dbg(("ip_newroute_ipif: "
8964 			    "ipif_lookup_multi_ire("
8965 			    "ipif %p, dst %08x) = fire %p\n",
8966 			    (void *)ipif, ntohl(dst), (void *)fire));
8967 		}
8968 
8969 		/*
8970 		 * Note: While we pick a dst_ill we are really only
8971 		 * interested in the ill for load spreading. The source
8972 		 * ipif is determined by source address selection below.
8973 		 */
8974 		if (IS_IPMP(ipif->ipif_ill)) {
8975 			ipmp_illgrp_t *illg = ipif->ipif_ill->ill_grp;
8976 
8977 			if (CLASSD(ipha_dst))
8978 				dst_ill = ipmp_illgrp_hold_cast_ill(illg);
8979 			else
8980 				dst_ill = ipmp_illgrp_hold_next_ill(illg);
8981 		} else {
8982 			dst_ill = ipif->ipif_ill;
8983 			ill_refhold(dst_ill);
8984 		}
8985 
8986 		if (dst_ill == NULL) {
8987 			if (ip_debug > 2) {
8988 				pr_addr_dbg("ip_newroute_ipif: no dst ill "
8989 				    "for dst %s\n", AF_INET, &dst);
8990 			}
8991 			goto err_ret;
8992 		}
8993 
8994 		/*
8995 		 * Pick a source address preferring non-deprecated ones.
8996 		 * Unlike ip_newroute, we don't do any source address
8997 		 * selection here since for multicast it really does not help
8998 		 * in inbound load spreading as in the unicast case.
8999 		 */
9000 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9001 		    (fire->ire_flags & RTF_SETSRC)) {
9002 			/*
9003 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9004 			 * on that interface. This ire has RTF_SETSRC flag, so
9005 			 * the source address of the packet must be changed.
9006 			 * Check that the ipif matching the requested source
9007 			 * address still exists.
9008 			 */
9009 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9010 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9011 		}
9012 
9013 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9014 
9015 		if (!IS_UNDER_IPMP(ipif->ipif_ill) &&
9016 		    (IS_IPMP(ipif->ipif_ill) ||
9017 		    (!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9018 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9019 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9020 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9021 		    (src_ipif == NULL) &&
9022 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9023 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9024 			if (src_ipif == NULL) {
9025 				if (ip_debug > 2) {
9026 					/* ip1dbg */
9027 					pr_addr_dbg("ip_newroute_ipif: "
9028 					    "no src for dst %s",
9029 					    AF_INET, &dst);
9030 				}
9031 				ip1dbg((" on interface %s\n",
9032 				    dst_ill->ill_name));
9033 				goto err_ret;
9034 			}
9035 			ipif_refrele(ipif);
9036 			ipif = src_ipif;
9037 			ipif_refhold(ipif);
9038 		}
9039 		if (src_ipif == NULL) {
9040 			src_ipif = ipif;
9041 			ipif_refhold(src_ipif);
9042 		}
9043 
9044 		/*
9045 		 * Assign a source address while we have the conn.
9046 		 * We can't have ip_wput_ire pick a source address when the
9047 		 * packet returns from arp since conn_unspec_src might be set
9048 		 * and we lose the conn when going through arp.
9049 		 */
9050 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9051 			ipha->ipha_src = src_ipif->ipif_src_addr;
9052 
9053 		/*
9054 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9055 		 * that the outgoing interface does not have an interface ire.
9056 		 */
9057 		if (CLASSD(ipha_dst) && (connp == NULL ||
9058 		    connp->conn_outgoing_ill == NULL) &&
9059 		    infop->ip_opt_ill_index == 0) {
9060 			/* ipif_to_ire returns an held ire */
9061 			ire = ipif_to_ire(ipif);
9062 			if (ire == NULL)
9063 				goto err_ret;
9064 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9065 				goto err_ret;
9066 			save_ire = ire;
9067 
9068 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9069 			    "flags %04x\n",
9070 			    (void *)ire, (void *)ipif, flags));
9071 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9072 			    (fire->ire_flags & RTF_MULTIRT)) {
9073 				/*
9074 				 * As requested by flags, an IRE_OFFSUBNET was
9075 				 * looked up on that interface. This ire has
9076 				 * RTF_MULTIRT flag, so the resolution loop will
9077 				 * be re-entered to resolve additional routes on
9078 				 * other interfaces. For that purpose, a copy of
9079 				 * the packet is performed at this point.
9080 				 */
9081 				fire->ire_last_used_time = lbolt;
9082 				copy_mp = copymsg(first_mp);
9083 				if (copy_mp) {
9084 					MULTIRT_DEBUG_TAG(copy_mp);
9085 				}
9086 			}
9087 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9088 			    (fire->ire_flags & RTF_SETSRC)) {
9089 				/*
9090 				 * As requested by flags, an IRE_OFFSUBET was
9091 				 * looked up on that interface. This ire has
9092 				 * RTF_SETSRC flag, so the source address of the
9093 				 * packet must be changed.
9094 				 */
9095 				ipha->ipha_src = fire->ire_src_addr;
9096 			}
9097 		} else {
9098 			/*
9099 			 * The only ways we can come here are:
9100 			 * 1) IP_BOUND_IF socket option is set
9101 			 * 2) SO_DONTROUTE socket option is set
9102 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9103 			 * In all cases, the new ire will not be added
9104 			 * into cache table.
9105 			 */
9106 			ASSERT(connp == NULL || connp->conn_dontroute ||
9107 			    connp->conn_outgoing_ill != NULL ||
9108 			    infop->ip_opt_ill_index != 0);
9109 			ire_marks |= IRE_MARK_NOADD;
9110 		}
9111 
9112 		switch (ipif->ipif_net_type) {
9113 		case IRE_IF_NORESOLVER: {
9114 			/* We have what we need to build an IRE_CACHE. */
9115 
9116 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9117 			    (dst_ill->ill_resolver_mp == NULL)) {
9118 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9119 				    "for IRE_IF_NORESOLVER ire %p has "
9120 				    "no ill_resolver_mp\n",
9121 				    (void *)dst_ill, (void *)ire));
9122 				break;
9123 			}
9124 
9125 			/*
9126 			 * The new ire inherits the IRE_OFFSUBNET flags
9127 			 * and source address, if this was requested.
9128 			 */
9129 			ire = ire_create(
9130 			    (uchar_t *)&dst,		/* dest address */
9131 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9132 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9133 			    NULL,			/* gateway address */
9134 			    &ipif->ipif_mtu,
9135 			    NULL,			/* no src nce */
9136 			    dst_ill->ill_rq,		/* recv-from queue */
9137 			    dst_ill->ill_wq,		/* send-to queue */
9138 			    IRE_CACHE,
9139 			    src_ipif,
9140 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9141 			    (fire != NULL) ?		/* Parent handle */
9142 			    fire->ire_phandle : 0,
9143 			    (save_ire != NULL) ?	/* Interface handle */
9144 			    save_ire->ire_ihandle : 0,
9145 			    (fire != NULL) ?
9146 			    (fire->ire_flags &
9147 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9148 			    (save_ire == NULL ? &ire_uinfo_null :
9149 			    &save_ire->ire_uinfo),
9150 			    NULL,
9151 			    NULL,
9152 			    ipst);
9153 
9154 			if (ire == NULL) {
9155 				if (save_ire != NULL)
9156 					ire_refrele(save_ire);
9157 				break;
9158 			}
9159 
9160 			ire->ire_marks |= ire_marks;
9161 
9162 			/*
9163 			 * If IRE_MARK_NOADD is set then we need to convert
9164 			 * the max_fragp to a useable value now. This is
9165 			 * normally done in ire_add_v[46]. We also need to
9166 			 * associate the ire with an nce (normally would be
9167 			 * done in ip_wput_nondata()).
9168 			 *
9169 			 * Note that IRE_MARK_NOADD packets created here
9170 			 * do not have a non-null ire_mp pointer. The null
9171 			 * value of ire_bucket indicates that they were
9172 			 * never added.
9173 			 */
9174 			if (ire->ire_marks & IRE_MARK_NOADD) {
9175 				uint_t  max_frag;
9176 
9177 				max_frag = *ire->ire_max_fragp;
9178 				ire->ire_max_fragp = NULL;
9179 				ire->ire_max_frag = max_frag;
9180 
9181 				if ((ire->ire_nce = ndp_lookup_v4(
9182 				    ire_to_ill(ire),
9183 				    (ire->ire_gateway_addr != INADDR_ANY ?
9184 				    &ire->ire_gateway_addr : &ire->ire_addr),
9185 				    B_FALSE)) == NULL) {
9186 					if (save_ire != NULL)
9187 						ire_refrele(save_ire);
9188 					break;
9189 				}
9190 				ASSERT(ire->ire_nce->nce_state ==
9191 				    ND_REACHABLE);
9192 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9193 			}
9194 
9195 			/* Prevent save_ire from getting deleted */
9196 			if (save_ire != NULL) {
9197 				IRB_REFHOLD(save_ire->ire_bucket);
9198 				/* Has it been removed already ? */
9199 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9200 					IRB_REFRELE(save_ire->ire_bucket);
9201 					ire_refrele(save_ire);
9202 					break;
9203 				}
9204 			}
9205 
9206 			ire_add_then_send(q, ire, first_mp);
9207 
9208 			/* Assert that save_ire is not deleted yet. */
9209 			if (save_ire != NULL) {
9210 				ASSERT(save_ire->ire_ptpn != NULL);
9211 				IRB_REFRELE(save_ire->ire_bucket);
9212 				ire_refrele(save_ire);
9213 				save_ire = NULL;
9214 			}
9215 			if (fire != NULL) {
9216 				ire_refrele(fire);
9217 				fire = NULL;
9218 			}
9219 
9220 			/*
9221 			 * the resolution loop is re-entered if this
9222 			 * was requested through flags and if we
9223 			 * actually are in a multirouting case.
9224 			 */
9225 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9226 				boolean_t need_resolve =
9227 				    ire_multirt_need_resolve(ipha_dst,
9228 				    msg_getlabel(copy_mp), ipst);
9229 				if (!need_resolve) {
9230 					MULTIRT_DEBUG_UNTAG(copy_mp);
9231 					freemsg(copy_mp);
9232 					copy_mp = NULL;
9233 				} else {
9234 					/*
9235 					 * ipif_lookup_group() calls
9236 					 * ire_lookup_multi() that uses
9237 					 * ire_ftable_lookup() to find
9238 					 * an IRE_INTERFACE for the group.
9239 					 * In the multirt case,
9240 					 * ire_lookup_multi() then invokes
9241 					 * ire_multirt_lookup() to find
9242 					 * the next resolvable ire.
9243 					 * As a result, we obtain an new
9244 					 * interface, derived from the
9245 					 * next ire.
9246 					 */
9247 					ipif_refrele(ipif);
9248 					ipif = ipif_lookup_group(ipha_dst,
9249 					    zoneid, ipst);
9250 					ip2dbg(("ip_newroute_ipif: "
9251 					    "multirt dst %08x, ipif %p\n",
9252 					    htonl(dst), (void *)ipif));
9253 					if (ipif != NULL) {
9254 						mp = copy_mp;
9255 						copy_mp = NULL;
9256 						multirt_resolve_next = B_TRUE;
9257 						continue;
9258 					} else {
9259 						freemsg(copy_mp);
9260 					}
9261 				}
9262 			}
9263 			if (ipif != NULL)
9264 				ipif_refrele(ipif);
9265 			ill_refrele(dst_ill);
9266 			ipif_refrele(src_ipif);
9267 			return;
9268 		}
9269 		case IRE_IF_RESOLVER:
9270 			/*
9271 			 * We can't build an IRE_CACHE yet, but at least
9272 			 * we found a resolver that can help.
9273 			 */
9274 			res_mp = dst_ill->ill_resolver_mp;
9275 			if (!OK_RESOLVER_MP(res_mp))
9276 				break;
9277 
9278 			/*
9279 			 * We obtain a partial IRE_CACHE which we will pass
9280 			 * along with the resolver query.  When the response
9281 			 * comes back it will be there ready for us to add.
9282 			 * The new ire inherits the IRE_OFFSUBNET flags
9283 			 * and source address, if this was requested.
9284 			 * The ire_max_frag is atomically set under the
9285 			 * irebucket lock in ire_add_v[46]. Only in the
9286 			 * case of IRE_MARK_NOADD, we set it here itself.
9287 			 */
9288 			ire = ire_create_mp(
9289 			    (uchar_t *)&dst,		/* dest address */
9290 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9291 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9292 			    NULL,			/* gateway address */
9293 			    (ire_marks & IRE_MARK_NOADD) ?
9294 			    ipif->ipif_mtu : 0,		/* max_frag */
9295 			    NULL,			/* no src nce */
9296 			    dst_ill->ill_rq,		/* recv-from queue */
9297 			    dst_ill->ill_wq,		/* send-to queue */
9298 			    IRE_CACHE,
9299 			    src_ipif,
9300 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9301 			    (fire != NULL) ?		/* Parent handle */
9302 			    fire->ire_phandle : 0,
9303 			    (save_ire != NULL) ?	/* Interface handle */
9304 			    save_ire->ire_ihandle : 0,
9305 			    (fire != NULL) ?		/* flags if any */
9306 			    (fire->ire_flags &
9307 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9308 			    (save_ire == NULL ? &ire_uinfo_null :
9309 			    &save_ire->ire_uinfo),
9310 			    NULL,
9311 			    NULL,
9312 			    ipst);
9313 
9314 			if (save_ire != NULL) {
9315 				ire_refrele(save_ire);
9316 				save_ire = NULL;
9317 			}
9318 			if (ire == NULL)
9319 				break;
9320 
9321 			ire->ire_marks |= ire_marks;
9322 			/*
9323 			 * Construct message chain for the resolver of the
9324 			 * form:
9325 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9326 			 *
9327 			 * NOTE : ire will be added later when the response
9328 			 * comes back from ARP. If the response does not
9329 			 * come back, ARP frees the packet. For this reason,
9330 			 * we can't REFHOLD the bucket of save_ire to prevent
9331 			 * deletions. We may not be able to REFRELE the
9332 			 * bucket if the response never comes back.
9333 			 * Thus, before adding the ire, ire_add_v4 will make
9334 			 * sure that the interface route does not get deleted.
9335 			 * This is the only case unlike ip_newroute_v6,
9336 			 * ip_newroute_ipif_v6 where we can always prevent
9337 			 * deletions because ire_add_then_send is called after
9338 			 * creating the IRE.
9339 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9340 			 * does not add this IRE into the IRE CACHE.
9341 			 */
9342 			ASSERT(ire->ire_mp != NULL);
9343 			ire->ire_mp->b_cont = first_mp;
9344 			/* Have saved_mp handy, for cleanup if canput fails */
9345 			saved_mp = mp;
9346 			mp = copyb(res_mp);
9347 			if (mp == NULL) {
9348 				/* Prepare for cleanup */
9349 				mp = saved_mp; /* pkt */
9350 				ire_delete(ire); /* ire_mp */
9351 				ire = NULL;
9352 				if (copy_mp != NULL) {
9353 					MULTIRT_DEBUG_UNTAG(copy_mp);
9354 					freemsg(copy_mp);
9355 					copy_mp = NULL;
9356 				}
9357 				break;
9358 			}
9359 			linkb(mp, ire->ire_mp);
9360 
9361 			/*
9362 			 * Fill in the source and dest addrs for the resolver.
9363 			 * NOTE: this depends on memory layouts imposed by
9364 			 * ill_init().  There are corner cases above where we
9365 			 * might've created the IRE with an INADDR_ANY source
9366 			 * address (e.g., if the zeroth ipif on an underlying
9367 			 * ill in an IPMP group is 0.0.0.0, but another ipif
9368 			 * on the ill has a usable test address).  If so, tell
9369 			 * ARP to use ipha_src as its sender address.
9370 			 */
9371 			areq = (areq_t *)mp->b_rptr;
9372 			addrp = (ipaddr_t *)((char *)areq +
9373 			    areq->areq_sender_addr_offset);
9374 			if (ire->ire_src_addr != INADDR_ANY)
9375 				*addrp = ire->ire_src_addr;
9376 			else
9377 				*addrp = ipha->ipha_src;
9378 			addrp = (ipaddr_t *)((char *)areq +
9379 			    areq->areq_target_addr_offset);
9380 			*addrp = dst;
9381 			/* Up to the resolver. */
9382 			if (canputnext(dst_ill->ill_rq) &&
9383 			    !(dst_ill->ill_arp_closing)) {
9384 				putnext(dst_ill->ill_rq, mp);
9385 				/*
9386 				 * The response will come back in ip_wput
9387 				 * with db_type IRE_DB_TYPE.
9388 				 */
9389 			} else {
9390 				mp->b_cont = NULL;
9391 				freeb(mp); /* areq */
9392 				ire_delete(ire); /* ire_mp */
9393 				saved_mp->b_next = NULL;
9394 				saved_mp->b_prev = NULL;
9395 				freemsg(first_mp); /* pkt */
9396 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9397 			}
9398 
9399 			if (fire != NULL) {
9400 				ire_refrele(fire);
9401 				fire = NULL;
9402 			}
9403 
9404 			/*
9405 			 * The resolution loop is re-entered if this was
9406 			 * requested through flags and we actually are
9407 			 * in a multirouting case.
9408 			 */
9409 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9410 				boolean_t need_resolve =
9411 				    ire_multirt_need_resolve(ipha_dst,
9412 				    msg_getlabel(copy_mp), ipst);
9413 				if (!need_resolve) {
9414 					MULTIRT_DEBUG_UNTAG(copy_mp);
9415 					freemsg(copy_mp);
9416 					copy_mp = NULL;
9417 				} else {
9418 					/*
9419 					 * ipif_lookup_group() calls
9420 					 * ire_lookup_multi() that uses
9421 					 * ire_ftable_lookup() to find
9422 					 * an IRE_INTERFACE for the group.
9423 					 * In the multirt case,
9424 					 * ire_lookup_multi() then invokes
9425 					 * ire_multirt_lookup() to find
9426 					 * the next resolvable ire.
9427 					 * As a result, we obtain an new
9428 					 * interface, derived from the
9429 					 * next ire.
9430 					 */
9431 					ipif_refrele(ipif);
9432 					ipif = ipif_lookup_group(ipha_dst,
9433 					    zoneid, ipst);
9434 					if (ipif != NULL) {
9435 						mp = copy_mp;
9436 						copy_mp = NULL;
9437 						multirt_resolve_next = B_TRUE;
9438 						continue;
9439 					} else {
9440 						freemsg(copy_mp);
9441 					}
9442 				}
9443 			}
9444 			if (ipif != NULL)
9445 				ipif_refrele(ipif);
9446 			ill_refrele(dst_ill);
9447 			ipif_refrele(src_ipif);
9448 			return;
9449 		default:
9450 			break;
9451 		}
9452 	} while (multirt_resolve_next);
9453 
9454 err_ret:
9455 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9456 	if (fire != NULL)
9457 		ire_refrele(fire);
9458 	ipif_refrele(ipif);
9459 	/* Did this packet originate externally? */
9460 	if (dst_ill != NULL)
9461 		ill_refrele(dst_ill);
9462 	if (src_ipif != NULL)
9463 		ipif_refrele(src_ipif);
9464 	if (mp->b_prev || mp->b_next) {
9465 		mp->b_next = NULL;
9466 		mp->b_prev = NULL;
9467 	} else {
9468 		/*
9469 		 * Since ip_wput() isn't close to finished, we fill
9470 		 * in enough of the header for credible error reporting.
9471 		 */
9472 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9473 			/* Failed */
9474 			freemsg(first_mp);
9475 			if (ire != NULL)
9476 				ire_refrele(ire);
9477 			return;
9478 		}
9479 	}
9480 	/*
9481 	 * At this point we will have ire only if RTF_BLACKHOLE
9482 	 * or RTF_REJECT flags are set on the IRE. It will not
9483 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9484 	 */
9485 	if (ire != NULL) {
9486 		if (ire->ire_flags & RTF_BLACKHOLE) {
9487 			ire_refrele(ire);
9488 			freemsg(first_mp);
9489 			return;
9490 		}
9491 		ire_refrele(ire);
9492 	}
9493 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9494 }
9495 
9496 /* Name/Value Table Lookup Routine */
9497 char *
9498 ip_nv_lookup(nv_t *nv, int value)
9499 {
9500 	if (!nv)
9501 		return (NULL);
9502 	for (; nv->nv_name; nv++) {
9503 		if (nv->nv_value == value)
9504 			return (nv->nv_name);
9505 	}
9506 	return ("unknown");
9507 }
9508 
9509 /*
9510  * This is a module open, i.e. this is a control stream for access
9511  * to a DLPI device.  We allocate an ill_t as the instance data in
9512  * this case.
9513  */
9514 int
9515 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9516 {
9517 	ill_t	*ill;
9518 	int	err;
9519 	zoneid_t zoneid;
9520 	netstack_t *ns;
9521 	ip_stack_t *ipst;
9522 
9523 	/*
9524 	 * Prevent unprivileged processes from pushing IP so that
9525 	 * they can't send raw IP.
9526 	 */
9527 	if (secpolicy_net_rawaccess(credp) != 0)
9528 		return (EPERM);
9529 
9530 	ns = netstack_find_by_cred(credp);
9531 	ASSERT(ns != NULL);
9532 	ipst = ns->netstack_ip;
9533 	ASSERT(ipst != NULL);
9534 
9535 	/*
9536 	 * For exclusive stacks we set the zoneid to zero
9537 	 * to make IP operate as if in the global zone.
9538 	 */
9539 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9540 		zoneid = GLOBAL_ZONEID;
9541 	else
9542 		zoneid = crgetzoneid(credp);
9543 
9544 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9545 	q->q_ptr = WR(q)->q_ptr = ill;
9546 	ill->ill_ipst = ipst;
9547 	ill->ill_zoneid = zoneid;
9548 
9549 	/*
9550 	 * ill_init initializes the ill fields and then sends down
9551 	 * down a DL_INFO_REQ after calling qprocson.
9552 	 */
9553 	err = ill_init(q, ill);
9554 	if (err != 0) {
9555 		mi_free(ill);
9556 		netstack_rele(ipst->ips_netstack);
9557 		q->q_ptr = NULL;
9558 		WR(q)->q_ptr = NULL;
9559 		return (err);
9560 	}
9561 
9562 	/* ill_init initializes the ipsq marking this thread as writer */
9563 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
9564 	/* Wait for the DL_INFO_ACK */
9565 	mutex_enter(&ill->ill_lock);
9566 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9567 		/*
9568 		 * Return value of 0 indicates a pending signal.
9569 		 */
9570 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9571 		if (err == 0) {
9572 			mutex_exit(&ill->ill_lock);
9573 			(void) ip_close(q, 0);
9574 			return (EINTR);
9575 		}
9576 	}
9577 	mutex_exit(&ill->ill_lock);
9578 
9579 	/*
9580 	 * ip_rput_other could have set an error  in ill_error on
9581 	 * receipt of M_ERROR.
9582 	 */
9583 
9584 	err = ill->ill_error;
9585 	if (err != 0) {
9586 		(void) ip_close(q, 0);
9587 		return (err);
9588 	}
9589 
9590 	ill->ill_credp = credp;
9591 	crhold(credp);
9592 
9593 	mutex_enter(&ipst->ips_ip_mi_lock);
9594 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9595 	    credp);
9596 	mutex_exit(&ipst->ips_ip_mi_lock);
9597 	if (err) {
9598 		(void) ip_close(q, 0);
9599 		return (err);
9600 	}
9601 	return (0);
9602 }
9603 
9604 /* For /dev/ip aka AF_INET open */
9605 int
9606 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9607 {
9608 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9609 }
9610 
9611 /* For /dev/ip6 aka AF_INET6 open */
9612 int
9613 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9614 {
9615 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9616 }
9617 
9618 /* IP open routine. */
9619 int
9620 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9621     boolean_t isv6)
9622 {
9623 	conn_t 		*connp;
9624 	major_t		maj;
9625 	zoneid_t	zoneid;
9626 	netstack_t	*ns;
9627 	ip_stack_t	*ipst;
9628 
9629 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9630 
9631 	/* Allow reopen. */
9632 	if (q->q_ptr != NULL)
9633 		return (0);
9634 
9635 	if (sflag & MODOPEN) {
9636 		/* This is a module open */
9637 		return (ip_modopen(q, devp, flag, sflag, credp));
9638 	}
9639 
9640 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
9641 		/*
9642 		 * Non streams based socket looking for a stream
9643 		 * to access IP
9644 		 */
9645 		return (ip_helper_stream_setup(q, devp, flag, sflag,
9646 		    credp, isv6));
9647 	}
9648 
9649 	ns = netstack_find_by_cred(credp);
9650 	ASSERT(ns != NULL);
9651 	ipst = ns->netstack_ip;
9652 	ASSERT(ipst != NULL);
9653 
9654 	/*
9655 	 * For exclusive stacks we set the zoneid to zero
9656 	 * to make IP operate as if in the global zone.
9657 	 */
9658 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9659 		zoneid = GLOBAL_ZONEID;
9660 	else
9661 		zoneid = crgetzoneid(credp);
9662 
9663 	/*
9664 	 * We are opening as a device. This is an IP client stream, and we
9665 	 * allocate an conn_t as the instance data.
9666 	 */
9667 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9668 
9669 	/*
9670 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9671 	 * done by netstack_find_by_cred()
9672 	 */
9673 	netstack_rele(ipst->ips_netstack);
9674 
9675 	connp->conn_zoneid = zoneid;
9676 	connp->conn_sqp = NULL;
9677 	connp->conn_initial_sqp = NULL;
9678 	connp->conn_final_sqp = NULL;
9679 
9680 	connp->conn_upq = q;
9681 	q->q_ptr = WR(q)->q_ptr = connp;
9682 
9683 	if (flag & SO_SOCKSTR)
9684 		connp->conn_flags |= IPCL_SOCKET;
9685 
9686 	/* Minor tells us which /dev entry was opened */
9687 	if (isv6) {
9688 		connp->conn_flags |= IPCL_ISV6;
9689 		connp->conn_af_isv6 = B_TRUE;
9690 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9691 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9692 	} else {
9693 		connp->conn_af_isv6 = B_FALSE;
9694 		connp->conn_pkt_isv6 = B_FALSE;
9695 	}
9696 
9697 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9698 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9699 		connp->conn_minor_arena = ip_minor_arena_la;
9700 	} else {
9701 		/*
9702 		 * Either minor numbers in the large arena were exhausted
9703 		 * or a non socket application is doing the open.
9704 		 * Try to allocate from the small arena.
9705 		 */
9706 		if ((connp->conn_dev =
9707 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9708 			/* CONN_DEC_REF takes care of netstack_rele() */
9709 			q->q_ptr = WR(q)->q_ptr = NULL;
9710 			CONN_DEC_REF(connp);
9711 			return (EBUSY);
9712 		}
9713 		connp->conn_minor_arena = ip_minor_arena_sa;
9714 	}
9715 
9716 	maj = getemajor(*devp);
9717 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9718 
9719 	/*
9720 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9721 	 */
9722 	connp->conn_cred = credp;
9723 
9724 	/*
9725 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9726 	 */
9727 	connp->conn_recv = ip_conn_input;
9728 
9729 	crhold(connp->conn_cred);
9730 
9731 	/*
9732 	 * If the caller has the process-wide flag set, then default to MAC
9733 	 * exempt mode.  This allows read-down to unlabeled hosts.
9734 	 */
9735 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9736 		connp->conn_mac_exempt = B_TRUE;
9737 
9738 	connp->conn_rq = q;
9739 	connp->conn_wq = WR(q);
9740 
9741 	/* Non-zero default values */
9742 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9743 
9744 	/*
9745 	 * Make the conn globally visible to walkers
9746 	 */
9747 	ASSERT(connp->conn_ref == 1);
9748 	mutex_enter(&connp->conn_lock);
9749 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9750 	mutex_exit(&connp->conn_lock);
9751 
9752 	qprocson(q);
9753 
9754 	return (0);
9755 }
9756 
9757 /*
9758  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9759  * Note that there is no race since either ip_output function works - it
9760  * is just an optimization to enter the best ip_output routine directly.
9761  */
9762 void
9763 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9764     ip_stack_t *ipst)
9765 {
9766 	if (isv6)  {
9767 		if (bump_mib) {
9768 			BUMP_MIB(&ipst->ips_ip6_mib,
9769 			    ipIfStatsOutSwitchIPVersion);
9770 		}
9771 		connp->conn_send = ip_output_v6;
9772 		connp->conn_pkt_isv6 = B_TRUE;
9773 	} else {
9774 		if (bump_mib) {
9775 			BUMP_MIB(&ipst->ips_ip_mib,
9776 			    ipIfStatsOutSwitchIPVersion);
9777 		}
9778 		connp->conn_send = ip_output;
9779 		connp->conn_pkt_isv6 = B_FALSE;
9780 	}
9781 
9782 }
9783 
9784 /*
9785  * See if IPsec needs loading because of the options in mp.
9786  */
9787 static boolean_t
9788 ipsec_opt_present(mblk_t *mp)
9789 {
9790 	uint8_t *optcp, *next_optcp, *opt_endcp;
9791 	struct opthdr *opt;
9792 	struct T_opthdr *topt;
9793 	int opthdr_len;
9794 	t_uscalar_t optname, optlevel;
9795 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9796 	ipsec_req_t *ipsr;
9797 
9798 	/*
9799 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9800 	 * return TRUE.
9801 	 */
9802 
9803 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9804 	opt_endcp = optcp + tor->OPT_length;
9805 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9806 		opthdr_len = sizeof (struct T_opthdr);
9807 	} else {		/* O_OPTMGMT_REQ */
9808 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9809 		opthdr_len = sizeof (struct opthdr);
9810 	}
9811 	for (; optcp < opt_endcp; optcp = next_optcp) {
9812 		if (optcp + opthdr_len > opt_endcp)
9813 			return (B_FALSE);	/* Not enough option header. */
9814 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9815 			topt = (struct T_opthdr *)optcp;
9816 			optlevel = topt->level;
9817 			optname = topt->name;
9818 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9819 		} else {
9820 			opt = (struct opthdr *)optcp;
9821 			optlevel = opt->level;
9822 			optname = opt->name;
9823 			next_optcp = optcp + opthdr_len +
9824 			    _TPI_ALIGN_OPT(opt->len);
9825 		}
9826 		if ((next_optcp < optcp) || /* wraparound pointer space */
9827 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9828 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9829 			return (B_FALSE); /* bad option buffer */
9830 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9831 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9832 			/*
9833 			 * Check to see if it's an all-bypass or all-zeroes
9834 			 * IPsec request.  Don't bother loading IPsec if
9835 			 * the socket doesn't want to use it.  (A good example
9836 			 * is a bypass request.)
9837 			 *
9838 			 * Basically, if any of the non-NEVER bits are set,
9839 			 * load IPsec.
9840 			 */
9841 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9842 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9843 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9844 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9845 			    != 0)
9846 				return (B_TRUE);
9847 		}
9848 	}
9849 	return (B_FALSE);
9850 }
9851 
9852 /*
9853  * If conn is is waiting for ipsec to finish loading, kick it.
9854  */
9855 /* ARGSUSED */
9856 static void
9857 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9858 {
9859 	t_scalar_t	optreq_prim;
9860 	mblk_t		*mp;
9861 	cred_t		*cr;
9862 	int		err = 0;
9863 
9864 	/*
9865 	 * This function is called, after ipsec loading is complete.
9866 	 * Since IP checks exclusively and atomically (i.e it prevents
9867 	 * ipsec load from completing until ip_optcom_req completes)
9868 	 * whether ipsec load is complete, there cannot be a race with IP
9869 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9870 	 */
9871 	mutex_enter(&connp->conn_lock);
9872 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9873 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9874 		mp = connp->conn_ipsec_opt_mp;
9875 		connp->conn_ipsec_opt_mp = NULL;
9876 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9877 		mutex_exit(&connp->conn_lock);
9878 
9879 		/*
9880 		 * All Solaris components should pass a db_credp
9881 		 * for this TPI message, hence we ASSERT.
9882 		 * But in case there is some other M_PROTO that looks
9883 		 * like a TPI message sent by some other kernel
9884 		 * component, we check and return an error.
9885 		 */
9886 		cr = msg_getcred(mp, NULL);
9887 		ASSERT(cr != NULL);
9888 		if (cr == NULL) {
9889 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
9890 			if (mp != NULL)
9891 				qreply(connp->conn_wq, mp);
9892 			return;
9893 		}
9894 
9895 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9896 
9897 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9898 		if (optreq_prim == T_OPTMGMT_REQ) {
9899 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9900 			    &ip_opt_obj, B_FALSE);
9901 		} else {
9902 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9903 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9904 			    &ip_opt_obj, B_FALSE);
9905 		}
9906 		if (err != EINPROGRESS)
9907 			CONN_OPER_PENDING_DONE(connp);
9908 		return;
9909 	}
9910 	mutex_exit(&connp->conn_lock);
9911 }
9912 
9913 /*
9914  * Called from the ipsec_loader thread, outside any perimeter, to tell
9915  * ip qenable any of the queues waiting for the ipsec loader to
9916  * complete.
9917  */
9918 void
9919 ip_ipsec_load_complete(ipsec_stack_t *ipss)
9920 {
9921 	netstack_t *ns = ipss->ipsec_netstack;
9922 
9923 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
9924 }
9925 
9926 /*
9927  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
9928  * determines the grp on which it has to become exclusive, queues the mp
9929  * and IPSQ draining restarts the optmgmt
9930  */
9931 static boolean_t
9932 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
9933 {
9934 	conn_t *connp = Q_TO_CONN(q);
9935 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
9936 
9937 	/*
9938 	 * Take IPsec requests and treat them special.
9939 	 */
9940 	if (ipsec_opt_present(mp)) {
9941 		/* First check if IPsec is loaded. */
9942 		mutex_enter(&ipss->ipsec_loader_lock);
9943 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
9944 			mutex_exit(&ipss->ipsec_loader_lock);
9945 			return (B_FALSE);
9946 		}
9947 		mutex_enter(&connp->conn_lock);
9948 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
9949 
9950 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
9951 		connp->conn_ipsec_opt_mp = mp;
9952 		mutex_exit(&connp->conn_lock);
9953 		mutex_exit(&ipss->ipsec_loader_lock);
9954 
9955 		ipsec_loader_loadnow(ipss);
9956 		return (B_TRUE);
9957 	}
9958 	return (B_FALSE);
9959 }
9960 
9961 /*
9962  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
9963  * all of them are copied to the conn_t. If the req is "zero", the policy is
9964  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
9965  * fields.
9966  * We keep only the latest setting of the policy and thus policy setting
9967  * is not incremental/cumulative.
9968  *
9969  * Requests to set policies with multiple alternative actions will
9970  * go through a different API.
9971  */
9972 int
9973 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
9974 {
9975 	uint_t ah_req = 0;
9976 	uint_t esp_req = 0;
9977 	uint_t se_req = 0;
9978 	ipsec_selkey_t sel;
9979 	ipsec_act_t *actp = NULL;
9980 	uint_t nact;
9981 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
9982 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
9983 	ipsec_policy_root_t *pr;
9984 	ipsec_policy_head_t *ph;
9985 	int fam;
9986 	boolean_t is_pol_reset;
9987 	int error = 0;
9988 	netstack_t	*ns = connp->conn_netstack;
9989 	ip_stack_t	*ipst = ns->netstack_ip;
9990 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
9991 
9992 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
9993 
9994 	/*
9995 	 * The IP_SEC_OPT option does not allow variable length parameters,
9996 	 * hence a request cannot be NULL.
9997 	 */
9998 	if (req == NULL)
9999 		return (EINVAL);
10000 
10001 	ah_req = req->ipsr_ah_req;
10002 	esp_req = req->ipsr_esp_req;
10003 	se_req = req->ipsr_self_encap_req;
10004 
10005 	/* Don't allow setting self-encap without one or more of AH/ESP. */
10006 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
10007 		return (EINVAL);
10008 
10009 	/*
10010 	 * Are we dealing with a request to reset the policy (i.e.
10011 	 * zero requests).
10012 	 */
10013 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10014 	    (esp_req & REQ_MASK) == 0 &&
10015 	    (se_req & REQ_MASK) == 0);
10016 
10017 	if (!is_pol_reset) {
10018 		/*
10019 		 * If we couldn't load IPsec, fail with "protocol
10020 		 * not supported".
10021 		 * IPsec may not have been loaded for a request with zero
10022 		 * policies, so we don't fail in this case.
10023 		 */
10024 		mutex_enter(&ipss->ipsec_loader_lock);
10025 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10026 			mutex_exit(&ipss->ipsec_loader_lock);
10027 			return (EPROTONOSUPPORT);
10028 		}
10029 		mutex_exit(&ipss->ipsec_loader_lock);
10030 
10031 		/*
10032 		 * Test for valid requests. Invalid algorithms
10033 		 * need to be tested by IPsec code because new
10034 		 * algorithms can be added dynamically.
10035 		 */
10036 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10037 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10038 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10039 			return (EINVAL);
10040 		}
10041 
10042 		/*
10043 		 * Only privileged users can issue these
10044 		 * requests.
10045 		 */
10046 		if (((ah_req & IPSEC_PREF_NEVER) ||
10047 		    (esp_req & IPSEC_PREF_NEVER) ||
10048 		    (se_req & IPSEC_PREF_NEVER)) &&
10049 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10050 			return (EPERM);
10051 		}
10052 
10053 		/*
10054 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10055 		 * are mutually exclusive.
10056 		 */
10057 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10058 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10059 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10060 			/* Both of them are set */
10061 			return (EINVAL);
10062 		}
10063 	}
10064 
10065 	mutex_enter(&connp->conn_lock);
10066 
10067 	/*
10068 	 * If we have already cached policies in ip_bind_connected*(), don't
10069 	 * let them change now. We cache policies for connections
10070 	 * whose src,dst [addr, port] is known.
10071 	 */
10072 	if (connp->conn_policy_cached) {
10073 		mutex_exit(&connp->conn_lock);
10074 		return (EINVAL);
10075 	}
10076 
10077 	/*
10078 	 * We have a zero policies, reset the connection policy if already
10079 	 * set. This will cause the connection to inherit the
10080 	 * global policy, if any.
10081 	 */
10082 	if (is_pol_reset) {
10083 		if (connp->conn_policy != NULL) {
10084 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10085 			connp->conn_policy = NULL;
10086 		}
10087 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10088 		connp->conn_in_enforce_policy = B_FALSE;
10089 		connp->conn_out_enforce_policy = B_FALSE;
10090 		mutex_exit(&connp->conn_lock);
10091 		return (0);
10092 	}
10093 
10094 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10095 	    ipst->ips_netstack);
10096 	if (ph == NULL)
10097 		goto enomem;
10098 
10099 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10100 	if (actp == NULL)
10101 		goto enomem;
10102 
10103 	/*
10104 	 * Always allocate IPv4 policy entries, since they can also
10105 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10106 	 */
10107 	bzero(&sel, sizeof (sel));
10108 	sel.ipsl_valid = IPSL_IPV4;
10109 
10110 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10111 	    ipst->ips_netstack);
10112 	if (pin4 == NULL)
10113 		goto enomem;
10114 
10115 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10116 	    ipst->ips_netstack);
10117 	if (pout4 == NULL)
10118 		goto enomem;
10119 
10120 	if (connp->conn_af_isv6) {
10121 		/*
10122 		 * We're looking at a v6 socket, also allocate the
10123 		 * v6-specific entries...
10124 		 */
10125 		sel.ipsl_valid = IPSL_IPV6;
10126 		pin6 = ipsec_policy_create(&sel, actp, nact,
10127 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10128 		if (pin6 == NULL)
10129 			goto enomem;
10130 
10131 		pout6 = ipsec_policy_create(&sel, actp, nact,
10132 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10133 		if (pout6 == NULL)
10134 			goto enomem;
10135 
10136 		/*
10137 		 * .. and file them away in the right place.
10138 		 */
10139 		fam = IPSEC_AF_V6;
10140 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10141 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10142 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10143 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10144 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10145 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10146 	}
10147 
10148 	ipsec_actvec_free(actp, nact);
10149 
10150 	/*
10151 	 * File the v4 policies.
10152 	 */
10153 	fam = IPSEC_AF_V4;
10154 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10155 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10156 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10157 
10158 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10159 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10160 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10161 
10162 	/*
10163 	 * If the requests need security, set enforce_policy.
10164 	 * If the requests are IPSEC_PREF_NEVER, one should
10165 	 * still set conn_out_enforce_policy so that an ipsec_out
10166 	 * gets attached in ip_wput. This is needed so that
10167 	 * for connections that we don't cache policy in ip_bind,
10168 	 * if global policy matches in ip_wput_attach_policy, we
10169 	 * don't wrongly inherit global policy. Similarly, we need
10170 	 * to set conn_in_enforce_policy also so that we don't verify
10171 	 * policy wrongly.
10172 	 */
10173 	if ((ah_req & REQ_MASK) != 0 ||
10174 	    (esp_req & REQ_MASK) != 0 ||
10175 	    (se_req & REQ_MASK) != 0) {
10176 		connp->conn_in_enforce_policy = B_TRUE;
10177 		connp->conn_out_enforce_policy = B_TRUE;
10178 		connp->conn_flags |= IPCL_CHECK_POLICY;
10179 	}
10180 
10181 	mutex_exit(&connp->conn_lock);
10182 	return (error);
10183 #undef REQ_MASK
10184 
10185 	/*
10186 	 * Common memory-allocation-failure exit path.
10187 	 */
10188 enomem:
10189 	mutex_exit(&connp->conn_lock);
10190 	if (actp != NULL)
10191 		ipsec_actvec_free(actp, nact);
10192 	if (pin4 != NULL)
10193 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10194 	if (pout4 != NULL)
10195 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10196 	if (pin6 != NULL)
10197 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10198 	if (pout6 != NULL)
10199 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10200 	return (ENOMEM);
10201 }
10202 
10203 /*
10204  * Only for options that pass in an IP addr. Currently only V4 options
10205  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10206  * So this function assumes level is IPPROTO_IP
10207  */
10208 int
10209 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10210     mblk_t *first_mp)
10211 {
10212 	ipif_t *ipif = NULL;
10213 	int error;
10214 	ill_t *ill;
10215 	int zoneid;
10216 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10217 
10218 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10219 
10220 	if (addr != INADDR_ANY || checkonly) {
10221 		ASSERT(connp != NULL);
10222 		zoneid = IPCL_ZONEID(connp);
10223 		if (option == IP_NEXTHOP) {
10224 			ipif = ipif_lookup_onlink_addr(addr,
10225 			    connp->conn_zoneid, ipst);
10226 		} else {
10227 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10228 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10229 			    &error, ipst);
10230 		}
10231 		if (ipif == NULL) {
10232 			if (error == EINPROGRESS)
10233 				return (error);
10234 			if ((option == IP_MULTICAST_IF) ||
10235 			    (option == IP_NEXTHOP))
10236 				return (EHOSTUNREACH);
10237 			else
10238 				return (EINVAL);
10239 		} else if (checkonly) {
10240 			if (option == IP_MULTICAST_IF) {
10241 				ill = ipif->ipif_ill;
10242 				/* not supported by the virtual network iface */
10243 				if (IS_VNI(ill)) {
10244 					ipif_refrele(ipif);
10245 					return (EINVAL);
10246 				}
10247 			}
10248 			ipif_refrele(ipif);
10249 			return (0);
10250 		}
10251 		ill = ipif->ipif_ill;
10252 		mutex_enter(&connp->conn_lock);
10253 		mutex_enter(&ill->ill_lock);
10254 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10255 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10256 			mutex_exit(&ill->ill_lock);
10257 			mutex_exit(&connp->conn_lock);
10258 			ipif_refrele(ipif);
10259 			return (option == IP_MULTICAST_IF ?
10260 			    EHOSTUNREACH : EINVAL);
10261 		}
10262 	} else {
10263 		mutex_enter(&connp->conn_lock);
10264 	}
10265 
10266 	/* None of the options below are supported on the VNI */
10267 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10268 		mutex_exit(&ill->ill_lock);
10269 		mutex_exit(&connp->conn_lock);
10270 		ipif_refrele(ipif);
10271 		return (EINVAL);
10272 	}
10273 
10274 	switch (option) {
10275 	case IP_MULTICAST_IF:
10276 		connp->conn_multicast_ipif = ipif;
10277 		break;
10278 	case IP_NEXTHOP:
10279 		connp->conn_nexthop_v4 = addr;
10280 		connp->conn_nexthop_set = B_TRUE;
10281 		break;
10282 	}
10283 
10284 	if (ipif != NULL) {
10285 		mutex_exit(&ill->ill_lock);
10286 		mutex_exit(&connp->conn_lock);
10287 		ipif_refrele(ipif);
10288 		return (0);
10289 	}
10290 	mutex_exit(&connp->conn_lock);
10291 	/* We succeded in cleared the option */
10292 	return (0);
10293 }
10294 
10295 /*
10296  * For options that pass in an ifindex specifying the ill. V6 options always
10297  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10298  */
10299 int
10300 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10301     int level, int option, mblk_t *first_mp)
10302 {
10303 	ill_t *ill = NULL;
10304 	int error = 0;
10305 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10306 
10307 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10308 	if (ifindex != 0) {
10309 		ASSERT(connp != NULL);
10310 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10311 		    first_mp, ip_restart_optmgmt, &error, ipst);
10312 		if (ill != NULL) {
10313 			if (checkonly) {
10314 				/* not supported by the virtual network iface */
10315 				if (IS_VNI(ill)) {
10316 					ill_refrele(ill);
10317 					return (EINVAL);
10318 				}
10319 				ill_refrele(ill);
10320 				return (0);
10321 			}
10322 			if (!ipif_lookup_zoneid(ill, connp->conn_zoneid,
10323 			    0, NULL)) {
10324 				ill_refrele(ill);
10325 				ill = NULL;
10326 				mutex_enter(&connp->conn_lock);
10327 				goto setit;
10328 			}
10329 			mutex_enter(&connp->conn_lock);
10330 			mutex_enter(&ill->ill_lock);
10331 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10332 				mutex_exit(&ill->ill_lock);
10333 				mutex_exit(&connp->conn_lock);
10334 				ill_refrele(ill);
10335 				ill = NULL;
10336 				mutex_enter(&connp->conn_lock);
10337 			}
10338 			goto setit;
10339 		} else if (error == EINPROGRESS) {
10340 			return (error);
10341 		} else {
10342 			error = 0;
10343 		}
10344 	}
10345 	mutex_enter(&connp->conn_lock);
10346 setit:
10347 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10348 
10349 	/*
10350 	 * The options below assume that the ILL (if any) transmits and/or
10351 	 * receives traffic. Neither of which is true for the virtual network
10352 	 * interface, so fail setting these on a VNI.
10353 	 */
10354 	if (IS_VNI(ill)) {
10355 		ASSERT(ill != NULL);
10356 		mutex_exit(&ill->ill_lock);
10357 		mutex_exit(&connp->conn_lock);
10358 		ill_refrele(ill);
10359 		return (EINVAL);
10360 	}
10361 
10362 	if (level == IPPROTO_IP) {
10363 		switch (option) {
10364 		case IP_BOUND_IF:
10365 			connp->conn_incoming_ill = ill;
10366 			connp->conn_outgoing_ill = ill;
10367 			break;
10368 
10369 		case IP_MULTICAST_IF:
10370 			/*
10371 			 * This option is an internal special. The socket
10372 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10373 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10374 			 * specifies an ifindex and we try first on V6 ill's.
10375 			 * If we don't find one, we they try using on v4 ill's
10376 			 * intenally and we come here.
10377 			 */
10378 			if (!checkonly && ill != NULL) {
10379 				ipif_t	*ipif;
10380 				ipif = ill->ill_ipif;
10381 
10382 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10383 					mutex_exit(&ill->ill_lock);
10384 					mutex_exit(&connp->conn_lock);
10385 					ill_refrele(ill);
10386 					ill = NULL;
10387 					mutex_enter(&connp->conn_lock);
10388 				} else {
10389 					connp->conn_multicast_ipif = ipif;
10390 				}
10391 			}
10392 			break;
10393 
10394 		case IP_DHCPINIT_IF:
10395 			if (connp->conn_dhcpinit_ill != NULL) {
10396 				/*
10397 				 * We've locked the conn so conn_cleanup_ill()
10398 				 * cannot clear conn_dhcpinit_ill -- so it's
10399 				 * safe to access the ill.
10400 				 */
10401 				ill_t *oill = connp->conn_dhcpinit_ill;
10402 
10403 				ASSERT(oill->ill_dhcpinit != 0);
10404 				atomic_dec_32(&oill->ill_dhcpinit);
10405 				connp->conn_dhcpinit_ill = NULL;
10406 			}
10407 
10408 			if (ill != NULL) {
10409 				connp->conn_dhcpinit_ill = ill;
10410 				atomic_inc_32(&ill->ill_dhcpinit);
10411 			}
10412 			break;
10413 		}
10414 	} else {
10415 		switch (option) {
10416 		case IPV6_BOUND_IF:
10417 			connp->conn_incoming_ill = ill;
10418 			connp->conn_outgoing_ill = ill;
10419 			break;
10420 
10421 		case IPV6_MULTICAST_IF:
10422 			/*
10423 			 * Set conn_multicast_ill to be the IPv6 ill.
10424 			 * Set conn_multicast_ipif to be an IPv4 ipif
10425 			 * for ifindex to make IPv4 mapped addresses
10426 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10427 			 * Even if no IPv6 ill exists for the ifindex
10428 			 * we need to check for an IPv4 ifindex in order
10429 			 * for this to work with mapped addresses. In that
10430 			 * case only set conn_multicast_ipif.
10431 			 */
10432 			if (!checkonly) {
10433 				if (ifindex == 0) {
10434 					connp->conn_multicast_ill = NULL;
10435 					connp->conn_multicast_ipif = NULL;
10436 				} else if (ill != NULL) {
10437 					connp->conn_multicast_ill = ill;
10438 				}
10439 			}
10440 			break;
10441 		}
10442 	}
10443 
10444 	if (ill != NULL) {
10445 		mutex_exit(&ill->ill_lock);
10446 		mutex_exit(&connp->conn_lock);
10447 		ill_refrele(ill);
10448 		return (0);
10449 	}
10450 	mutex_exit(&connp->conn_lock);
10451 	/*
10452 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10453 	 * locate the ill and could not set the option (ifindex != 0)
10454 	 */
10455 	return (ifindex == 0 ? 0 : EINVAL);
10456 }
10457 
10458 /* This routine sets socket options. */
10459 /* ARGSUSED */
10460 int
10461 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10462     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10463     void *dummy, cred_t *cr, mblk_t *first_mp)
10464 {
10465 	int		*i1 = (int *)invalp;
10466 	conn_t		*connp = Q_TO_CONN(q);
10467 	int		error = 0;
10468 	boolean_t	checkonly;
10469 	ire_t		*ire;
10470 	boolean_t	found;
10471 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10472 
10473 	switch (optset_context) {
10474 
10475 	case SETFN_OPTCOM_CHECKONLY:
10476 		checkonly = B_TRUE;
10477 		/*
10478 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10479 		 * inlen != 0 implies value supplied and
10480 		 * 	we have to "pretend" to set it.
10481 		 * inlen == 0 implies that there is no
10482 		 * 	value part in T_CHECK request and just validation
10483 		 * done elsewhere should be enough, we just return here.
10484 		 */
10485 		if (inlen == 0) {
10486 			*outlenp = 0;
10487 			return (0);
10488 		}
10489 		break;
10490 	case SETFN_OPTCOM_NEGOTIATE:
10491 	case SETFN_UD_NEGOTIATE:
10492 	case SETFN_CONN_NEGOTIATE:
10493 		checkonly = B_FALSE;
10494 		break;
10495 	default:
10496 		/*
10497 		 * We should never get here
10498 		 */
10499 		*outlenp = 0;
10500 		return (EINVAL);
10501 	}
10502 
10503 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10504 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10505 
10506 	/*
10507 	 * For fixed length options, no sanity check
10508 	 * of passed in length is done. It is assumed *_optcom_req()
10509 	 * routines do the right thing.
10510 	 */
10511 
10512 	switch (level) {
10513 	case SOL_SOCKET:
10514 		/*
10515 		 * conn_lock protects the bitfields, and is used to
10516 		 * set the fields atomically.
10517 		 */
10518 		switch (name) {
10519 		case SO_BROADCAST:
10520 			if (!checkonly) {
10521 				/* TODO: use value someplace? */
10522 				mutex_enter(&connp->conn_lock);
10523 				connp->conn_broadcast = *i1 ? 1 : 0;
10524 				mutex_exit(&connp->conn_lock);
10525 			}
10526 			break;	/* goto sizeof (int) option return */
10527 		case SO_USELOOPBACK:
10528 			if (!checkonly) {
10529 				/* TODO: use value someplace? */
10530 				mutex_enter(&connp->conn_lock);
10531 				connp->conn_loopback = *i1 ? 1 : 0;
10532 				mutex_exit(&connp->conn_lock);
10533 			}
10534 			break;	/* goto sizeof (int) option return */
10535 		case SO_DONTROUTE:
10536 			if (!checkonly) {
10537 				mutex_enter(&connp->conn_lock);
10538 				connp->conn_dontroute = *i1 ? 1 : 0;
10539 				mutex_exit(&connp->conn_lock);
10540 			}
10541 			break;	/* goto sizeof (int) option return */
10542 		case SO_REUSEADDR:
10543 			if (!checkonly) {
10544 				mutex_enter(&connp->conn_lock);
10545 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10546 				mutex_exit(&connp->conn_lock);
10547 			}
10548 			break;	/* goto sizeof (int) option return */
10549 		case SO_PROTOTYPE:
10550 			if (!checkonly) {
10551 				mutex_enter(&connp->conn_lock);
10552 				connp->conn_proto = *i1;
10553 				mutex_exit(&connp->conn_lock);
10554 			}
10555 			break;	/* goto sizeof (int) option return */
10556 		case SO_ALLZONES:
10557 			if (!checkonly) {
10558 				mutex_enter(&connp->conn_lock);
10559 				if (IPCL_IS_BOUND(connp)) {
10560 					mutex_exit(&connp->conn_lock);
10561 					return (EINVAL);
10562 				}
10563 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10564 				mutex_exit(&connp->conn_lock);
10565 			}
10566 			break;	/* goto sizeof (int) option return */
10567 		case SO_ANON_MLP:
10568 			if (!checkonly) {
10569 				mutex_enter(&connp->conn_lock);
10570 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10571 				mutex_exit(&connp->conn_lock);
10572 			}
10573 			break;	/* goto sizeof (int) option return */
10574 		case SO_MAC_EXEMPT:
10575 			if (secpolicy_net_mac_aware(cr) != 0 ||
10576 			    IPCL_IS_BOUND(connp))
10577 				return (EACCES);
10578 			if (!checkonly) {
10579 				mutex_enter(&connp->conn_lock);
10580 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10581 				mutex_exit(&connp->conn_lock);
10582 			}
10583 			break;	/* goto sizeof (int) option return */
10584 		default:
10585 			/*
10586 			 * "soft" error (negative)
10587 			 * option not handled at this level
10588 			 * Note: Do not modify *outlenp
10589 			 */
10590 			return (-EINVAL);
10591 		}
10592 		break;
10593 	case IPPROTO_IP:
10594 		switch (name) {
10595 		case IP_NEXTHOP:
10596 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10597 				return (EPERM);
10598 			/* FALLTHRU */
10599 		case IP_MULTICAST_IF: {
10600 			ipaddr_t addr = *i1;
10601 
10602 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10603 			    first_mp);
10604 			if (error != 0)
10605 				return (error);
10606 			break;	/* goto sizeof (int) option return */
10607 		}
10608 
10609 		case IP_MULTICAST_TTL:
10610 			/* Recorded in transport above IP */
10611 			*outvalp = *invalp;
10612 			*outlenp = sizeof (uchar_t);
10613 			return (0);
10614 		case IP_MULTICAST_LOOP:
10615 			if (!checkonly) {
10616 				mutex_enter(&connp->conn_lock);
10617 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10618 				mutex_exit(&connp->conn_lock);
10619 			}
10620 			*outvalp = *invalp;
10621 			*outlenp = sizeof (uchar_t);
10622 			return (0);
10623 		case IP_ADD_MEMBERSHIP:
10624 		case MCAST_JOIN_GROUP:
10625 		case IP_DROP_MEMBERSHIP:
10626 		case MCAST_LEAVE_GROUP: {
10627 			struct ip_mreq *mreqp;
10628 			struct group_req *greqp;
10629 			ire_t *ire;
10630 			boolean_t done = B_FALSE;
10631 			ipaddr_t group, ifaddr;
10632 			struct sockaddr_in *sin;
10633 			uint32_t *ifindexp;
10634 			boolean_t mcast_opt = B_TRUE;
10635 			mcast_record_t fmode;
10636 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10637 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10638 
10639 			switch (name) {
10640 			case IP_ADD_MEMBERSHIP:
10641 				mcast_opt = B_FALSE;
10642 				/* FALLTHRU */
10643 			case MCAST_JOIN_GROUP:
10644 				fmode = MODE_IS_EXCLUDE;
10645 				optfn = ip_opt_add_group;
10646 				break;
10647 
10648 			case IP_DROP_MEMBERSHIP:
10649 				mcast_opt = B_FALSE;
10650 				/* FALLTHRU */
10651 			case MCAST_LEAVE_GROUP:
10652 				fmode = MODE_IS_INCLUDE;
10653 				optfn = ip_opt_delete_group;
10654 				break;
10655 			}
10656 
10657 			if (mcast_opt) {
10658 				greqp = (struct group_req *)i1;
10659 				sin = (struct sockaddr_in *)&greqp->gr_group;
10660 				if (sin->sin_family != AF_INET) {
10661 					*outlenp = 0;
10662 					return (ENOPROTOOPT);
10663 				}
10664 				group = (ipaddr_t)sin->sin_addr.s_addr;
10665 				ifaddr = INADDR_ANY;
10666 				ifindexp = &greqp->gr_interface;
10667 			} else {
10668 				mreqp = (struct ip_mreq *)i1;
10669 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10670 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10671 				ifindexp = NULL;
10672 			}
10673 
10674 			/*
10675 			 * In the multirouting case, we need to replicate
10676 			 * the request on all interfaces that will take part
10677 			 * in replication.  We do so because multirouting is
10678 			 * reflective, thus we will probably receive multi-
10679 			 * casts on those interfaces.
10680 			 * The ip_multirt_apply_membership() succeeds if the
10681 			 * operation succeeds on at least one interface.
10682 			 */
10683 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10684 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10685 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10686 			if (ire != NULL) {
10687 				if (ire->ire_flags & RTF_MULTIRT) {
10688 					error = ip_multirt_apply_membership(
10689 					    optfn, ire, connp, checkonly, group,
10690 					    fmode, INADDR_ANY, first_mp);
10691 					done = B_TRUE;
10692 				}
10693 				ire_refrele(ire);
10694 			}
10695 			if (!done) {
10696 				error = optfn(connp, checkonly, group, ifaddr,
10697 				    ifindexp, fmode, INADDR_ANY, first_mp);
10698 			}
10699 			if (error) {
10700 				/*
10701 				 * EINPROGRESS is a soft error, needs retry
10702 				 * so don't make *outlenp zero.
10703 				 */
10704 				if (error != EINPROGRESS)
10705 					*outlenp = 0;
10706 				return (error);
10707 			}
10708 			/* OK return - copy input buffer into output buffer */
10709 			if (invalp != outvalp) {
10710 				/* don't trust bcopy for identical src/dst */
10711 				bcopy(invalp, outvalp, inlen);
10712 			}
10713 			*outlenp = inlen;
10714 			return (0);
10715 		}
10716 		case IP_BLOCK_SOURCE:
10717 		case IP_UNBLOCK_SOURCE:
10718 		case IP_ADD_SOURCE_MEMBERSHIP:
10719 		case IP_DROP_SOURCE_MEMBERSHIP:
10720 		case MCAST_BLOCK_SOURCE:
10721 		case MCAST_UNBLOCK_SOURCE:
10722 		case MCAST_JOIN_SOURCE_GROUP:
10723 		case MCAST_LEAVE_SOURCE_GROUP: {
10724 			struct ip_mreq_source *imreqp;
10725 			struct group_source_req *gsreqp;
10726 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10727 			uint32_t ifindex = 0;
10728 			mcast_record_t fmode;
10729 			struct sockaddr_in *sin;
10730 			ire_t *ire;
10731 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10732 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10733 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10734 
10735 			switch (name) {
10736 			case IP_BLOCK_SOURCE:
10737 				mcast_opt = B_FALSE;
10738 				/* FALLTHRU */
10739 			case MCAST_BLOCK_SOURCE:
10740 				fmode = MODE_IS_EXCLUDE;
10741 				optfn = ip_opt_add_group;
10742 				break;
10743 
10744 			case IP_UNBLOCK_SOURCE:
10745 				mcast_opt = B_FALSE;
10746 				/* FALLTHRU */
10747 			case MCAST_UNBLOCK_SOURCE:
10748 				fmode = MODE_IS_EXCLUDE;
10749 				optfn = ip_opt_delete_group;
10750 				break;
10751 
10752 			case IP_ADD_SOURCE_MEMBERSHIP:
10753 				mcast_opt = B_FALSE;
10754 				/* FALLTHRU */
10755 			case MCAST_JOIN_SOURCE_GROUP:
10756 				fmode = MODE_IS_INCLUDE;
10757 				optfn = ip_opt_add_group;
10758 				break;
10759 
10760 			case IP_DROP_SOURCE_MEMBERSHIP:
10761 				mcast_opt = B_FALSE;
10762 				/* FALLTHRU */
10763 			case MCAST_LEAVE_SOURCE_GROUP:
10764 				fmode = MODE_IS_INCLUDE;
10765 				optfn = ip_opt_delete_group;
10766 				break;
10767 			}
10768 
10769 			if (mcast_opt) {
10770 				gsreqp = (struct group_source_req *)i1;
10771 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10772 					*outlenp = 0;
10773 					return (ENOPROTOOPT);
10774 				}
10775 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10776 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10777 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10778 				src = (ipaddr_t)sin->sin_addr.s_addr;
10779 				ifindex = gsreqp->gsr_interface;
10780 			} else {
10781 				imreqp = (struct ip_mreq_source *)i1;
10782 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10783 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10784 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10785 			}
10786 
10787 			/*
10788 			 * In the multirouting case, we need to replicate
10789 			 * the request as noted in the mcast cases above.
10790 			 */
10791 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10792 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10793 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10794 			if (ire != NULL) {
10795 				if (ire->ire_flags & RTF_MULTIRT) {
10796 					error = ip_multirt_apply_membership(
10797 					    optfn, ire, connp, checkonly, grp,
10798 					    fmode, src, first_mp);
10799 					done = B_TRUE;
10800 				}
10801 				ire_refrele(ire);
10802 			}
10803 			if (!done) {
10804 				error = optfn(connp, checkonly, grp, ifaddr,
10805 				    &ifindex, fmode, src, first_mp);
10806 			}
10807 			if (error != 0) {
10808 				/*
10809 				 * EINPROGRESS is a soft error, needs retry
10810 				 * so don't make *outlenp zero.
10811 				 */
10812 				if (error != EINPROGRESS)
10813 					*outlenp = 0;
10814 				return (error);
10815 			}
10816 			/* OK return - copy input buffer into output buffer */
10817 			if (invalp != outvalp) {
10818 				bcopy(invalp, outvalp, inlen);
10819 			}
10820 			*outlenp = inlen;
10821 			return (0);
10822 		}
10823 		case IP_SEC_OPT:
10824 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10825 			if (error != 0) {
10826 				*outlenp = 0;
10827 				return (error);
10828 			}
10829 			break;
10830 		case IP_HDRINCL:
10831 		case IP_OPTIONS:
10832 		case T_IP_OPTIONS:
10833 		case IP_TOS:
10834 		case T_IP_TOS:
10835 		case IP_TTL:
10836 		case IP_RECVDSTADDR:
10837 		case IP_RECVOPTS:
10838 			/* OK return - copy input buffer into output buffer */
10839 			if (invalp != outvalp) {
10840 				/* don't trust bcopy for identical src/dst */
10841 				bcopy(invalp, outvalp, inlen);
10842 			}
10843 			*outlenp = inlen;
10844 			return (0);
10845 		case IP_RECVIF:
10846 			/* Retrieve the inbound interface index */
10847 			if (!checkonly) {
10848 				mutex_enter(&connp->conn_lock);
10849 				connp->conn_recvif = *i1 ? 1 : 0;
10850 				mutex_exit(&connp->conn_lock);
10851 			}
10852 			break;	/* goto sizeof (int) option return */
10853 		case IP_RECVPKTINFO:
10854 			if (!checkonly) {
10855 				mutex_enter(&connp->conn_lock);
10856 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
10857 				mutex_exit(&connp->conn_lock);
10858 			}
10859 			break;	/* goto sizeof (int) option return */
10860 		case IP_RECVSLLA:
10861 			/* Retrieve the source link layer address */
10862 			if (!checkonly) {
10863 				mutex_enter(&connp->conn_lock);
10864 				connp->conn_recvslla = *i1 ? 1 : 0;
10865 				mutex_exit(&connp->conn_lock);
10866 			}
10867 			break;	/* goto sizeof (int) option return */
10868 		case MRT_INIT:
10869 		case MRT_DONE:
10870 		case MRT_ADD_VIF:
10871 		case MRT_DEL_VIF:
10872 		case MRT_ADD_MFC:
10873 		case MRT_DEL_MFC:
10874 		case MRT_ASSERT:
10875 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
10876 				*outlenp = 0;
10877 				return (error);
10878 			}
10879 			error = ip_mrouter_set((int)name, q, checkonly,
10880 			    (uchar_t *)invalp, inlen, first_mp);
10881 			if (error) {
10882 				*outlenp = 0;
10883 				return (error);
10884 			}
10885 			/* OK return - copy input buffer into output buffer */
10886 			if (invalp != outvalp) {
10887 				/* don't trust bcopy for identical src/dst */
10888 				bcopy(invalp, outvalp, inlen);
10889 			}
10890 			*outlenp = inlen;
10891 			return (0);
10892 		case IP_BOUND_IF:
10893 		case IP_DHCPINIT_IF:
10894 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10895 			    level, name, first_mp);
10896 			if (error != 0)
10897 				return (error);
10898 			break; 		/* goto sizeof (int) option return */
10899 
10900 		case IP_UNSPEC_SRC:
10901 			/* Allow sending with a zero source address */
10902 			if (!checkonly) {
10903 				mutex_enter(&connp->conn_lock);
10904 				connp->conn_unspec_src = *i1 ? 1 : 0;
10905 				mutex_exit(&connp->conn_lock);
10906 			}
10907 			break;	/* goto sizeof (int) option return */
10908 		default:
10909 			/*
10910 			 * "soft" error (negative)
10911 			 * option not handled at this level
10912 			 * Note: Do not modify *outlenp
10913 			 */
10914 			return (-EINVAL);
10915 		}
10916 		break;
10917 	case IPPROTO_IPV6:
10918 		switch (name) {
10919 		case IPV6_BOUND_IF:
10920 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10921 			    level, name, first_mp);
10922 			if (error != 0)
10923 				return (error);
10924 			break; 		/* goto sizeof (int) option return */
10925 
10926 		case IPV6_MULTICAST_IF:
10927 			/*
10928 			 * The only possible errors are EINPROGRESS and
10929 			 * EINVAL. EINPROGRESS will be restarted and is not
10930 			 * a hard error. We call this option on both V4 and V6
10931 			 * If both return EINVAL, then this call returns
10932 			 * EINVAL. If at least one of them succeeds we
10933 			 * return success.
10934 			 */
10935 			found = B_FALSE;
10936 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10937 			    level, name, first_mp);
10938 			if (error == EINPROGRESS)
10939 				return (error);
10940 			if (error == 0)
10941 				found = B_TRUE;
10942 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10943 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
10944 			if (error == 0)
10945 				found = B_TRUE;
10946 			if (!found)
10947 				return (error);
10948 			break; 		/* goto sizeof (int) option return */
10949 
10950 		case IPV6_MULTICAST_HOPS:
10951 			/* Recorded in transport above IP */
10952 			break;	/* goto sizeof (int) option return */
10953 		case IPV6_MULTICAST_LOOP:
10954 			if (!checkonly) {
10955 				mutex_enter(&connp->conn_lock);
10956 				connp->conn_multicast_loop = *i1;
10957 				mutex_exit(&connp->conn_lock);
10958 			}
10959 			break;	/* goto sizeof (int) option return */
10960 		case IPV6_JOIN_GROUP:
10961 		case MCAST_JOIN_GROUP:
10962 		case IPV6_LEAVE_GROUP:
10963 		case MCAST_LEAVE_GROUP: {
10964 			struct ipv6_mreq *ip_mreqp;
10965 			struct group_req *greqp;
10966 			ire_t *ire;
10967 			boolean_t done = B_FALSE;
10968 			in6_addr_t groupv6;
10969 			uint32_t ifindex;
10970 			boolean_t mcast_opt = B_TRUE;
10971 			mcast_record_t fmode;
10972 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10973 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10974 
10975 			switch (name) {
10976 			case IPV6_JOIN_GROUP:
10977 				mcast_opt = B_FALSE;
10978 				/* FALLTHRU */
10979 			case MCAST_JOIN_GROUP:
10980 				fmode = MODE_IS_EXCLUDE;
10981 				optfn = ip_opt_add_group_v6;
10982 				break;
10983 
10984 			case IPV6_LEAVE_GROUP:
10985 				mcast_opt = B_FALSE;
10986 				/* FALLTHRU */
10987 			case MCAST_LEAVE_GROUP:
10988 				fmode = MODE_IS_INCLUDE;
10989 				optfn = ip_opt_delete_group_v6;
10990 				break;
10991 			}
10992 
10993 			if (mcast_opt) {
10994 				struct sockaddr_in *sin;
10995 				struct sockaddr_in6 *sin6;
10996 				greqp = (struct group_req *)i1;
10997 				if (greqp->gr_group.ss_family == AF_INET) {
10998 					sin = (struct sockaddr_in *)
10999 					    &(greqp->gr_group);
11000 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11001 					    &groupv6);
11002 				} else {
11003 					sin6 = (struct sockaddr_in6 *)
11004 					    &(greqp->gr_group);
11005 					groupv6 = sin6->sin6_addr;
11006 				}
11007 				ifindex = greqp->gr_interface;
11008 			} else {
11009 				ip_mreqp = (struct ipv6_mreq *)i1;
11010 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11011 				ifindex = ip_mreqp->ipv6mr_interface;
11012 			}
11013 			/*
11014 			 * In the multirouting case, we need to replicate
11015 			 * the request on all interfaces that will take part
11016 			 * in replication.  We do so because multirouting is
11017 			 * reflective, thus we will probably receive multi-
11018 			 * casts on those interfaces.
11019 			 * The ip_multirt_apply_membership_v6() succeeds if
11020 			 * the operation succeeds on at least one interface.
11021 			 */
11022 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11023 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11024 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11025 			if (ire != NULL) {
11026 				if (ire->ire_flags & RTF_MULTIRT) {
11027 					error = ip_multirt_apply_membership_v6(
11028 					    optfn, ire, connp, checkonly,
11029 					    &groupv6, fmode, &ipv6_all_zeros,
11030 					    first_mp);
11031 					done = B_TRUE;
11032 				}
11033 				ire_refrele(ire);
11034 			}
11035 			if (!done) {
11036 				error = optfn(connp, checkonly, &groupv6,
11037 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11038 			}
11039 			if (error) {
11040 				/*
11041 				 * EINPROGRESS is a soft error, needs retry
11042 				 * so don't make *outlenp zero.
11043 				 */
11044 				if (error != EINPROGRESS)
11045 					*outlenp = 0;
11046 				return (error);
11047 			}
11048 			/* OK return - copy input buffer into output buffer */
11049 			if (invalp != outvalp) {
11050 				/* don't trust bcopy for identical src/dst */
11051 				bcopy(invalp, outvalp, inlen);
11052 			}
11053 			*outlenp = inlen;
11054 			return (0);
11055 		}
11056 		case MCAST_BLOCK_SOURCE:
11057 		case MCAST_UNBLOCK_SOURCE:
11058 		case MCAST_JOIN_SOURCE_GROUP:
11059 		case MCAST_LEAVE_SOURCE_GROUP: {
11060 			struct group_source_req *gsreqp;
11061 			in6_addr_t v6grp, v6src;
11062 			uint32_t ifindex;
11063 			mcast_record_t fmode;
11064 			ire_t *ire;
11065 			boolean_t done = B_FALSE;
11066 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11067 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11068 
11069 			switch (name) {
11070 			case MCAST_BLOCK_SOURCE:
11071 				fmode = MODE_IS_EXCLUDE;
11072 				optfn = ip_opt_add_group_v6;
11073 				break;
11074 			case MCAST_UNBLOCK_SOURCE:
11075 				fmode = MODE_IS_EXCLUDE;
11076 				optfn = ip_opt_delete_group_v6;
11077 				break;
11078 			case MCAST_JOIN_SOURCE_GROUP:
11079 				fmode = MODE_IS_INCLUDE;
11080 				optfn = ip_opt_add_group_v6;
11081 				break;
11082 			case MCAST_LEAVE_SOURCE_GROUP:
11083 				fmode = MODE_IS_INCLUDE;
11084 				optfn = ip_opt_delete_group_v6;
11085 				break;
11086 			}
11087 
11088 			gsreqp = (struct group_source_req *)i1;
11089 			ifindex = gsreqp->gsr_interface;
11090 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11091 				struct sockaddr_in *s;
11092 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11093 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11094 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11095 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11096 			} else {
11097 				struct sockaddr_in6 *s6;
11098 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11099 				v6grp = s6->sin6_addr;
11100 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11101 				v6src = s6->sin6_addr;
11102 			}
11103 
11104 			/*
11105 			 * In the multirouting case, we need to replicate
11106 			 * the request as noted in the mcast cases above.
11107 			 */
11108 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11109 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11110 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11111 			if (ire != NULL) {
11112 				if (ire->ire_flags & RTF_MULTIRT) {
11113 					error = ip_multirt_apply_membership_v6(
11114 					    optfn, ire, connp, checkonly,
11115 					    &v6grp, fmode, &v6src, first_mp);
11116 					done = B_TRUE;
11117 				}
11118 				ire_refrele(ire);
11119 			}
11120 			if (!done) {
11121 				error = optfn(connp, checkonly, &v6grp,
11122 				    ifindex, fmode, &v6src, first_mp);
11123 			}
11124 			if (error != 0) {
11125 				/*
11126 				 * EINPROGRESS is a soft error, needs retry
11127 				 * so don't make *outlenp zero.
11128 				 */
11129 				if (error != EINPROGRESS)
11130 					*outlenp = 0;
11131 				return (error);
11132 			}
11133 			/* OK return - copy input buffer into output buffer */
11134 			if (invalp != outvalp) {
11135 				bcopy(invalp, outvalp, inlen);
11136 			}
11137 			*outlenp = inlen;
11138 			return (0);
11139 		}
11140 		case IPV6_UNICAST_HOPS:
11141 			/* Recorded in transport above IP */
11142 			break;	/* goto sizeof (int) option return */
11143 		case IPV6_UNSPEC_SRC:
11144 			/* Allow sending with a zero source address */
11145 			if (!checkonly) {
11146 				mutex_enter(&connp->conn_lock);
11147 				connp->conn_unspec_src = *i1 ? 1 : 0;
11148 				mutex_exit(&connp->conn_lock);
11149 			}
11150 			break;	/* goto sizeof (int) option return */
11151 		case IPV6_RECVPKTINFO:
11152 			if (!checkonly) {
11153 				mutex_enter(&connp->conn_lock);
11154 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11155 				mutex_exit(&connp->conn_lock);
11156 			}
11157 			break;	/* goto sizeof (int) option return */
11158 		case IPV6_RECVTCLASS:
11159 			if (!checkonly) {
11160 				if (*i1 < 0 || *i1 > 1) {
11161 					return (EINVAL);
11162 				}
11163 				mutex_enter(&connp->conn_lock);
11164 				connp->conn_ipv6_recvtclass = *i1;
11165 				mutex_exit(&connp->conn_lock);
11166 			}
11167 			break;
11168 		case IPV6_RECVPATHMTU:
11169 			if (!checkonly) {
11170 				if (*i1 < 0 || *i1 > 1) {
11171 					return (EINVAL);
11172 				}
11173 				mutex_enter(&connp->conn_lock);
11174 				connp->conn_ipv6_recvpathmtu = *i1;
11175 				mutex_exit(&connp->conn_lock);
11176 			}
11177 			break;
11178 		case IPV6_RECVHOPLIMIT:
11179 			if (!checkonly) {
11180 				mutex_enter(&connp->conn_lock);
11181 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11182 				mutex_exit(&connp->conn_lock);
11183 			}
11184 			break;	/* goto sizeof (int) option return */
11185 		case IPV6_RECVHOPOPTS:
11186 			if (!checkonly) {
11187 				mutex_enter(&connp->conn_lock);
11188 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11189 				mutex_exit(&connp->conn_lock);
11190 			}
11191 			break;	/* goto sizeof (int) option return */
11192 		case IPV6_RECVDSTOPTS:
11193 			if (!checkonly) {
11194 				mutex_enter(&connp->conn_lock);
11195 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11196 				mutex_exit(&connp->conn_lock);
11197 			}
11198 			break;	/* goto sizeof (int) option return */
11199 		case IPV6_RECVRTHDR:
11200 			if (!checkonly) {
11201 				mutex_enter(&connp->conn_lock);
11202 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11203 				mutex_exit(&connp->conn_lock);
11204 			}
11205 			break;	/* goto sizeof (int) option return */
11206 		case IPV6_RECVRTHDRDSTOPTS:
11207 			if (!checkonly) {
11208 				mutex_enter(&connp->conn_lock);
11209 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11210 				mutex_exit(&connp->conn_lock);
11211 			}
11212 			break;	/* goto sizeof (int) option return */
11213 		case IPV6_PKTINFO:
11214 			if (inlen == 0)
11215 				return (-EINVAL);	/* clearing option */
11216 			error = ip6_set_pktinfo(cr, connp,
11217 			    (struct in6_pktinfo *)invalp);
11218 			if (error != 0)
11219 				*outlenp = 0;
11220 			else
11221 				*outlenp = inlen;
11222 			return (error);
11223 		case IPV6_NEXTHOP: {
11224 			struct sockaddr_in6 *sin6;
11225 
11226 			/* Verify that the nexthop is reachable */
11227 			if (inlen == 0)
11228 				return (-EINVAL);	/* clearing option */
11229 
11230 			sin6 = (struct sockaddr_in6 *)invalp;
11231 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11232 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11233 			    NULL, MATCH_IRE_DEFAULT, ipst);
11234 
11235 			if (ire == NULL) {
11236 				*outlenp = 0;
11237 				return (EHOSTUNREACH);
11238 			}
11239 			ire_refrele(ire);
11240 			return (-EINVAL);
11241 		}
11242 		case IPV6_SEC_OPT:
11243 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11244 			if (error != 0) {
11245 				*outlenp = 0;
11246 				return (error);
11247 			}
11248 			break;
11249 		case IPV6_SRC_PREFERENCES: {
11250 			/*
11251 			 * This is implemented strictly in the ip module
11252 			 * (here and in tcp_opt_*() to accomodate tcp
11253 			 * sockets).  Modules above ip pass this option
11254 			 * down here since ip is the only one that needs to
11255 			 * be aware of source address preferences.
11256 			 *
11257 			 * This socket option only affects connected
11258 			 * sockets that haven't already bound to a specific
11259 			 * IPv6 address.  In other words, sockets that
11260 			 * don't call bind() with an address other than the
11261 			 * unspecified address and that call connect().
11262 			 * ip_bind_connected_v6() passes these preferences
11263 			 * to the ipif_select_source_v6() function.
11264 			 */
11265 			if (inlen != sizeof (uint32_t))
11266 				return (EINVAL);
11267 			error = ip6_set_src_preferences(connp,
11268 			    *(uint32_t *)invalp);
11269 			if (error != 0) {
11270 				*outlenp = 0;
11271 				return (error);
11272 			} else {
11273 				*outlenp = sizeof (uint32_t);
11274 			}
11275 			break;
11276 		}
11277 		case IPV6_V6ONLY:
11278 			if (*i1 < 0 || *i1 > 1) {
11279 				return (EINVAL);
11280 			}
11281 			mutex_enter(&connp->conn_lock);
11282 			connp->conn_ipv6_v6only = *i1;
11283 			mutex_exit(&connp->conn_lock);
11284 			break;
11285 		default:
11286 			return (-EINVAL);
11287 		}
11288 		break;
11289 	default:
11290 		/*
11291 		 * "soft" error (negative)
11292 		 * option not handled at this level
11293 		 * Note: Do not modify *outlenp
11294 		 */
11295 		return (-EINVAL);
11296 	}
11297 	/*
11298 	 * Common case of return from an option that is sizeof (int)
11299 	 */
11300 	*(int *)outvalp = *i1;
11301 	*outlenp = sizeof (int);
11302 	return (0);
11303 }
11304 
11305 /*
11306  * This routine gets default values of certain options whose default
11307  * values are maintained by protocol specific code
11308  */
11309 /* ARGSUSED */
11310 int
11311 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11312 {
11313 	int *i1 = (int *)ptr;
11314 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11315 
11316 	switch (level) {
11317 	case IPPROTO_IP:
11318 		switch (name) {
11319 		case IP_MULTICAST_TTL:
11320 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11321 			return (sizeof (uchar_t));
11322 		case IP_MULTICAST_LOOP:
11323 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11324 			return (sizeof (uchar_t));
11325 		default:
11326 			return (-1);
11327 		}
11328 	case IPPROTO_IPV6:
11329 		switch (name) {
11330 		case IPV6_UNICAST_HOPS:
11331 			*i1 = ipst->ips_ipv6_def_hops;
11332 			return (sizeof (int));
11333 		case IPV6_MULTICAST_HOPS:
11334 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11335 			return (sizeof (int));
11336 		case IPV6_MULTICAST_LOOP:
11337 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11338 			return (sizeof (int));
11339 		case IPV6_V6ONLY:
11340 			*i1 = 1;
11341 			return (sizeof (int));
11342 		default:
11343 			return (-1);
11344 		}
11345 	default:
11346 		return (-1);
11347 	}
11348 	/* NOTREACHED */
11349 }
11350 
11351 /*
11352  * Given a destination address and a pointer to where to put the information
11353  * this routine fills in the mtuinfo.
11354  */
11355 int
11356 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11357     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11358 {
11359 	ire_t *ire;
11360 	ip_stack_t	*ipst = ns->netstack_ip;
11361 
11362 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11363 		return (-1);
11364 
11365 	bzero(mtuinfo, sizeof (*mtuinfo));
11366 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11367 	mtuinfo->ip6m_addr.sin6_port = port;
11368 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11369 
11370 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11371 	if (ire != NULL) {
11372 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11373 		ire_refrele(ire);
11374 	} else {
11375 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11376 	}
11377 	return (sizeof (struct ip6_mtuinfo));
11378 }
11379 
11380 /*
11381  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11382  * checking of cred and that ip_g_mrouter is set should be done and
11383  * isn't.  This doesn't matter as the error checking is done properly for the
11384  * other MRT options coming in through ip_opt_set.
11385  */
11386 int
11387 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11388 {
11389 	conn_t		*connp = Q_TO_CONN(q);
11390 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11391 
11392 	switch (level) {
11393 	case IPPROTO_IP:
11394 		switch (name) {
11395 		case MRT_VERSION:
11396 		case MRT_ASSERT:
11397 			(void) ip_mrouter_get(name, q, ptr);
11398 			return (sizeof (int));
11399 		case IP_SEC_OPT:
11400 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11401 		case IP_NEXTHOP:
11402 			if (connp->conn_nexthop_set) {
11403 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11404 				return (sizeof (ipaddr_t));
11405 			} else
11406 				return (0);
11407 		case IP_RECVPKTINFO:
11408 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11409 			return (sizeof (int));
11410 		default:
11411 			break;
11412 		}
11413 		break;
11414 	case IPPROTO_IPV6:
11415 		switch (name) {
11416 		case IPV6_SEC_OPT:
11417 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11418 		case IPV6_SRC_PREFERENCES: {
11419 			return (ip6_get_src_preferences(connp,
11420 			    (uint32_t *)ptr));
11421 		}
11422 		case IPV6_V6ONLY:
11423 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11424 			return (sizeof (int));
11425 		case IPV6_PATHMTU:
11426 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11427 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11428 		default:
11429 			break;
11430 		}
11431 		break;
11432 	default:
11433 		break;
11434 	}
11435 	return (-1);
11436 }
11437 /* Named Dispatch routine to get a current value out of our parameter table. */
11438 /* ARGSUSED */
11439 static int
11440 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11441 {
11442 	ipparam_t *ippa = (ipparam_t *)cp;
11443 
11444 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11445 	return (0);
11446 }
11447 
11448 /* ARGSUSED */
11449 static int
11450 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11451 {
11452 
11453 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11454 	return (0);
11455 }
11456 
11457 /*
11458  * Set ip{,6}_forwarding values.  This means walking through all of the
11459  * ill's and toggling their forwarding values.
11460  */
11461 /* ARGSUSED */
11462 static int
11463 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11464 {
11465 	long new_value;
11466 	int *forwarding_value = (int *)cp;
11467 	ill_t *ill;
11468 	boolean_t isv6;
11469 	ill_walk_context_t ctx;
11470 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11471 
11472 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11473 
11474 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11475 	    new_value < 0 || new_value > 1) {
11476 		return (EINVAL);
11477 	}
11478 
11479 	*forwarding_value = new_value;
11480 
11481 	/*
11482 	 * Regardless of the current value of ip_forwarding, set all per-ill
11483 	 * values of ip_forwarding to the value being set.
11484 	 *
11485 	 * Bring all the ill's up to date with the new global value.
11486 	 */
11487 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11488 
11489 	if (isv6)
11490 		ill = ILL_START_WALK_V6(&ctx, ipst);
11491 	else
11492 		ill = ILL_START_WALK_V4(&ctx, ipst);
11493 
11494 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11495 		(void) ill_forward_set(ill, new_value != 0);
11496 
11497 	rw_exit(&ipst->ips_ill_g_lock);
11498 	return (0);
11499 }
11500 
11501 /*
11502  * Walk through the param array specified registering each element with the
11503  * Named Dispatch handler. This is called only during init. So it is ok
11504  * not to acquire any locks
11505  */
11506 static boolean_t
11507 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11508     ipndp_t *ipnd, size_t ipnd_cnt)
11509 {
11510 	for (; ippa_cnt-- > 0; ippa++) {
11511 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11512 			if (!nd_load(ndp, ippa->ip_param_name,
11513 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11514 				nd_free(ndp);
11515 				return (B_FALSE);
11516 			}
11517 		}
11518 	}
11519 
11520 	for (; ipnd_cnt-- > 0; ipnd++) {
11521 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11522 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11523 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11524 			    ipnd->ip_ndp_data)) {
11525 				nd_free(ndp);
11526 				return (B_FALSE);
11527 			}
11528 		}
11529 	}
11530 
11531 	return (B_TRUE);
11532 }
11533 
11534 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11535 /* ARGSUSED */
11536 static int
11537 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11538 {
11539 	long		new_value;
11540 	ipparam_t	*ippa = (ipparam_t *)cp;
11541 
11542 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11543 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11544 		return (EINVAL);
11545 	}
11546 	ippa->ip_param_value = new_value;
11547 	return (0);
11548 }
11549 
11550 /*
11551  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11552  * When an ipf is passed here for the first time, if
11553  * we already have in-order fragments on the queue, we convert from the fast-
11554  * path reassembly scheme to the hard-case scheme.  From then on, additional
11555  * fragments are reassembled here.  We keep track of the start and end offsets
11556  * of each piece, and the number of holes in the chain.  When the hole count
11557  * goes to zero, we are done!
11558  *
11559  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11560  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11561  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11562  * after the call to ip_reassemble().
11563  */
11564 int
11565 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11566     size_t msg_len)
11567 {
11568 	uint_t	end;
11569 	mblk_t	*next_mp;
11570 	mblk_t	*mp1;
11571 	uint_t	offset;
11572 	boolean_t incr_dups = B_TRUE;
11573 	boolean_t offset_zero_seen = B_FALSE;
11574 	boolean_t pkt_boundary_checked = B_FALSE;
11575 
11576 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11577 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11578 
11579 	/* Add in byte count */
11580 	ipf->ipf_count += msg_len;
11581 	if (ipf->ipf_end) {
11582 		/*
11583 		 * We were part way through in-order reassembly, but now there
11584 		 * is a hole.  We walk through messages already queued, and
11585 		 * mark them for hard case reassembly.  We know that up till
11586 		 * now they were in order starting from offset zero.
11587 		 */
11588 		offset = 0;
11589 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11590 			IP_REASS_SET_START(mp1, offset);
11591 			if (offset == 0) {
11592 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11593 				offset = -ipf->ipf_nf_hdr_len;
11594 			}
11595 			offset += mp1->b_wptr - mp1->b_rptr;
11596 			IP_REASS_SET_END(mp1, offset);
11597 		}
11598 		/* One hole at the end. */
11599 		ipf->ipf_hole_cnt = 1;
11600 		/* Brand it as a hard case, forever. */
11601 		ipf->ipf_end = 0;
11602 	}
11603 	/* Walk through all the new pieces. */
11604 	do {
11605 		end = start + (mp->b_wptr - mp->b_rptr);
11606 		/*
11607 		 * If start is 0, decrease 'end' only for the first mblk of
11608 		 * the fragment. Otherwise 'end' can get wrong value in the
11609 		 * second pass of the loop if first mblk is exactly the
11610 		 * size of ipf_nf_hdr_len.
11611 		 */
11612 		if (start == 0 && !offset_zero_seen) {
11613 			/* First segment */
11614 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11615 			end -= ipf->ipf_nf_hdr_len;
11616 			offset_zero_seen = B_TRUE;
11617 		}
11618 		next_mp = mp->b_cont;
11619 		/*
11620 		 * We are checking to see if there is any interesing data
11621 		 * to process.  If there isn't and the mblk isn't the
11622 		 * one which carries the unfragmentable header then we
11623 		 * drop it.  It's possible to have just the unfragmentable
11624 		 * header come through without any data.  That needs to be
11625 		 * saved.
11626 		 *
11627 		 * If the assert at the top of this function holds then the
11628 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11629 		 * is infrequently traveled enough that the test is left in
11630 		 * to protect against future code changes which break that
11631 		 * invariant.
11632 		 */
11633 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11634 			/* Empty.  Blast it. */
11635 			IP_REASS_SET_START(mp, 0);
11636 			IP_REASS_SET_END(mp, 0);
11637 			/*
11638 			 * If the ipf points to the mblk we are about to free,
11639 			 * update ipf to point to the next mblk (or NULL
11640 			 * if none).
11641 			 */
11642 			if (ipf->ipf_mp->b_cont == mp)
11643 				ipf->ipf_mp->b_cont = next_mp;
11644 			freeb(mp);
11645 			continue;
11646 		}
11647 		mp->b_cont = NULL;
11648 		IP_REASS_SET_START(mp, start);
11649 		IP_REASS_SET_END(mp, end);
11650 		if (!ipf->ipf_tail_mp) {
11651 			ipf->ipf_tail_mp = mp;
11652 			ipf->ipf_mp->b_cont = mp;
11653 			if (start == 0 || !more) {
11654 				ipf->ipf_hole_cnt = 1;
11655 				/*
11656 				 * if the first fragment comes in more than one
11657 				 * mblk, this loop will be executed for each
11658 				 * mblk. Need to adjust hole count so exiting
11659 				 * this routine will leave hole count at 1.
11660 				 */
11661 				if (next_mp)
11662 					ipf->ipf_hole_cnt++;
11663 			} else
11664 				ipf->ipf_hole_cnt = 2;
11665 			continue;
11666 		} else if (ipf->ipf_last_frag_seen && !more &&
11667 		    !pkt_boundary_checked) {
11668 			/*
11669 			 * We check datagram boundary only if this fragment
11670 			 * claims to be the last fragment and we have seen a
11671 			 * last fragment in the past too. We do this only
11672 			 * once for a given fragment.
11673 			 *
11674 			 * start cannot be 0 here as fragments with start=0
11675 			 * and MF=0 gets handled as a complete packet. These
11676 			 * fragments should not reach here.
11677 			 */
11678 
11679 			if (start + msgdsize(mp) !=
11680 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11681 				/*
11682 				 * We have two fragments both of which claim
11683 				 * to be the last fragment but gives conflicting
11684 				 * information about the whole datagram size.
11685 				 * Something fishy is going on. Drop the
11686 				 * fragment and free up the reassembly list.
11687 				 */
11688 				return (IP_REASS_FAILED);
11689 			}
11690 
11691 			/*
11692 			 * We shouldn't come to this code block again for this
11693 			 * particular fragment.
11694 			 */
11695 			pkt_boundary_checked = B_TRUE;
11696 		}
11697 
11698 		/* New stuff at or beyond tail? */
11699 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11700 		if (start >= offset) {
11701 			if (ipf->ipf_last_frag_seen) {
11702 				/* current fragment is beyond last fragment */
11703 				return (IP_REASS_FAILED);
11704 			}
11705 			/* Link it on end. */
11706 			ipf->ipf_tail_mp->b_cont = mp;
11707 			ipf->ipf_tail_mp = mp;
11708 			if (more) {
11709 				if (start != offset)
11710 					ipf->ipf_hole_cnt++;
11711 			} else if (start == offset && next_mp == NULL)
11712 					ipf->ipf_hole_cnt--;
11713 			continue;
11714 		}
11715 		mp1 = ipf->ipf_mp->b_cont;
11716 		offset = IP_REASS_START(mp1);
11717 		/* New stuff at the front? */
11718 		if (start < offset) {
11719 			if (start == 0) {
11720 				if (end >= offset) {
11721 					/* Nailed the hole at the begining. */
11722 					ipf->ipf_hole_cnt--;
11723 				}
11724 			} else if (end < offset) {
11725 				/*
11726 				 * A hole, stuff, and a hole where there used
11727 				 * to be just a hole.
11728 				 */
11729 				ipf->ipf_hole_cnt++;
11730 			}
11731 			mp->b_cont = mp1;
11732 			/* Check for overlap. */
11733 			while (end > offset) {
11734 				if (end < IP_REASS_END(mp1)) {
11735 					mp->b_wptr -= end - offset;
11736 					IP_REASS_SET_END(mp, offset);
11737 					BUMP_MIB(ill->ill_ip_mib,
11738 					    ipIfStatsReasmPartDups);
11739 					break;
11740 				}
11741 				/* Did we cover another hole? */
11742 				if ((mp1->b_cont &&
11743 				    IP_REASS_END(mp1) !=
11744 				    IP_REASS_START(mp1->b_cont) &&
11745 				    end >= IP_REASS_START(mp1->b_cont)) ||
11746 				    (!ipf->ipf_last_frag_seen && !more)) {
11747 					ipf->ipf_hole_cnt--;
11748 				}
11749 				/* Clip out mp1. */
11750 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11751 					/*
11752 					 * After clipping out mp1, this guy
11753 					 * is now hanging off the end.
11754 					 */
11755 					ipf->ipf_tail_mp = mp;
11756 				}
11757 				IP_REASS_SET_START(mp1, 0);
11758 				IP_REASS_SET_END(mp1, 0);
11759 				/* Subtract byte count */
11760 				ipf->ipf_count -= mp1->b_datap->db_lim -
11761 				    mp1->b_datap->db_base;
11762 				freeb(mp1);
11763 				BUMP_MIB(ill->ill_ip_mib,
11764 				    ipIfStatsReasmPartDups);
11765 				mp1 = mp->b_cont;
11766 				if (!mp1)
11767 					break;
11768 				offset = IP_REASS_START(mp1);
11769 			}
11770 			ipf->ipf_mp->b_cont = mp;
11771 			continue;
11772 		}
11773 		/*
11774 		 * The new piece starts somewhere between the start of the head
11775 		 * and before the end of the tail.
11776 		 */
11777 		for (; mp1; mp1 = mp1->b_cont) {
11778 			offset = IP_REASS_END(mp1);
11779 			if (start < offset) {
11780 				if (end <= offset) {
11781 					/* Nothing new. */
11782 					IP_REASS_SET_START(mp, 0);
11783 					IP_REASS_SET_END(mp, 0);
11784 					/* Subtract byte count */
11785 					ipf->ipf_count -= mp->b_datap->db_lim -
11786 					    mp->b_datap->db_base;
11787 					if (incr_dups) {
11788 						ipf->ipf_num_dups++;
11789 						incr_dups = B_FALSE;
11790 					}
11791 					freeb(mp);
11792 					BUMP_MIB(ill->ill_ip_mib,
11793 					    ipIfStatsReasmDuplicates);
11794 					break;
11795 				}
11796 				/*
11797 				 * Trim redundant stuff off beginning of new
11798 				 * piece.
11799 				 */
11800 				IP_REASS_SET_START(mp, offset);
11801 				mp->b_rptr += offset - start;
11802 				BUMP_MIB(ill->ill_ip_mib,
11803 				    ipIfStatsReasmPartDups);
11804 				start = offset;
11805 				if (!mp1->b_cont) {
11806 					/*
11807 					 * After trimming, this guy is now
11808 					 * hanging off the end.
11809 					 */
11810 					mp1->b_cont = mp;
11811 					ipf->ipf_tail_mp = mp;
11812 					if (!more) {
11813 						ipf->ipf_hole_cnt--;
11814 					}
11815 					break;
11816 				}
11817 			}
11818 			if (start >= IP_REASS_START(mp1->b_cont))
11819 				continue;
11820 			/* Fill a hole */
11821 			if (start > offset)
11822 				ipf->ipf_hole_cnt++;
11823 			mp->b_cont = mp1->b_cont;
11824 			mp1->b_cont = mp;
11825 			mp1 = mp->b_cont;
11826 			offset = IP_REASS_START(mp1);
11827 			if (end >= offset) {
11828 				ipf->ipf_hole_cnt--;
11829 				/* Check for overlap. */
11830 				while (end > offset) {
11831 					if (end < IP_REASS_END(mp1)) {
11832 						mp->b_wptr -= end - offset;
11833 						IP_REASS_SET_END(mp, offset);
11834 						/*
11835 						 * TODO we might bump
11836 						 * this up twice if there is
11837 						 * overlap at both ends.
11838 						 */
11839 						BUMP_MIB(ill->ill_ip_mib,
11840 						    ipIfStatsReasmPartDups);
11841 						break;
11842 					}
11843 					/* Did we cover another hole? */
11844 					if ((mp1->b_cont &&
11845 					    IP_REASS_END(mp1)
11846 					    != IP_REASS_START(mp1->b_cont) &&
11847 					    end >=
11848 					    IP_REASS_START(mp1->b_cont)) ||
11849 					    (!ipf->ipf_last_frag_seen &&
11850 					    !more)) {
11851 						ipf->ipf_hole_cnt--;
11852 					}
11853 					/* Clip out mp1. */
11854 					if ((mp->b_cont = mp1->b_cont) ==
11855 					    NULL) {
11856 						/*
11857 						 * After clipping out mp1,
11858 						 * this guy is now hanging
11859 						 * off the end.
11860 						 */
11861 						ipf->ipf_tail_mp = mp;
11862 					}
11863 					IP_REASS_SET_START(mp1, 0);
11864 					IP_REASS_SET_END(mp1, 0);
11865 					/* Subtract byte count */
11866 					ipf->ipf_count -=
11867 					    mp1->b_datap->db_lim -
11868 					    mp1->b_datap->db_base;
11869 					freeb(mp1);
11870 					BUMP_MIB(ill->ill_ip_mib,
11871 					    ipIfStatsReasmPartDups);
11872 					mp1 = mp->b_cont;
11873 					if (!mp1)
11874 						break;
11875 					offset = IP_REASS_START(mp1);
11876 				}
11877 			}
11878 			break;
11879 		}
11880 	} while (start = end, mp = next_mp);
11881 
11882 	/* Fragment just processed could be the last one. Remember this fact */
11883 	if (!more)
11884 		ipf->ipf_last_frag_seen = B_TRUE;
11885 
11886 	/* Still got holes? */
11887 	if (ipf->ipf_hole_cnt)
11888 		return (IP_REASS_PARTIAL);
11889 	/* Clean up overloaded fields to avoid upstream disasters. */
11890 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11891 		IP_REASS_SET_START(mp1, 0);
11892 		IP_REASS_SET_END(mp1, 0);
11893 	}
11894 	return (IP_REASS_COMPLETE);
11895 }
11896 
11897 /*
11898  * ipsec processing for the fast path, used for input UDP Packets
11899  * Returns true if ready for passup to UDP.
11900  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
11901  * was an ESP-in-UDP packet, etc.).
11902  */
11903 static boolean_t
11904 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
11905     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
11906 {
11907 	uint32_t	ill_index;
11908 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
11909 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
11910 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
11911 	udp_t		*udp = connp->conn_udp;
11912 
11913 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11914 	/* The ill_index of the incoming ILL */
11915 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
11916 
11917 	/* pass packet up to the transport */
11918 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
11919 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
11920 		    NULL, mctl_present);
11921 		if (*first_mpp == NULL) {
11922 			return (B_FALSE);
11923 		}
11924 	}
11925 
11926 	/* Initiate IPPF processing for fastpath UDP */
11927 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
11928 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
11929 		if (*mpp == NULL) {
11930 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
11931 			    "deferred/dropped during IPPF processing\n"));
11932 			return (B_FALSE);
11933 		}
11934 	}
11935 	/*
11936 	 * Remove 0-spi if it's 0, or move everything behind
11937 	 * the UDP header over it and forward to ESP via
11938 	 * ip_proto_input().
11939 	 */
11940 	if (udp->udp_nat_t_endpoint) {
11941 		if (mctl_present) {
11942 			/* mctl_present *shouldn't* happen. */
11943 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
11944 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
11945 			    &ipss->ipsec_dropper);
11946 			*first_mpp = NULL;
11947 			return (B_FALSE);
11948 		}
11949 
11950 		/* "ill" is "recv_ill" in actuality. */
11951 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
11952 			return (B_FALSE);
11953 
11954 		/* Else continue like a normal UDP packet. */
11955 	}
11956 
11957 	/*
11958 	 * We make the checks as below since we are in the fast path
11959 	 * and want to minimize the number of checks if the IP_RECVIF and/or
11960 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
11961 	 */
11962 	if (connp->conn_recvif || connp->conn_recvslla ||
11963 	    connp->conn_ip_recvpktinfo) {
11964 		if (connp->conn_recvif) {
11965 			in_flags = IPF_RECVIF;
11966 		}
11967 		/*
11968 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
11969 		 * so the flag passed to ip_add_info is based on IP version
11970 		 * of connp.
11971 		 */
11972 		if (connp->conn_ip_recvpktinfo) {
11973 			if (connp->conn_af_isv6) {
11974 				/*
11975 				 * V6 only needs index
11976 				 */
11977 				in_flags |= IPF_RECVIF;
11978 			} else {
11979 				/*
11980 				 * V4 needs index + matching address.
11981 				 */
11982 				in_flags |= IPF_RECVADDR;
11983 			}
11984 		}
11985 		if (connp->conn_recvslla) {
11986 			in_flags |= IPF_RECVSLLA;
11987 		}
11988 		/*
11989 		 * since in_flags are being set ill will be
11990 		 * referenced in ip_add_info, so it better not
11991 		 * be NULL.
11992 		 */
11993 		/*
11994 		 * the actual data will be contained in b_cont
11995 		 * upon successful return of the following call.
11996 		 * If the call fails then the original mblk is
11997 		 * returned.
11998 		 */
11999 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12000 		    ipst);
12001 	}
12002 
12003 	return (B_TRUE);
12004 }
12005 
12006 /*
12007  * Fragmentation reassembly.  Each ILL has a hash table for
12008  * queuing packets undergoing reassembly for all IPIFs
12009  * associated with the ILL.  The hash is based on the packet
12010  * IP ident field.  The ILL frag hash table was allocated
12011  * as a timer block at the time the ILL was created.  Whenever
12012  * there is anything on the reassembly queue, the timer will
12013  * be running.  Returns B_TRUE if successful else B_FALSE;
12014  * frees mp on failure.
12015  */
12016 static boolean_t
12017 ip_rput_fragment(ill_t *ill, ill_t *recv_ill, mblk_t **mpp, ipha_t *ipha,
12018     uint32_t *cksum_val, uint16_t *cksum_flags)
12019 {
12020 	uint32_t	frag_offset_flags;
12021 	mblk_t		*mp = *mpp;
12022 	mblk_t		*t_mp;
12023 	ipaddr_t	dst;
12024 	uint8_t		proto = ipha->ipha_protocol;
12025 	uint32_t	sum_val;
12026 	uint16_t	sum_flags;
12027 	ipf_t		*ipf;
12028 	ipf_t		**ipfp;
12029 	ipfb_t		*ipfb;
12030 	uint16_t	ident;
12031 	uint32_t	offset;
12032 	ipaddr_t	src;
12033 	uint_t		hdr_length;
12034 	uint32_t	end;
12035 	mblk_t		*mp1;
12036 	mblk_t		*tail_mp;
12037 	size_t		count;
12038 	size_t		msg_len;
12039 	uint8_t		ecn_info = 0;
12040 	uint32_t	packet_size;
12041 	boolean_t	pruned = B_FALSE;
12042 	ip_stack_t *ipst = ill->ill_ipst;
12043 
12044 	if (cksum_val != NULL)
12045 		*cksum_val = 0;
12046 	if (cksum_flags != NULL)
12047 		*cksum_flags = 0;
12048 
12049 	/*
12050 	 * Drop the fragmented as early as possible, if
12051 	 * we don't have resource(s) to re-assemble.
12052 	 */
12053 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12054 		freemsg(mp);
12055 		return (B_FALSE);
12056 	}
12057 
12058 	/* Check for fragmentation offset; return if there's none */
12059 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12060 	    (IPH_MF | IPH_OFFSET)) == 0)
12061 		return (B_TRUE);
12062 
12063 	/*
12064 	 * We utilize hardware computed checksum info only for UDP since
12065 	 * IP fragmentation is a normal occurrence for the protocol.  In
12066 	 * addition, checksum offload support for IP fragments carrying
12067 	 * UDP payload is commonly implemented across network adapters.
12068 	 */
12069 	ASSERT(recv_ill != NULL);
12070 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(recv_ill) &&
12071 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12072 		mblk_t *mp1 = mp->b_cont;
12073 		int32_t len;
12074 
12075 		/* Record checksum information from the packet */
12076 		sum_val = (uint32_t)DB_CKSUM16(mp);
12077 		sum_flags = DB_CKSUMFLAGS(mp);
12078 
12079 		/* IP payload offset from beginning of mblk */
12080 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12081 
12082 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12083 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12084 		    offset >= DB_CKSUMSTART(mp) &&
12085 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12086 			uint32_t adj;
12087 			/*
12088 			 * Partial checksum has been calculated by hardware
12089 			 * and attached to the packet; in addition, any
12090 			 * prepended extraneous data is even byte aligned.
12091 			 * If any such data exists, we adjust the checksum;
12092 			 * this would also handle any postpended data.
12093 			 */
12094 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12095 			    mp, mp1, len, adj);
12096 
12097 			/* One's complement subtract extraneous checksum */
12098 			if (adj >= sum_val)
12099 				sum_val = ~(adj - sum_val) & 0xFFFF;
12100 			else
12101 				sum_val -= adj;
12102 		}
12103 	} else {
12104 		sum_val = 0;
12105 		sum_flags = 0;
12106 	}
12107 
12108 	/* Clear hardware checksumming flag */
12109 	DB_CKSUMFLAGS(mp) = 0;
12110 
12111 	ident = ipha->ipha_ident;
12112 	offset = (frag_offset_flags << 3) & 0xFFFF;
12113 	src = ipha->ipha_src;
12114 	dst = ipha->ipha_dst;
12115 	hdr_length = IPH_HDR_LENGTH(ipha);
12116 	end = ntohs(ipha->ipha_length) - hdr_length;
12117 
12118 	/* If end == 0 then we have a packet with no data, so just free it */
12119 	if (end == 0) {
12120 		freemsg(mp);
12121 		return (B_FALSE);
12122 	}
12123 
12124 	/* Record the ECN field info. */
12125 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12126 	if (offset != 0) {
12127 		/*
12128 		 * If this isn't the first piece, strip the header, and
12129 		 * add the offset to the end value.
12130 		 */
12131 		mp->b_rptr += hdr_length;
12132 		end += offset;
12133 	}
12134 
12135 	msg_len = MBLKSIZE(mp);
12136 	tail_mp = mp;
12137 	while (tail_mp->b_cont != NULL) {
12138 		tail_mp = tail_mp->b_cont;
12139 		msg_len += MBLKSIZE(tail_mp);
12140 	}
12141 
12142 	/* If the reassembly list for this ILL will get too big, prune it */
12143 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12144 	    ipst->ips_ip_reass_queue_bytes) {
12145 		ill_frag_prune(ill,
12146 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12147 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12148 		pruned = B_TRUE;
12149 	}
12150 
12151 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12152 	mutex_enter(&ipfb->ipfb_lock);
12153 
12154 	ipfp = &ipfb->ipfb_ipf;
12155 	/* Try to find an existing fragment queue for this packet. */
12156 	for (;;) {
12157 		ipf = ipfp[0];
12158 		if (ipf != NULL) {
12159 			/*
12160 			 * It has to match on ident and src/dst address.
12161 			 */
12162 			if (ipf->ipf_ident == ident &&
12163 			    ipf->ipf_src == src &&
12164 			    ipf->ipf_dst == dst &&
12165 			    ipf->ipf_protocol == proto) {
12166 				/*
12167 				 * If we have received too many
12168 				 * duplicate fragments for this packet
12169 				 * free it.
12170 				 */
12171 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12172 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12173 					freemsg(mp);
12174 					mutex_exit(&ipfb->ipfb_lock);
12175 					return (B_FALSE);
12176 				}
12177 				/* Found it. */
12178 				break;
12179 			}
12180 			ipfp = &ipf->ipf_hash_next;
12181 			continue;
12182 		}
12183 
12184 		/*
12185 		 * If we pruned the list, do we want to store this new
12186 		 * fragment?. We apply an optimization here based on the
12187 		 * fact that most fragments will be received in order.
12188 		 * So if the offset of this incoming fragment is zero,
12189 		 * it is the first fragment of a new packet. We will
12190 		 * keep it.  Otherwise drop the fragment, as we have
12191 		 * probably pruned the packet already (since the
12192 		 * packet cannot be found).
12193 		 */
12194 		if (pruned && offset != 0) {
12195 			mutex_exit(&ipfb->ipfb_lock);
12196 			freemsg(mp);
12197 			return (B_FALSE);
12198 		}
12199 
12200 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12201 			/*
12202 			 * Too many fragmented packets in this hash
12203 			 * bucket. Free the oldest.
12204 			 */
12205 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12206 		}
12207 
12208 		/* New guy.  Allocate a frag message. */
12209 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12210 		if (mp1 == NULL) {
12211 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12212 			freemsg(mp);
12213 reass_done:
12214 			mutex_exit(&ipfb->ipfb_lock);
12215 			return (B_FALSE);
12216 		}
12217 
12218 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12219 		mp1->b_cont = mp;
12220 
12221 		/* Initialize the fragment header. */
12222 		ipf = (ipf_t *)mp1->b_rptr;
12223 		ipf->ipf_mp = mp1;
12224 		ipf->ipf_ptphn = ipfp;
12225 		ipfp[0] = ipf;
12226 		ipf->ipf_hash_next = NULL;
12227 		ipf->ipf_ident = ident;
12228 		ipf->ipf_protocol = proto;
12229 		ipf->ipf_src = src;
12230 		ipf->ipf_dst = dst;
12231 		ipf->ipf_nf_hdr_len = 0;
12232 		/* Record reassembly start time. */
12233 		ipf->ipf_timestamp = gethrestime_sec();
12234 		/* Record ipf generation and account for frag header */
12235 		ipf->ipf_gen = ill->ill_ipf_gen++;
12236 		ipf->ipf_count = MBLKSIZE(mp1);
12237 		ipf->ipf_last_frag_seen = B_FALSE;
12238 		ipf->ipf_ecn = ecn_info;
12239 		ipf->ipf_num_dups = 0;
12240 		ipfb->ipfb_frag_pkts++;
12241 		ipf->ipf_checksum = 0;
12242 		ipf->ipf_checksum_flags = 0;
12243 
12244 		/* Store checksum value in fragment header */
12245 		if (sum_flags != 0) {
12246 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12247 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12248 			ipf->ipf_checksum = sum_val;
12249 			ipf->ipf_checksum_flags = sum_flags;
12250 		}
12251 
12252 		/*
12253 		 * We handle reassembly two ways.  In the easy case,
12254 		 * where all the fragments show up in order, we do
12255 		 * minimal bookkeeping, and just clip new pieces on
12256 		 * the end.  If we ever see a hole, then we go off
12257 		 * to ip_reassemble which has to mark the pieces and
12258 		 * keep track of the number of holes, etc.  Obviously,
12259 		 * the point of having both mechanisms is so we can
12260 		 * handle the easy case as efficiently as possible.
12261 		 */
12262 		if (offset == 0) {
12263 			/* Easy case, in-order reassembly so far. */
12264 			ipf->ipf_count += msg_len;
12265 			ipf->ipf_tail_mp = tail_mp;
12266 			/*
12267 			 * Keep track of next expected offset in
12268 			 * ipf_end.
12269 			 */
12270 			ipf->ipf_end = end;
12271 			ipf->ipf_nf_hdr_len = hdr_length;
12272 		} else {
12273 			/* Hard case, hole at the beginning. */
12274 			ipf->ipf_tail_mp = NULL;
12275 			/*
12276 			 * ipf_end == 0 means that we have given up
12277 			 * on easy reassembly.
12278 			 */
12279 			ipf->ipf_end = 0;
12280 
12281 			/* Forget checksum offload from now on */
12282 			ipf->ipf_checksum_flags = 0;
12283 
12284 			/*
12285 			 * ipf_hole_cnt is set by ip_reassemble.
12286 			 * ipf_count is updated by ip_reassemble.
12287 			 * No need to check for return value here
12288 			 * as we don't expect reassembly to complete
12289 			 * or fail for the first fragment itself.
12290 			 */
12291 			(void) ip_reassemble(mp, ipf,
12292 			    (frag_offset_flags & IPH_OFFSET) << 3,
12293 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12294 		}
12295 		/* Update per ipfb and ill byte counts */
12296 		ipfb->ipfb_count += ipf->ipf_count;
12297 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12298 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
12299 		/* If the frag timer wasn't already going, start it. */
12300 		mutex_enter(&ill->ill_lock);
12301 		ill_frag_timer_start(ill);
12302 		mutex_exit(&ill->ill_lock);
12303 		goto reass_done;
12304 	}
12305 
12306 	/*
12307 	 * If the packet's flag has changed (it could be coming up
12308 	 * from an interface different than the previous, therefore
12309 	 * possibly different checksum capability), then forget about
12310 	 * any stored checksum states.  Otherwise add the value to
12311 	 * the existing one stored in the fragment header.
12312 	 */
12313 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12314 		sum_val += ipf->ipf_checksum;
12315 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12316 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12317 		ipf->ipf_checksum = sum_val;
12318 	} else if (ipf->ipf_checksum_flags != 0) {
12319 		/* Forget checksum offload from now on */
12320 		ipf->ipf_checksum_flags = 0;
12321 	}
12322 
12323 	/*
12324 	 * We have a new piece of a datagram which is already being
12325 	 * reassembled.  Update the ECN info if all IP fragments
12326 	 * are ECN capable.  If there is one which is not, clear
12327 	 * all the info.  If there is at least one which has CE
12328 	 * code point, IP needs to report that up to transport.
12329 	 */
12330 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12331 		if (ecn_info == IPH_ECN_CE)
12332 			ipf->ipf_ecn = IPH_ECN_CE;
12333 	} else {
12334 		ipf->ipf_ecn = IPH_ECN_NECT;
12335 	}
12336 	if (offset && ipf->ipf_end == offset) {
12337 		/* The new fragment fits at the end */
12338 		ipf->ipf_tail_mp->b_cont = mp;
12339 		/* Update the byte count */
12340 		ipf->ipf_count += msg_len;
12341 		/* Update per ipfb and ill byte counts */
12342 		ipfb->ipfb_count += msg_len;
12343 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12344 		atomic_add_32(&ill->ill_frag_count, msg_len);
12345 		if (frag_offset_flags & IPH_MF) {
12346 			/* More to come. */
12347 			ipf->ipf_end = end;
12348 			ipf->ipf_tail_mp = tail_mp;
12349 			goto reass_done;
12350 		}
12351 	} else {
12352 		/* Go do the hard cases. */
12353 		int ret;
12354 
12355 		if (offset == 0)
12356 			ipf->ipf_nf_hdr_len = hdr_length;
12357 
12358 		/* Save current byte count */
12359 		count = ipf->ipf_count;
12360 		ret = ip_reassemble(mp, ipf,
12361 		    (frag_offset_flags & IPH_OFFSET) << 3,
12362 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12363 		/* Count of bytes added and subtracted (freeb()ed) */
12364 		count = ipf->ipf_count - count;
12365 		if (count) {
12366 			/* Update per ipfb and ill byte counts */
12367 			ipfb->ipfb_count += count;
12368 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12369 			atomic_add_32(&ill->ill_frag_count, count);
12370 		}
12371 		if (ret == IP_REASS_PARTIAL) {
12372 			goto reass_done;
12373 		} else if (ret == IP_REASS_FAILED) {
12374 			/* Reassembly failed. Free up all resources */
12375 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12376 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12377 				IP_REASS_SET_START(t_mp, 0);
12378 				IP_REASS_SET_END(t_mp, 0);
12379 			}
12380 			freemsg(mp);
12381 			goto reass_done;
12382 		}
12383 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12384 	}
12385 	/*
12386 	 * We have completed reassembly.  Unhook the frag header from
12387 	 * the reassembly list.
12388 	 *
12389 	 * Before we free the frag header, record the ECN info
12390 	 * to report back to the transport.
12391 	 */
12392 	ecn_info = ipf->ipf_ecn;
12393 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12394 	ipfp = ipf->ipf_ptphn;
12395 
12396 	/* We need to supply these to caller */
12397 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12398 		sum_val = ipf->ipf_checksum;
12399 	else
12400 		sum_val = 0;
12401 
12402 	mp1 = ipf->ipf_mp;
12403 	count = ipf->ipf_count;
12404 	ipf = ipf->ipf_hash_next;
12405 	if (ipf != NULL)
12406 		ipf->ipf_ptphn = ipfp;
12407 	ipfp[0] = ipf;
12408 	atomic_add_32(&ill->ill_frag_count, -count);
12409 	ASSERT(ipfb->ipfb_count >= count);
12410 	ipfb->ipfb_count -= count;
12411 	ipfb->ipfb_frag_pkts--;
12412 	mutex_exit(&ipfb->ipfb_lock);
12413 	/* Ditch the frag header. */
12414 	mp = mp1->b_cont;
12415 
12416 	freeb(mp1);
12417 
12418 	/* Restore original IP length in header. */
12419 	packet_size = (uint32_t)msgdsize(mp);
12420 	if (packet_size > IP_MAXPACKET) {
12421 		freemsg(mp);
12422 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12423 		return (B_FALSE);
12424 	}
12425 
12426 	if (DB_REF(mp) > 1) {
12427 		mblk_t *mp2 = copymsg(mp);
12428 
12429 		freemsg(mp);
12430 		if (mp2 == NULL) {
12431 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12432 			return (B_FALSE);
12433 		}
12434 		mp = mp2;
12435 	}
12436 	ipha = (ipha_t *)mp->b_rptr;
12437 
12438 	ipha->ipha_length = htons((uint16_t)packet_size);
12439 	/* We're now complete, zip the frag state */
12440 	ipha->ipha_fragment_offset_and_flags = 0;
12441 	/* Record the ECN info. */
12442 	ipha->ipha_type_of_service &= 0xFC;
12443 	ipha->ipha_type_of_service |= ecn_info;
12444 	*mpp = mp;
12445 
12446 	/* Reassembly is successful; return checksum information if needed */
12447 	if (cksum_val != NULL)
12448 		*cksum_val = sum_val;
12449 	if (cksum_flags != NULL)
12450 		*cksum_flags = sum_flags;
12451 
12452 	return (B_TRUE);
12453 }
12454 
12455 /*
12456  * Perform ip header check sum update local options.
12457  * return B_TRUE if all is well, else return B_FALSE and release
12458  * the mp. caller is responsible for decrementing ire ref cnt.
12459  */
12460 static boolean_t
12461 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12462     ip_stack_t *ipst)
12463 {
12464 	mblk_t		*first_mp;
12465 	boolean_t	mctl_present;
12466 	uint16_t	sum;
12467 
12468 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12469 	/*
12470 	 * Don't do the checksum if it has gone through AH/ESP
12471 	 * processing.
12472 	 */
12473 	if (!mctl_present) {
12474 		sum = ip_csum_hdr(ipha);
12475 		if (sum != 0) {
12476 			if (ill != NULL) {
12477 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12478 			} else {
12479 				BUMP_MIB(&ipst->ips_ip_mib,
12480 				    ipIfStatsInCksumErrs);
12481 			}
12482 			freemsg(first_mp);
12483 			return (B_FALSE);
12484 		}
12485 	}
12486 
12487 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12488 		if (mctl_present)
12489 			freeb(first_mp);
12490 		return (B_FALSE);
12491 	}
12492 
12493 	return (B_TRUE);
12494 }
12495 
12496 /*
12497  * All udp packet are delivered to the local host via this routine.
12498  */
12499 void
12500 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12501     ill_t *recv_ill)
12502 {
12503 	uint32_t	sum;
12504 	uint32_t	u1;
12505 	boolean_t	mctl_present;
12506 	conn_t		*connp;
12507 	mblk_t		*first_mp;
12508 	uint16_t	*up;
12509 	ill_t		*ill = (ill_t *)q->q_ptr;
12510 	uint16_t	reass_hck_flags = 0;
12511 	ip_stack_t	*ipst;
12512 
12513 	ASSERT(recv_ill != NULL);
12514 	ipst = recv_ill->ill_ipst;
12515 
12516 #define	rptr    ((uchar_t *)ipha)
12517 
12518 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12519 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12520 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12521 	ASSERT(ill != NULL);
12522 
12523 	/*
12524 	 * FAST PATH for udp packets
12525 	 */
12526 
12527 	/* u1 is # words of IP options */
12528 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12529 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12530 
12531 	/* IP options present */
12532 	if (u1 != 0)
12533 		goto ipoptions;
12534 
12535 	/* Check the IP header checksum.  */
12536 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12537 		/* Clear the IP header h/w cksum flag */
12538 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12539 	} else if (!mctl_present) {
12540 		/*
12541 		 * Don't verify header checksum if this packet is coming
12542 		 * back from AH/ESP as we already did it.
12543 		 */
12544 #define	uph	((uint16_t *)ipha)
12545 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12546 		    uph[6] + uph[7] + uph[8] + uph[9];
12547 #undef	uph
12548 		/* finish doing IP checksum */
12549 		sum = (sum & 0xFFFF) + (sum >> 16);
12550 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12551 		if (sum != 0 && sum != 0xFFFF) {
12552 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12553 			freemsg(first_mp);
12554 			return;
12555 		}
12556 	}
12557 
12558 	/*
12559 	 * Count for SNMP of inbound packets for ire.
12560 	 * if mctl is present this might be a secure packet and
12561 	 * has already been counted for in ip_proto_input().
12562 	 */
12563 	if (!mctl_present) {
12564 		UPDATE_IB_PKT_COUNT(ire);
12565 		ire->ire_last_used_time = lbolt;
12566 	}
12567 
12568 	/* packet part of fragmented IP packet? */
12569 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12570 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12571 		goto fragmented;
12572 	}
12573 
12574 	/* u1 = IP header length (20 bytes) */
12575 	u1 = IP_SIMPLE_HDR_LENGTH;
12576 
12577 	/* packet does not contain complete IP & UDP headers */
12578 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12579 		goto udppullup;
12580 
12581 	/* up points to UDP header */
12582 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12583 #define	iphs    ((uint16_t *)ipha)
12584 
12585 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12586 	if (up[3] != 0) {
12587 		mblk_t *mp1 = mp->b_cont;
12588 		boolean_t cksum_err;
12589 		uint16_t hck_flags = 0;
12590 
12591 		/* Pseudo-header checksum */
12592 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12593 		    iphs[9] + up[2];
12594 
12595 		/*
12596 		 * Revert to software checksum calculation if the interface
12597 		 * isn't capable of checksum offload or if IPsec is present.
12598 		 */
12599 		if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
12600 			hck_flags = DB_CKSUMFLAGS(mp);
12601 
12602 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12603 			IP_STAT(ipst, ip_in_sw_cksum);
12604 
12605 		IP_CKSUM_RECV(hck_flags, u1,
12606 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12607 		    (int32_t)((uchar_t *)up - rptr),
12608 		    mp, mp1, cksum_err);
12609 
12610 		if (cksum_err) {
12611 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12612 			if (hck_flags & HCK_FULLCKSUM)
12613 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12614 			else if (hck_flags & HCK_PARTIALCKSUM)
12615 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12616 			else
12617 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12618 
12619 			freemsg(first_mp);
12620 			return;
12621 		}
12622 	}
12623 
12624 	/* Non-fragmented broadcast or multicast packet? */
12625 	if (ire->ire_type == IRE_BROADCAST)
12626 		goto udpslowpath;
12627 
12628 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12629 	    ire->ire_zoneid, ipst)) != NULL) {
12630 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
12631 		IP_STAT(ipst, ip_udp_fast_path);
12632 
12633 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
12634 		    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
12635 			freemsg(mp);
12636 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12637 		} else {
12638 			if (!mctl_present) {
12639 				BUMP_MIB(ill->ill_ip_mib,
12640 				    ipIfStatsHCInDelivers);
12641 			}
12642 			/*
12643 			 * mp and first_mp can change.
12644 			 */
12645 			if (ip_udp_check(q, connp, recv_ill,
12646 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12647 				/* Send it upstream */
12648 				(connp->conn_recv)(connp, mp, NULL);
12649 			}
12650 		}
12651 		/*
12652 		 * freeb() cannot deal with null mblk being passed
12653 		 * in and first_mp can be set to null in the call
12654 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12655 		 */
12656 		if (mctl_present && first_mp != NULL) {
12657 			freeb(first_mp);
12658 		}
12659 		CONN_DEC_REF(connp);
12660 		return;
12661 	}
12662 
12663 	/*
12664 	 * if we got here we know the packet is not fragmented and
12665 	 * has no options. The classifier could not find a conn_t and
12666 	 * most likely its an icmp packet so send it through slow path.
12667 	 */
12668 
12669 	goto udpslowpath;
12670 
12671 ipoptions:
12672 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12673 		goto slow_done;
12674 	}
12675 
12676 	UPDATE_IB_PKT_COUNT(ire);
12677 	ire->ire_last_used_time = lbolt;
12678 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12679 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12680 fragmented:
12681 		/*
12682 		 * "sum" and "reass_hck_flags" are non-zero if the
12683 		 * reassembled packet has a valid hardware computed
12684 		 * checksum information associated with it.
12685 		 */
12686 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, &sum,
12687 		    &reass_hck_flags)) {
12688 			goto slow_done;
12689 		}
12690 
12691 		/*
12692 		 * Make sure that first_mp points back to mp as
12693 		 * the mp we came in with could have changed in
12694 		 * ip_rput_fragment().
12695 		 */
12696 		ASSERT(!mctl_present);
12697 		ipha = (ipha_t *)mp->b_rptr;
12698 		first_mp = mp;
12699 	}
12700 
12701 	/* Now we have a complete datagram, destined for this machine. */
12702 	u1 = IPH_HDR_LENGTH(ipha);
12703 	/* Pull up the UDP header, if necessary. */
12704 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12705 udppullup:
12706 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12707 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12708 			freemsg(first_mp);
12709 			goto slow_done;
12710 		}
12711 		ipha = (ipha_t *)mp->b_rptr;
12712 	}
12713 
12714 	/*
12715 	 * Validate the checksum for the reassembled packet; for the
12716 	 * pullup case we calculate the payload checksum in software.
12717 	 */
12718 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12719 	if (up[3] != 0) {
12720 		boolean_t cksum_err;
12721 
12722 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12723 			IP_STAT(ipst, ip_in_sw_cksum);
12724 
12725 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12726 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12727 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12728 		    iphs[9] + up[2], sum, cksum_err);
12729 
12730 		if (cksum_err) {
12731 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12732 
12733 			if (reass_hck_flags & HCK_FULLCKSUM)
12734 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12735 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12736 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12737 			else
12738 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12739 
12740 			freemsg(first_mp);
12741 			goto slow_done;
12742 		}
12743 	}
12744 udpslowpath:
12745 
12746 	/* Clear hardware checksum flag to be safe */
12747 	DB_CKSUMFLAGS(mp) = 0;
12748 
12749 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12750 	    (ire->ire_type == IRE_BROADCAST),
12751 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12752 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12753 
12754 slow_done:
12755 	IP_STAT(ipst, ip_udp_slow_path);
12756 	return;
12757 
12758 #undef  iphs
12759 #undef  rptr
12760 }
12761 
12762 /* ARGSUSED */
12763 static mblk_t *
12764 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12765     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12766     ill_rx_ring_t *ill_ring)
12767 {
12768 	conn_t		*connp;
12769 	uint32_t	sum;
12770 	uint32_t	u1;
12771 	uint16_t	*up;
12772 	int		offset;
12773 	ssize_t		len;
12774 	mblk_t		*mp1;
12775 	boolean_t	syn_present = B_FALSE;
12776 	tcph_t		*tcph;
12777 	uint_t		tcph_flags;
12778 	uint_t		ip_hdr_len;
12779 	ill_t		*ill = (ill_t *)q->q_ptr;
12780 	zoneid_t	zoneid = ire->ire_zoneid;
12781 	boolean_t	cksum_err;
12782 	uint16_t	hck_flags = 0;
12783 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12784 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12785 
12786 #define	rptr	((uchar_t *)ipha)
12787 
12788 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12789 	ASSERT(ill != NULL);
12790 
12791 	/*
12792 	 * FAST PATH for tcp packets
12793 	 */
12794 
12795 	/* u1 is # words of IP options */
12796 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12797 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12798 
12799 	/* IP options present */
12800 	if (u1) {
12801 		goto ipoptions;
12802 	} else if (!mctl_present) {
12803 		/* Check the IP header checksum.  */
12804 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12805 			/* Clear the IP header h/w cksum flag */
12806 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12807 		} else if (!mctl_present) {
12808 			/*
12809 			 * Don't verify header checksum if this packet
12810 			 * is coming back from AH/ESP as we already did it.
12811 			 */
12812 #define	uph	((uint16_t *)ipha)
12813 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12814 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12815 #undef	uph
12816 			/* finish doing IP checksum */
12817 			sum = (sum & 0xFFFF) + (sum >> 16);
12818 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12819 			if (sum != 0 && sum != 0xFFFF) {
12820 				BUMP_MIB(ill->ill_ip_mib,
12821 				    ipIfStatsInCksumErrs);
12822 				goto error;
12823 			}
12824 		}
12825 	}
12826 
12827 	if (!mctl_present) {
12828 		UPDATE_IB_PKT_COUNT(ire);
12829 		ire->ire_last_used_time = lbolt;
12830 	}
12831 
12832 	/* packet part of fragmented IP packet? */
12833 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12834 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12835 		goto fragmented;
12836 	}
12837 
12838 	/* u1 = IP header length (20 bytes) */
12839 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12840 
12841 	/* does packet contain IP+TCP headers? */
12842 	len = mp->b_wptr - rptr;
12843 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12844 		IP_STAT(ipst, ip_tcppullup);
12845 		goto tcppullup;
12846 	}
12847 
12848 	/* TCP options present? */
12849 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12850 
12851 	/*
12852 	 * If options need to be pulled up, then goto tcpoptions.
12853 	 * otherwise we are still in the fast path
12854 	 */
12855 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12856 		IP_STAT(ipst, ip_tcpoptions);
12857 		goto tcpoptions;
12858 	}
12859 
12860 	/* multiple mblks of tcp data? */
12861 	if ((mp1 = mp->b_cont) != NULL) {
12862 		/* more then two? */
12863 		if (mp1->b_cont != NULL) {
12864 			IP_STAT(ipst, ip_multipkttcp);
12865 			goto multipkttcp;
12866 		}
12867 		len += mp1->b_wptr - mp1->b_rptr;
12868 	}
12869 
12870 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12871 
12872 	/* part of pseudo checksum */
12873 
12874 	/* TCP datagram length */
12875 	u1 = len - IP_SIMPLE_HDR_LENGTH;
12876 
12877 #define	iphs    ((uint16_t *)ipha)
12878 
12879 #ifdef	_BIG_ENDIAN
12880 	u1 += IPPROTO_TCP;
12881 #else
12882 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12883 #endif
12884 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12885 
12886 	/*
12887 	 * Revert to software checksum calculation if the interface
12888 	 * isn't capable of checksum offload or if IPsec is present.
12889 	 */
12890 	if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
12891 		hck_flags = DB_CKSUMFLAGS(mp);
12892 
12893 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12894 		IP_STAT(ipst, ip_in_sw_cksum);
12895 
12896 	IP_CKSUM_RECV(hck_flags, u1,
12897 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12898 	    (int32_t)((uchar_t *)up - rptr),
12899 	    mp, mp1, cksum_err);
12900 
12901 	if (cksum_err) {
12902 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
12903 
12904 		if (hck_flags & HCK_FULLCKSUM)
12905 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
12906 		else if (hck_flags & HCK_PARTIALCKSUM)
12907 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
12908 		else
12909 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
12910 
12911 		goto error;
12912 	}
12913 
12914 try_again:
12915 
12916 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
12917 	    zoneid, ipst)) == NULL) {
12918 		/* Send the TH_RST */
12919 		goto no_conn;
12920 	}
12921 
12922 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
12923 	tcph_flags = tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG);
12924 
12925 	/*
12926 	 * TCP FAST PATH for AF_INET socket.
12927 	 *
12928 	 * TCP fast path to avoid extra work. An AF_INET socket type
12929 	 * does not have facility to receive extra information via
12930 	 * ip_process or ip_add_info. Also, when the connection was
12931 	 * established, we made a check if this connection is impacted
12932 	 * by any global IPsec policy or per connection policy (a
12933 	 * policy that comes in effect later will not apply to this
12934 	 * connection). Since all this can be determined at the
12935 	 * connection establishment time, a quick check of flags
12936 	 * can avoid extra work.
12937 	 */
12938 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
12939 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12940 		ASSERT(first_mp == mp);
12941 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
12942 		if (tcph_flags != (TH_SYN | TH_ACK)) {
12943 			SET_SQUEUE(mp, tcp_rput_data, connp);
12944 			return (mp);
12945 		}
12946 		mp->b_datap->db_struioflag |= STRUIO_CONNECT;
12947 		DB_CKSUMSTART(mp) = (intptr_t)ip_squeue_get(ill_ring);
12948 		SET_SQUEUE(mp, tcp_input, connp);
12949 		return (mp);
12950 	}
12951 
12952 	if (tcph_flags == TH_SYN) {
12953 		if (IPCL_IS_TCP(connp)) {
12954 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
12955 			DB_CKSUMSTART(mp) =
12956 			    (intptr_t)ip_squeue_get(ill_ring);
12957 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
12958 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
12959 				BUMP_MIB(ill->ill_ip_mib,
12960 				    ipIfStatsHCInDelivers);
12961 				SET_SQUEUE(mp, connp->conn_recv, connp);
12962 				return (mp);
12963 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
12964 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
12965 				BUMP_MIB(ill->ill_ip_mib,
12966 				    ipIfStatsHCInDelivers);
12967 				ip_squeue_enter_unbound++;
12968 				SET_SQUEUE(mp, tcp_conn_request_unbound,
12969 				    connp);
12970 				return (mp);
12971 			}
12972 			syn_present = B_TRUE;
12973 		}
12974 	}
12975 
12976 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
12977 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12978 
12979 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
12980 		/* No need to send this packet to TCP */
12981 		if ((flags & TH_RST) || (flags & TH_URG)) {
12982 			CONN_DEC_REF(connp);
12983 			freemsg(first_mp);
12984 			return (NULL);
12985 		}
12986 		if (flags & TH_ACK) {
12987 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
12988 			    ipst->ips_netstack->netstack_tcp, connp);
12989 			CONN_DEC_REF(connp);
12990 			return (NULL);
12991 		}
12992 
12993 		CONN_DEC_REF(connp);
12994 		freemsg(first_mp);
12995 		return (NULL);
12996 	}
12997 
12998 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12999 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13000 		    ipha, NULL, mctl_present);
13001 		if (first_mp == NULL) {
13002 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13003 			CONN_DEC_REF(connp);
13004 			return (NULL);
13005 		}
13006 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13007 			ASSERT(syn_present);
13008 			if (mctl_present) {
13009 				ASSERT(first_mp != mp);
13010 				first_mp->b_datap->db_struioflag |=
13011 				    STRUIO_POLICY;
13012 			} else {
13013 				ASSERT(first_mp == mp);
13014 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13015 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13016 			}
13017 		} else {
13018 			/*
13019 			 * Discard first_mp early since we're dealing with a
13020 			 * fully-connected conn_t and tcp doesn't do policy in
13021 			 * this case.
13022 			 */
13023 			if (mctl_present) {
13024 				freeb(first_mp);
13025 				mctl_present = B_FALSE;
13026 			}
13027 			first_mp = mp;
13028 		}
13029 	}
13030 
13031 	/* Initiate IPPF processing for fastpath */
13032 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13033 		uint32_t	ill_index;
13034 
13035 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13036 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13037 		if (mp == NULL) {
13038 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13039 			    "deferred/dropped during IPPF processing\n"));
13040 			CONN_DEC_REF(connp);
13041 			if (mctl_present)
13042 				freeb(first_mp);
13043 			return (NULL);
13044 		} else if (mctl_present) {
13045 			/*
13046 			 * ip_process might return a new mp.
13047 			 */
13048 			ASSERT(first_mp != mp);
13049 			first_mp->b_cont = mp;
13050 		} else {
13051 			first_mp = mp;
13052 		}
13053 
13054 	}
13055 
13056 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13057 		/*
13058 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13059 		 * make sure IPF_RECVIF is passed to ip_add_info.
13060 		 */
13061 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13062 		    IPCL_ZONEID(connp), ipst);
13063 		if (mp == NULL) {
13064 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13065 			CONN_DEC_REF(connp);
13066 			if (mctl_present)
13067 				freeb(first_mp);
13068 			return (NULL);
13069 		} else if (mctl_present) {
13070 			/*
13071 			 * ip_add_info might return a new mp.
13072 			 */
13073 			ASSERT(first_mp != mp);
13074 			first_mp->b_cont = mp;
13075 		} else {
13076 			first_mp = mp;
13077 		}
13078 	}
13079 
13080 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13081 	if (IPCL_IS_TCP(connp)) {
13082 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13083 		return (first_mp);
13084 	} else {
13085 		/* SOCK_RAW, IPPROTO_TCP case */
13086 		(connp->conn_recv)(connp, first_mp, NULL);
13087 		CONN_DEC_REF(connp);
13088 		return (NULL);
13089 	}
13090 
13091 no_conn:
13092 	/* Initiate IPPf processing, if needed. */
13093 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13094 		uint32_t ill_index;
13095 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13096 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13097 		if (first_mp == NULL) {
13098 			return (NULL);
13099 		}
13100 	}
13101 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13102 
13103 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13104 	    ipst->ips_netstack->netstack_tcp, NULL);
13105 	return (NULL);
13106 ipoptions:
13107 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13108 		goto slow_done;
13109 	}
13110 
13111 	UPDATE_IB_PKT_COUNT(ire);
13112 	ire->ire_last_used_time = lbolt;
13113 
13114 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13115 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13116 fragmented:
13117 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL)) {
13118 			if (mctl_present)
13119 				freeb(first_mp);
13120 			goto slow_done;
13121 		}
13122 		/*
13123 		 * Make sure that first_mp points back to mp as
13124 		 * the mp we came in with could have changed in
13125 		 * ip_rput_fragment().
13126 		 */
13127 		ASSERT(!mctl_present);
13128 		ipha = (ipha_t *)mp->b_rptr;
13129 		first_mp = mp;
13130 	}
13131 
13132 	/* Now we have a complete datagram, destined for this machine. */
13133 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13134 
13135 	len = mp->b_wptr - mp->b_rptr;
13136 	/* Pull up a minimal TCP header, if necessary. */
13137 	if (len < (u1 + 20)) {
13138 tcppullup:
13139 		if (!pullupmsg(mp, u1 + 20)) {
13140 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13141 			goto error;
13142 		}
13143 		ipha = (ipha_t *)mp->b_rptr;
13144 		len = mp->b_wptr - mp->b_rptr;
13145 	}
13146 
13147 	/*
13148 	 * Extract the offset field from the TCP header.  As usual, we
13149 	 * try to help the compiler more than the reader.
13150 	 */
13151 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13152 	if (offset != 5) {
13153 tcpoptions:
13154 		if (offset < 5) {
13155 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13156 			goto error;
13157 		}
13158 		/*
13159 		 * There must be TCP options.
13160 		 * Make sure we can grab them.
13161 		 */
13162 		offset <<= 2;
13163 		offset += u1;
13164 		if (len < offset) {
13165 			if (!pullupmsg(mp, offset)) {
13166 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13167 				goto error;
13168 			}
13169 			ipha = (ipha_t *)mp->b_rptr;
13170 			len = mp->b_wptr - rptr;
13171 		}
13172 	}
13173 
13174 	/* Get the total packet length in len, including headers. */
13175 	if (mp->b_cont) {
13176 multipkttcp:
13177 		len = msgdsize(mp);
13178 	}
13179 
13180 	/*
13181 	 * Check the TCP checksum by pulling together the pseudo-
13182 	 * header checksum, and passing it to ip_csum to be added in
13183 	 * with the TCP datagram.
13184 	 *
13185 	 * Since we are not using the hwcksum if available we must
13186 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13187 	 * If either of these fails along the way the mblk is freed.
13188 	 * If this logic ever changes and mblk is reused to say send
13189 	 * ICMP's back, then this flag may need to be cleared in
13190 	 * other places as well.
13191 	 */
13192 	DB_CKSUMFLAGS(mp) = 0;
13193 
13194 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13195 
13196 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13197 #ifdef	_BIG_ENDIAN
13198 	u1 += IPPROTO_TCP;
13199 #else
13200 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13201 #endif
13202 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13203 	/*
13204 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13205 	 */
13206 	IP_STAT(ipst, ip_in_sw_cksum);
13207 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13208 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13209 		goto error;
13210 	}
13211 
13212 	IP_STAT(ipst, ip_tcp_slow_path);
13213 	goto try_again;
13214 #undef  iphs
13215 #undef  rptr
13216 
13217 error:
13218 	freemsg(first_mp);
13219 slow_done:
13220 	return (NULL);
13221 }
13222 
13223 /* ARGSUSED */
13224 static void
13225 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13226     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13227 {
13228 	conn_t		*connp;
13229 	uint32_t	sum;
13230 	uint32_t	u1;
13231 	ssize_t		len;
13232 	sctp_hdr_t	*sctph;
13233 	zoneid_t	zoneid = ire->ire_zoneid;
13234 	uint32_t	pktsum;
13235 	uint32_t	calcsum;
13236 	uint32_t	ports;
13237 	in6_addr_t	map_src, map_dst;
13238 	ill_t		*ill = (ill_t *)q->q_ptr;
13239 	ip_stack_t	*ipst;
13240 	sctp_stack_t	*sctps;
13241 	boolean_t	sctp_csum_err = B_FALSE;
13242 
13243 	ASSERT(recv_ill != NULL);
13244 	ipst = recv_ill->ill_ipst;
13245 	sctps = ipst->ips_netstack->netstack_sctp;
13246 
13247 #define	rptr	((uchar_t *)ipha)
13248 
13249 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13250 	ASSERT(ill != NULL);
13251 
13252 	/* u1 is # words of IP options */
13253 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13254 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13255 
13256 	/* IP options present */
13257 	if (u1 > 0) {
13258 		goto ipoptions;
13259 	} else {
13260 		/* Check the IP header checksum.  */
13261 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill) &&
13262 		    !mctl_present) {
13263 #define	uph	((uint16_t *)ipha)
13264 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13265 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13266 #undef	uph
13267 			/* finish doing IP checksum */
13268 			sum = (sum & 0xFFFF) + (sum >> 16);
13269 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13270 			/*
13271 			 * Don't verify header checksum if this packet
13272 			 * is coming back from AH/ESP as we already did it.
13273 			 */
13274 			if (sum != 0 && sum != 0xFFFF) {
13275 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13276 				goto error;
13277 			}
13278 		}
13279 		/*
13280 		 * Since there is no SCTP h/w cksum support yet, just
13281 		 * clear the flag.
13282 		 */
13283 		DB_CKSUMFLAGS(mp) = 0;
13284 	}
13285 
13286 	/*
13287 	 * Don't verify header checksum if this packet is coming
13288 	 * back from AH/ESP as we already did it.
13289 	 */
13290 	if (!mctl_present) {
13291 		UPDATE_IB_PKT_COUNT(ire);
13292 		ire->ire_last_used_time = lbolt;
13293 	}
13294 
13295 	/* packet part of fragmented IP packet? */
13296 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13297 	if (u1 & (IPH_MF | IPH_OFFSET))
13298 		goto fragmented;
13299 
13300 	/* u1 = IP header length (20 bytes) */
13301 	u1 = IP_SIMPLE_HDR_LENGTH;
13302 
13303 find_sctp_client:
13304 	/* Pullup if we don't have the sctp common header. */
13305 	len = MBLKL(mp);
13306 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13307 		if (mp->b_cont == NULL ||
13308 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13309 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13310 			goto error;
13311 		}
13312 		ipha = (ipha_t *)mp->b_rptr;
13313 		len = MBLKL(mp);
13314 	}
13315 
13316 	sctph = (sctp_hdr_t *)(rptr + u1);
13317 #ifdef	DEBUG
13318 	if (!skip_sctp_cksum) {
13319 #endif
13320 		pktsum = sctph->sh_chksum;
13321 		sctph->sh_chksum = 0;
13322 		calcsum = sctp_cksum(mp, u1);
13323 		sctph->sh_chksum = pktsum;
13324 		if (calcsum != pktsum)
13325 			sctp_csum_err = B_TRUE;
13326 #ifdef	DEBUG	/* skip_sctp_cksum */
13327 	}
13328 #endif
13329 	/* get the ports */
13330 	ports = *(uint32_t *)&sctph->sh_sport;
13331 
13332 	IRE_REFRELE(ire);
13333 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13334 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13335 	if (sctp_csum_err) {
13336 		/*
13337 		 * No potential sctp checksum errors go to the Sun
13338 		 * sctp stack however they might be Adler-32 summed
13339 		 * packets a userland stack bound to a raw IP socket
13340 		 * could reasonably use. Note though that Adler-32 is
13341 		 * a long deprecated algorithm and customer sctp
13342 		 * networks should eventually migrate to CRC-32 at
13343 		 * which time this facility should be removed.
13344 		 */
13345 		flags |= IP_FF_SCTP_CSUM_ERR;
13346 		goto no_conn;
13347 	}
13348 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13349 	    sctps)) == NULL) {
13350 		/* Check for raw socket or OOTB handling */
13351 		goto no_conn;
13352 	}
13353 
13354 	/* Found a client; up it goes */
13355 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13356 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13357 	return;
13358 
13359 no_conn:
13360 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13361 	    ports, mctl_present, flags, B_TRUE, zoneid);
13362 	return;
13363 
13364 ipoptions:
13365 	DB_CKSUMFLAGS(mp) = 0;
13366 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13367 		goto slow_done;
13368 
13369 	UPDATE_IB_PKT_COUNT(ire);
13370 	ire->ire_last_used_time = lbolt;
13371 
13372 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13373 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13374 fragmented:
13375 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
13376 			goto slow_done;
13377 		/*
13378 		 * Make sure that first_mp points back to mp as
13379 		 * the mp we came in with could have changed in
13380 		 * ip_rput_fragment().
13381 		 */
13382 		ASSERT(!mctl_present);
13383 		ipha = (ipha_t *)mp->b_rptr;
13384 		first_mp = mp;
13385 	}
13386 
13387 	/* Now we have a complete datagram, destined for this machine. */
13388 	u1 = IPH_HDR_LENGTH(ipha);
13389 	goto find_sctp_client;
13390 #undef  iphs
13391 #undef  rptr
13392 
13393 error:
13394 	freemsg(first_mp);
13395 slow_done:
13396 	IRE_REFRELE(ire);
13397 }
13398 
13399 #define	VER_BITS	0xF0
13400 #define	VERSION_6	0x60
13401 
13402 static boolean_t
13403 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13404     ipaddr_t *dstp, ip_stack_t *ipst)
13405 {
13406 	uint_t	opt_len;
13407 	ipha_t *ipha;
13408 	ssize_t len;
13409 	uint_t	pkt_len;
13410 
13411 	ASSERT(ill != NULL);
13412 	IP_STAT(ipst, ip_ipoptions);
13413 	ipha = *iphapp;
13414 
13415 #define	rptr    ((uchar_t *)ipha)
13416 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13417 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13418 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13419 		freemsg(mp);
13420 		return (B_FALSE);
13421 	}
13422 
13423 	/* multiple mblk or too short */
13424 	pkt_len = ntohs(ipha->ipha_length);
13425 
13426 	/* Get the number of words of IP options in the IP header. */
13427 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13428 	if (opt_len) {
13429 		/* IP Options present!  Validate and process. */
13430 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13431 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13432 			goto done;
13433 		}
13434 		/*
13435 		 * Recompute complete header length and make sure we
13436 		 * have access to all of it.
13437 		 */
13438 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13439 		if (len > (mp->b_wptr - rptr)) {
13440 			if (len > pkt_len) {
13441 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13442 				goto done;
13443 			}
13444 			if (!pullupmsg(mp, len)) {
13445 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13446 				goto done;
13447 			}
13448 			ipha = (ipha_t *)mp->b_rptr;
13449 		}
13450 		/*
13451 		 * Go off to ip_rput_options which returns the next hop
13452 		 * destination address, which may have been affected
13453 		 * by source routing.
13454 		 */
13455 		IP_STAT(ipst, ip_opt);
13456 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13457 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13458 			return (B_FALSE);
13459 		}
13460 	}
13461 	*iphapp = ipha;
13462 	return (B_TRUE);
13463 done:
13464 	/* clear b_prev - used by ip_mroute_decap */
13465 	mp->b_prev = NULL;
13466 	freemsg(mp);
13467 	return (B_FALSE);
13468 #undef  rptr
13469 }
13470 
13471 /*
13472  * Deal with the fact that there is no ire for the destination.
13473  */
13474 static ire_t *
13475 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13476 {
13477 	ipha_t	*ipha;
13478 	ill_t	*ill;
13479 	ire_t	*ire;
13480 	ip_stack_t *ipst;
13481 	enum	ire_forward_action ret_action;
13482 
13483 	ipha = (ipha_t *)mp->b_rptr;
13484 	ill = (ill_t *)q->q_ptr;
13485 
13486 	ASSERT(ill != NULL);
13487 	ipst = ill->ill_ipst;
13488 
13489 	/*
13490 	 * No IRE for this destination, so it can't be for us.
13491 	 * Unless we are forwarding, drop the packet.
13492 	 * We have to let source routed packets through
13493 	 * since we don't yet know if they are 'ping -l'
13494 	 * packets i.e. if they will go out over the
13495 	 * same interface as they came in on.
13496 	 */
13497 	if (ll_multicast) {
13498 		freemsg(mp);
13499 		return (NULL);
13500 	}
13501 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13502 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13503 		freemsg(mp);
13504 		return (NULL);
13505 	}
13506 
13507 	/*
13508 	 * Mark this packet as having originated externally.
13509 	 *
13510 	 * For non-forwarding code path, ire_send later double
13511 	 * checks this interface to see if it is still exists
13512 	 * post-ARP resolution.
13513 	 *
13514 	 * Also, IPQOS uses this to differentiate between
13515 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13516 	 * QOS packet processing in ip_wput_attach_llhdr().
13517 	 * The QoS module can mark the b_band for a fastpath message
13518 	 * or the dl_priority field in a unitdata_req header for
13519 	 * CoS marking. This info can only be found in
13520 	 * ip_wput_attach_llhdr().
13521 	 */
13522 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13523 	/*
13524 	 * Clear the indication that this may have a hardware checksum
13525 	 * as we are not using it
13526 	 */
13527 	DB_CKSUMFLAGS(mp) = 0;
13528 
13529 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13530 	    msg_getlabel(mp), ipst);
13531 
13532 	if (ire == NULL && ret_action == Forward_check_multirt) {
13533 		/* Let ip_newroute handle CGTP  */
13534 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13535 		return (NULL);
13536 	}
13537 
13538 	if (ire != NULL)
13539 		return (ire);
13540 
13541 	mp->b_prev = mp->b_next = 0;
13542 
13543 	if (ret_action == Forward_blackhole) {
13544 		freemsg(mp);
13545 		return (NULL);
13546 	}
13547 	/* send icmp unreachable */
13548 	q = WR(q);
13549 	/* Sent by forwarding path, and router is global zone */
13550 	if (ip_source_routed(ipha, ipst)) {
13551 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13552 		    GLOBAL_ZONEID, ipst);
13553 	} else {
13554 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13555 		    ipst);
13556 	}
13557 
13558 	return (NULL);
13559 
13560 }
13561 
13562 /*
13563  * check ip header length and align it.
13564  */
13565 static boolean_t
13566 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13567 {
13568 	ssize_t len;
13569 	ill_t *ill;
13570 	ipha_t	*ipha;
13571 
13572 	len = MBLKL(mp);
13573 
13574 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13575 		ill = (ill_t *)q->q_ptr;
13576 
13577 		if (!OK_32PTR(mp->b_rptr))
13578 			IP_STAT(ipst, ip_notaligned1);
13579 		else
13580 			IP_STAT(ipst, ip_notaligned2);
13581 		/* Guard against bogus device drivers */
13582 		if (len < 0) {
13583 			/* clear b_prev - used by ip_mroute_decap */
13584 			mp->b_prev = NULL;
13585 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13586 			freemsg(mp);
13587 			return (B_FALSE);
13588 		}
13589 
13590 		if (ip_rput_pullups++ == 0) {
13591 			ipha = (ipha_t *)mp->b_rptr;
13592 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13593 			    "ip_check_and_align_header: %s forced us to "
13594 			    " pullup pkt, hdr len %ld, hdr addr %p",
13595 			    ill->ill_name, len, (void *)ipha);
13596 		}
13597 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13598 			/* clear b_prev - used by ip_mroute_decap */
13599 			mp->b_prev = NULL;
13600 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13601 			freemsg(mp);
13602 			return (B_FALSE);
13603 		}
13604 	}
13605 	return (B_TRUE);
13606 }
13607 
13608 /*
13609  * Handle the situation where a packet came in on `ill' but matched an IRE
13610  * whose ire_rfq doesn't match `ill'.  We return the IRE that should be used
13611  * for interface statistics.
13612  */
13613 ire_t *
13614 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13615 {
13616 	ire_t		*new_ire;
13617 	ill_t		*ire_ill;
13618 	uint_t		ifindex;
13619 	ip_stack_t	*ipst = ill->ill_ipst;
13620 	boolean_t	strict_check = B_FALSE;
13621 
13622 	/*
13623 	 * IPMP common case: if IRE and ILL are in the same group, there's no
13624 	 * issue (e.g. packet received on an underlying interface matched an
13625 	 * IRE_LOCAL on its associated group interface).
13626 	 */
13627 	if (ire->ire_rfq != NULL &&
13628 	    IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr)) {
13629 		return (ire);
13630 	}
13631 
13632 	/*
13633 	 * Do another ire lookup here, using the ingress ill, to see if the
13634 	 * interface is in a usesrc group.
13635 	 * As long as the ills belong to the same group, we don't consider
13636 	 * them to be arriving on the wrong interface. Thus, if the switch
13637 	 * is doing inbound load spreading, we won't drop packets when the
13638 	 * ip*_strict_dst_multihoming switch is on.
13639 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13640 	 * where the local address may not be unique. In this case we were
13641 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13642 	 * actually returned. The new lookup, which is more specific, should
13643 	 * only find the IRE_LOCAL associated with the ingress ill if one
13644 	 * exists.
13645 	 */
13646 
13647 	if (ire->ire_ipversion == IPV4_VERSION) {
13648 		if (ipst->ips_ip_strict_dst_multihoming)
13649 			strict_check = B_TRUE;
13650 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13651 		    ill->ill_ipif, ALL_ZONES, NULL,
13652 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13653 	} else {
13654 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13655 		if (ipst->ips_ipv6_strict_dst_multihoming)
13656 			strict_check = B_TRUE;
13657 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13658 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13659 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13660 	}
13661 	/*
13662 	 * If the same ire that was returned in ip_input() is found then this
13663 	 * is an indication that usesrc groups are in use. The packet
13664 	 * arrived on a different ill in the group than the one associated with
13665 	 * the destination address.  If a different ire was found then the same
13666 	 * IP address must be hosted on multiple ills. This is possible with
13667 	 * unnumbered point2point interfaces. We switch to use this new ire in
13668 	 * order to have accurate interface statistics.
13669 	 */
13670 	if (new_ire != NULL) {
13671 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13672 			ire_refrele(ire);
13673 			ire = new_ire;
13674 		} else {
13675 			ire_refrele(new_ire);
13676 		}
13677 		return (ire);
13678 	} else if ((ire->ire_rfq == NULL) &&
13679 	    (ire->ire_ipversion == IPV4_VERSION)) {
13680 		/*
13681 		 * The best match could have been the original ire which
13682 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13683 		 * the strict multihoming checks are irrelevant as we consider
13684 		 * local addresses hosted on lo0 to be interface agnostic. We
13685 		 * only expect a null ire_rfq on IREs which are associated with
13686 		 * lo0 hence we can return now.
13687 		 */
13688 		return (ire);
13689 	}
13690 
13691 	/*
13692 	 * Chase pointers once and store locally.
13693 	 */
13694 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13695 	    (ill_t *)(ire->ire_rfq->q_ptr);
13696 	ifindex = ill->ill_usesrc_ifindex;
13697 
13698 	/*
13699 	 * Check if it's a legal address on the 'usesrc' interface.
13700 	 */
13701 	if ((ifindex != 0) && (ire_ill != NULL) &&
13702 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13703 		return (ire);
13704 	}
13705 
13706 	/*
13707 	 * If the ip*_strict_dst_multihoming switch is on then we can
13708 	 * only accept this packet if the interface is marked as routing.
13709 	 */
13710 	if (!(strict_check))
13711 		return (ire);
13712 
13713 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13714 	    ILLF_ROUTER) != 0) {
13715 		return (ire);
13716 	}
13717 
13718 	ire_refrele(ire);
13719 	return (NULL);
13720 }
13721 
13722 /*
13723  *
13724  * This is the fast forward path. If we are here, we dont need to
13725  * worry about RSVP, CGTP, or TSol. Furthermore the ftable lookup
13726  * needed to find the nexthop in this case is much simpler
13727  */
13728 ire_t *
13729 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13730 {
13731 	ipha_t	*ipha;
13732 	ire_t	*src_ire;
13733 	ill_t	*stq_ill;
13734 	uint_t	hlen;
13735 	uint_t	pkt_len;
13736 	uint32_t sum;
13737 	queue_t	*dev_q;
13738 	ip_stack_t *ipst = ill->ill_ipst;
13739 	mblk_t *fpmp;
13740 	enum	ire_forward_action ret_action;
13741 
13742 	ipha = (ipha_t *)mp->b_rptr;
13743 
13744 	if (ire != NULL &&
13745 	    ire->ire_zoneid != GLOBAL_ZONEID &&
13746 	    ire->ire_zoneid != ALL_ZONES) {
13747 		/*
13748 		 * Should only use IREs that are visible to the global
13749 		 * zone for forwarding.
13750 		 */
13751 		ire_refrele(ire);
13752 		ire = ire_cache_lookup(dst, GLOBAL_ZONEID, NULL, ipst);
13753 		/*
13754 		 * ire_cache_lookup() can return ire of IRE_LOCAL in
13755 		 * transient cases. In such case, just drop the packet
13756 		 */
13757 		if (ire->ire_type != IRE_CACHE)
13758 			goto drop;
13759 	}
13760 
13761 	/*
13762 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13763 	 * The loopback address check for both src and dst has already
13764 	 * been checked in ip_input
13765 	 */
13766 
13767 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13768 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13769 		goto drop;
13770 	}
13771 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13772 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13773 
13774 	if (src_ire != NULL) {
13775 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13776 		ire_refrele(src_ire);
13777 		goto drop;
13778 	}
13779 
13780 	/* No ire cache of nexthop. So first create one  */
13781 	if (ire == NULL) {
13782 
13783 		ire = ire_forward_simple(dst, &ret_action, ipst);
13784 
13785 		/*
13786 		 * We only come to ip_fast_forward if ip_cgtp_filter
13787 		 * is not set. So ire_forward() should not return with
13788 		 * Forward_check_multirt as the next action.
13789 		 */
13790 		ASSERT(ret_action != Forward_check_multirt);
13791 		if (ire == NULL) {
13792 			/* An attempt was made to forward the packet */
13793 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13794 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13795 			mp->b_prev = mp->b_next = 0;
13796 			/* send icmp unreachable */
13797 			/* Sent by forwarding path, and router is global zone */
13798 			if (ret_action == Forward_ret_icmp_err) {
13799 				if (ip_source_routed(ipha, ipst)) {
13800 					icmp_unreachable(ill->ill_wq, mp,
13801 					    ICMP_SOURCE_ROUTE_FAILED,
13802 					    GLOBAL_ZONEID, ipst);
13803 				} else {
13804 					icmp_unreachable(ill->ill_wq, mp,
13805 					    ICMP_HOST_UNREACHABLE,
13806 					    GLOBAL_ZONEID, ipst);
13807 				}
13808 			} else {
13809 				freemsg(mp);
13810 			}
13811 			return (NULL);
13812 		}
13813 	}
13814 
13815 	/*
13816 	 * Forwarding fastpath exception case:
13817 	 * If any of the following are true, we take the slowpath:
13818 	 *	o forwarding is not enabled
13819 	 *	o incoming and outgoing interface are the same, or in the same
13820 	 *	  IPMP group.
13821 	 *	o corresponding ire is in incomplete state
13822 	 *	o packet needs fragmentation
13823 	 *	o ARP cache is not resolved
13824 	 *
13825 	 * The codeflow from here on is thus:
13826 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13827 	 */
13828 	pkt_len = ntohs(ipha->ipha_length);
13829 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13830 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13831 	    (ill == stq_ill) || IS_IN_SAME_ILLGRP(ill, stq_ill) ||
13832 	    (ire->ire_nce == NULL) ||
13833 	    (pkt_len > ire->ire_max_frag) ||
13834 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
13835 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
13836 	    ipha->ipha_ttl <= 1) {
13837 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13838 		    ipha, ill, B_FALSE, B_TRUE);
13839 		return (ire);
13840 	}
13841 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13842 
13843 	DTRACE_PROBE4(ip4__forwarding__start,
13844 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13845 
13846 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13847 	    ipst->ips_ipv4firewall_forwarding,
13848 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
13849 
13850 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13851 
13852 	if (mp == NULL)
13853 		goto drop;
13854 
13855 	mp->b_datap->db_struioun.cksum.flags = 0;
13856 	/* Adjust the checksum to reflect the ttl decrement. */
13857 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13858 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13859 	ipha->ipha_ttl--;
13860 
13861 	/*
13862 	 * Write the link layer header.  We can do this safely here,
13863 	 * because we have already tested to make sure that the IP
13864 	 * policy is not set, and that we have a fast path destination
13865 	 * header.
13866 	 */
13867 	mp->b_rptr -= hlen;
13868 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
13869 
13870 	UPDATE_IB_PKT_COUNT(ire);
13871 	ire->ire_last_used_time = lbolt;
13872 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
13873 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
13874 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
13875 
13876 	if (!ILL_DIRECT_CAPABLE(stq_ill) || DB_TYPE(mp) != M_DATA) {
13877 		dev_q = ire->ire_stq->q_next;
13878 		if (DEV_Q_FLOW_BLOCKED(dev_q))
13879 			goto indiscard;
13880 	}
13881 
13882 	DTRACE_PROBE4(ip4__physical__out__start,
13883 	    ill_t *, NULL, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13884 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
13885 	    ipst->ips_ipv4firewall_physical_out,
13886 	    NULL, stq_ill, ipha, mp, mp, 0, ipst);
13887 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
13888 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,
13889 	    ipha, __dtrace_ipsr_ill_t *, stq_ill, ipha_t *, ipha,
13890 	    ip6_t *, NULL, int, 0);
13891 
13892 	if (mp != NULL) {
13893 		if (ipst->ips_ipobs_enabled) {
13894 			zoneid_t szone;
13895 
13896 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
13897 			    ipst, ALL_ZONES);
13898 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
13899 			    ALL_ZONES, ill, IPV4_VERSION, hlen, ipst);
13900 		}
13901 
13902 		ILL_SEND_TX(stq_ill, ire, dst, mp, IP_DROP_ON_NO_DESC);
13903 	}
13904 	return (ire);
13905 
13906 indiscard:
13907 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13908 drop:
13909 	if (mp != NULL)
13910 		freemsg(mp);
13911 	return (ire);
13912 
13913 }
13914 
13915 /*
13916  * This function is called in the forwarding slowpath, when
13917  * either the ire lacks the link-layer address, or the packet needs
13918  * further processing(eg. fragmentation), before transmission.
13919  */
13920 
13921 static void
13922 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13923     ill_t *ill, boolean_t ll_multicast, boolean_t from_ip_fast_forward)
13924 {
13925 	queue_t		*dev_q;
13926 	ire_t		*src_ire;
13927 	ip_stack_t	*ipst = ill->ill_ipst;
13928 	boolean_t	same_illgrp = B_FALSE;
13929 
13930 	ASSERT(ire->ire_stq != NULL);
13931 
13932 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
13933 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
13934 
13935 	/*
13936 	 * If the caller of this function is ip_fast_forward() skip the
13937 	 * next three checks as it does not apply.
13938 	 */
13939 	if (from_ip_fast_forward)
13940 		goto skip;
13941 
13942 	if (ll_multicast != 0) {
13943 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13944 		goto drop_pkt;
13945 	}
13946 
13947 	/*
13948 	 * check if ipha_src is a broadcast address. Note that this
13949 	 * check is redundant when we get here from ip_fast_forward()
13950 	 * which has already done this check. However, since we can
13951 	 * also get here from ip_rput_process_broadcast() or, for
13952 	 * for the slow path through ip_fast_forward(), we perform
13953 	 * the check again for code-reusability
13954 	 */
13955 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13956 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13957 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
13958 		if (src_ire != NULL)
13959 			ire_refrele(src_ire);
13960 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13961 		ip2dbg(("ip_rput_process_forward: Received packet with"
13962 		    " bad src/dst address on %s\n", ill->ill_name));
13963 		goto drop_pkt;
13964 	}
13965 
13966 	/*
13967 	 * Check if we want to forward this one at this time.
13968 	 * We allow source routed packets on a host provided that
13969 	 * they go out the same ill or illgrp as they came in on.
13970 	 *
13971 	 * XXX To be quicker, we may wish to not chase pointers to
13972 	 * get the ILLF_ROUTER flag and instead store the
13973 	 * forwarding policy in the ire.  An unfortunate
13974 	 * side-effect of that would be requiring an ire flush
13975 	 * whenever the ILLF_ROUTER flag changes.
13976 	 */
13977 skip:
13978 	same_illgrp = IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr);
13979 
13980 	if (((ill->ill_flags &
13981 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags & ILLF_ROUTER) == 0) &&
13982 	    !(ip_source_routed(ipha, ipst) &&
13983 	    (ire->ire_rfq == q || same_illgrp))) {
13984 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13985 		if (ip_source_routed(ipha, ipst)) {
13986 			q = WR(q);
13987 			/*
13988 			 * Clear the indication that this may have
13989 			 * hardware checksum as we are not using it.
13990 			 */
13991 			DB_CKSUMFLAGS(mp) = 0;
13992 			/* Sent by forwarding path, and router is global zone */
13993 			icmp_unreachable(q, mp,
13994 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
13995 			return;
13996 		}
13997 		goto drop_pkt;
13998 	}
13999 
14000 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14001 
14002 	/* Packet is being forwarded. Turning off hwcksum flag. */
14003 	DB_CKSUMFLAGS(mp) = 0;
14004 	if (ipst->ips_ip_g_send_redirects) {
14005 		/*
14006 		 * Check whether the incoming interface and outgoing
14007 		 * interface is part of the same group. If so,
14008 		 * send redirects.
14009 		 *
14010 		 * Check the source address to see if it originated
14011 		 * on the same logical subnet it is going back out on.
14012 		 * If so, we should be able to send it a redirect.
14013 		 * Avoid sending a redirect if the destination
14014 		 * is directly connected (i.e., ipha_dst is the same
14015 		 * as ire_gateway_addr or the ire_addr of the
14016 		 * nexthop IRE_CACHE ), or if the packet was source
14017 		 * routed out this interface.
14018 		 */
14019 		ipaddr_t src, nhop;
14020 		mblk_t	*mp1;
14021 		ire_t	*nhop_ire = NULL;
14022 
14023 		/*
14024 		 * Check whether ire_rfq and q are from the same ill or illgrp.
14025 		 * If so, send redirects.
14026 		 */
14027 		if ((ire->ire_rfq == q || same_illgrp) &&
14028 		    !ip_source_routed(ipha, ipst)) {
14029 
14030 			nhop = (ire->ire_gateway_addr != 0 ?
14031 			    ire->ire_gateway_addr : ire->ire_addr);
14032 
14033 			if (ipha->ipha_dst == nhop) {
14034 				/*
14035 				 * We avoid sending a redirect if the
14036 				 * destination is directly connected
14037 				 * because it is possible that multiple
14038 				 * IP subnets may have been configured on
14039 				 * the link, and the source may not
14040 				 * be on the same subnet as ip destination,
14041 				 * even though they are on the same
14042 				 * physical link.
14043 				 */
14044 				goto sendit;
14045 			}
14046 
14047 			src = ipha->ipha_src;
14048 
14049 			/*
14050 			 * We look up the interface ire for the nexthop,
14051 			 * to see if ipha_src is in the same subnet
14052 			 * as the nexthop.
14053 			 *
14054 			 * Note that, if, in the future, IRE_CACHE entries
14055 			 * are obsoleted,  this lookup will not be needed,
14056 			 * as the ire passed to this function will be the
14057 			 * same as the nhop_ire computed below.
14058 			 */
14059 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14060 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14061 			    0, NULL, MATCH_IRE_TYPE, ipst);
14062 
14063 			if (nhop_ire != NULL) {
14064 				if ((src & nhop_ire->ire_mask) ==
14065 				    (nhop & nhop_ire->ire_mask)) {
14066 					/*
14067 					 * The source is directly connected.
14068 					 * Just copy the ip header (which is
14069 					 * in the first mblk)
14070 					 */
14071 					mp1 = copyb(mp);
14072 					if (mp1 != NULL) {
14073 						icmp_send_redirect(WR(q), mp1,
14074 						    nhop, ipst);
14075 					}
14076 				}
14077 				ire_refrele(nhop_ire);
14078 			}
14079 		}
14080 	}
14081 sendit:
14082 	dev_q = ire->ire_stq->q_next;
14083 	if (DEV_Q_FLOW_BLOCKED(dev_q)) {
14084 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14085 		freemsg(mp);
14086 		return;
14087 	}
14088 
14089 	ip_rput_forward(ire, ipha, mp, ill);
14090 	return;
14091 
14092 drop_pkt:
14093 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14094 	freemsg(mp);
14095 }
14096 
14097 ire_t *
14098 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14099     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14100 {
14101 	queue_t		*q;
14102 	uint16_t	hcksumflags;
14103 	ip_stack_t	*ipst = ill->ill_ipst;
14104 
14105 	q = *qp;
14106 
14107 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14108 
14109 	/*
14110 	 * Clear the indication that this may have hardware
14111 	 * checksum as we are not using it for forwarding.
14112 	 */
14113 	hcksumflags = DB_CKSUMFLAGS(mp);
14114 	DB_CKSUMFLAGS(mp) = 0;
14115 
14116 	/*
14117 	 * Directed broadcast forwarding: if the packet came in over a
14118 	 * different interface then it is routed out over we can forward it.
14119 	 */
14120 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14121 		ire_refrele(ire);
14122 		freemsg(mp);
14123 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14124 		return (NULL);
14125 	}
14126 	/*
14127 	 * For multicast we have set dst to be INADDR_BROADCAST
14128 	 * for delivering to all STREAMS.
14129 	 */
14130 	if (!CLASSD(ipha->ipha_dst)) {
14131 		ire_t *new_ire;
14132 		ipif_t *ipif;
14133 
14134 		ipif = ipif_get_next_ipif(NULL, ill);
14135 		if (ipif == NULL) {
14136 discard:		ire_refrele(ire);
14137 			freemsg(mp);
14138 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14139 			return (NULL);
14140 		}
14141 		new_ire = ire_ctable_lookup(dst, 0, 0,
14142 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14143 		ipif_refrele(ipif);
14144 
14145 		if (new_ire != NULL) {
14146 			/*
14147 			 * If the matching IRE_BROADCAST is part of an IPMP
14148 			 * group, then drop the packet unless our ill has been
14149 			 * nominated to receive for the group.
14150 			 */
14151 			if (IS_IPMP(new_ire->ire_ipif->ipif_ill) &&
14152 			    new_ire->ire_rfq != q) {
14153 				ire_refrele(new_ire);
14154 				goto discard;
14155 			}
14156 
14157 			/*
14158 			 * In the special case of multirouted broadcast
14159 			 * packets, we unconditionally need to "gateway"
14160 			 * them to the appropriate interface here.
14161 			 * In the normal case, this cannot happen, because
14162 			 * there is no broadcast IRE tagged with the
14163 			 * RTF_MULTIRT flag.
14164 			 */
14165 			if (new_ire->ire_flags & RTF_MULTIRT) {
14166 				ire_refrele(new_ire);
14167 				if (ire->ire_rfq != NULL) {
14168 					q = ire->ire_rfq;
14169 					*qp = q;
14170 				}
14171 			} else {
14172 				ire_refrele(ire);
14173 				ire = new_ire;
14174 			}
14175 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14176 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14177 				/*
14178 				 * Free the message if
14179 				 * ip_g_forward_directed_bcast is turned
14180 				 * off for non-local broadcast.
14181 				 */
14182 				ire_refrele(ire);
14183 				freemsg(mp);
14184 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14185 				return (NULL);
14186 			}
14187 		} else {
14188 			/*
14189 			 * This CGTP packet successfully passed the
14190 			 * CGTP filter, but the related CGTP
14191 			 * broadcast IRE has not been found,
14192 			 * meaning that the redundant ipif is
14193 			 * probably down. However, if we discarded
14194 			 * this packet, its duplicate would be
14195 			 * filtered out by the CGTP filter so none
14196 			 * of them would get through. So we keep
14197 			 * going with this one.
14198 			 */
14199 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14200 			if (ire->ire_rfq != NULL) {
14201 				q = ire->ire_rfq;
14202 				*qp = q;
14203 			}
14204 		}
14205 	}
14206 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14207 		/*
14208 		 * Verify that there are not more then one
14209 		 * IRE_BROADCAST with this broadcast address which
14210 		 * has ire_stq set.
14211 		 * TODO: simplify, loop over all IRE's
14212 		 */
14213 		ire_t	*ire1;
14214 		int	num_stq = 0;
14215 		mblk_t	*mp1;
14216 
14217 		/* Find the first one with ire_stq set */
14218 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14219 		for (ire1 = ire; ire1 &&
14220 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14221 		    ire1 = ire1->ire_next)
14222 			;
14223 		if (ire1) {
14224 			ire_refrele(ire);
14225 			ire = ire1;
14226 			IRE_REFHOLD(ire);
14227 		}
14228 
14229 		/* Check if there are additional ones with stq set */
14230 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14231 			if (ire->ire_addr != ire1->ire_addr)
14232 				break;
14233 			if (ire1->ire_stq) {
14234 				num_stq++;
14235 				break;
14236 			}
14237 		}
14238 		rw_exit(&ire->ire_bucket->irb_lock);
14239 		if (num_stq == 1 && ire->ire_stq != NULL) {
14240 			ip1dbg(("ip_rput_process_broadcast: directed "
14241 			    "broadcast to 0x%x\n",
14242 			    ntohl(ire->ire_addr)));
14243 			mp1 = copymsg(mp);
14244 			if (mp1) {
14245 				switch (ipha->ipha_protocol) {
14246 				case IPPROTO_UDP:
14247 					ip_udp_input(q, mp1, ipha, ire, ill);
14248 					break;
14249 				default:
14250 					ip_proto_input(q, mp1, ipha, ire, ill,
14251 					    0);
14252 					break;
14253 				}
14254 			}
14255 			/*
14256 			 * Adjust ttl to 2 (1+1 - the forward engine
14257 			 * will decrement it by one.
14258 			 */
14259 			if (ip_csum_hdr(ipha)) {
14260 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14261 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14262 				freemsg(mp);
14263 				ire_refrele(ire);
14264 				return (NULL);
14265 			}
14266 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14267 			ipha->ipha_hdr_checksum = 0;
14268 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14269 			ip_rput_process_forward(q, mp, ire, ipha,
14270 			    ill, ll_multicast, B_FALSE);
14271 			ire_refrele(ire);
14272 			return (NULL);
14273 		}
14274 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14275 		    ntohl(ire->ire_addr)));
14276 	}
14277 
14278 	/* Restore any hardware checksum flags */
14279 	DB_CKSUMFLAGS(mp) = hcksumflags;
14280 	return (ire);
14281 }
14282 
14283 /* ARGSUSED */
14284 static boolean_t
14285 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14286     int *ll_multicast, ipaddr_t *dstp)
14287 {
14288 	ip_stack_t	*ipst = ill->ill_ipst;
14289 
14290 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14291 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14292 	    ntohs(ipha->ipha_length));
14293 
14294 	/*
14295 	 * So that we don't end up with dups, only one ill in an IPMP group is
14296 	 * nominated to receive multicast traffic.
14297 	 */
14298 	if (IS_UNDER_IPMP(ill) && !ill->ill_nom_cast)
14299 		goto drop_pkt;
14300 
14301 	/*
14302 	 * Forward packets only if we have joined the allmulti
14303 	 * group on this interface.
14304 	 */
14305 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14306 		int retval;
14307 
14308 		/*
14309 		 * Clear the indication that this may have hardware
14310 		 * checksum as we are not using it.
14311 		 */
14312 		DB_CKSUMFLAGS(mp) = 0;
14313 		retval = ip_mforward(ill, ipha, mp);
14314 		/* ip_mforward updates mib variables if needed */
14315 		/* clear b_prev - used by ip_mroute_decap */
14316 		mp->b_prev = NULL;
14317 
14318 		switch (retval) {
14319 		case 0:
14320 			/*
14321 			 * pkt is okay and arrived on phyint.
14322 			 *
14323 			 * If we are running as a multicast router
14324 			 * we need to see all IGMP and/or PIM packets.
14325 			 */
14326 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14327 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14328 				goto done;
14329 			}
14330 			break;
14331 		case -1:
14332 			/* pkt is mal-formed, toss it */
14333 			goto drop_pkt;
14334 		case 1:
14335 			/* pkt is okay and arrived on a tunnel */
14336 			/*
14337 			 * If we are running a multicast router
14338 			 *  we need to see all igmp packets.
14339 			 */
14340 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14341 				*dstp = INADDR_BROADCAST;
14342 				*ll_multicast = 1;
14343 				return (B_FALSE);
14344 			}
14345 
14346 			goto drop_pkt;
14347 		}
14348 	}
14349 
14350 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14351 		/*
14352 		 * This might just be caused by the fact that
14353 		 * multiple IP Multicast addresses map to the same
14354 		 * link layer multicast - no need to increment counter!
14355 		 */
14356 		freemsg(mp);
14357 		return (B_TRUE);
14358 	}
14359 done:
14360 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14361 	/*
14362 	 * This assumes the we deliver to all streams for multicast
14363 	 * and broadcast packets.
14364 	 */
14365 	*dstp = INADDR_BROADCAST;
14366 	*ll_multicast = 1;
14367 	return (B_FALSE);
14368 drop_pkt:
14369 	ip2dbg(("ip_rput: drop pkt\n"));
14370 	freemsg(mp);
14371 	return (B_TRUE);
14372 }
14373 
14374 /*
14375  * This function is used to both return an indication of whether or not
14376  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14377  * and in doing so, determine whether or not it is broadcast vs multicast.
14378  * For it to be a broadcast packet, we must have the appropriate mblk_t
14379  * hanging off the ill_t.  If this is either not present or doesn't match
14380  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14381  * to be multicast.  Thus NICs that have no broadcast address (or no
14382  * capability for one, such as point to point links) cannot return as
14383  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14384  * the return values simplifies the current use of the return value of this
14385  * function, which is to pass through the multicast/broadcast characteristic
14386  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14387  * changing the return value to some other symbol demands the appropriate
14388  * "translation" when hpe_flags is set prior to calling hook_run() for
14389  * packet events.
14390  */
14391 int
14392 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14393 {
14394 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14395 	mblk_t *bmp;
14396 
14397 	if (ind->dl_group_address) {
14398 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14399 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14400 		    MBLKL(mb) &&
14401 		    (bmp = ill->ill_bcast_mp) != NULL) {
14402 			dl_unitdata_req_t *dlur;
14403 			uint8_t *bphys_addr;
14404 
14405 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14406 			if (ill->ill_sap_length < 0)
14407 				bphys_addr = (uchar_t *)dlur +
14408 				    dlur->dl_dest_addr_offset;
14409 			else
14410 				bphys_addr = (uchar_t *)dlur +
14411 				    dlur->dl_dest_addr_offset +
14412 				    ill->ill_sap_length;
14413 
14414 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14415 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14416 				return (HPE_BROADCAST);
14417 			}
14418 			return (HPE_MULTICAST);
14419 		}
14420 		return (HPE_MULTICAST);
14421 	}
14422 	return (0);
14423 }
14424 
14425 static boolean_t
14426 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14427     int *ll_multicast, mblk_t **mpp)
14428 {
14429 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14430 	boolean_t must_copy = B_FALSE;
14431 	struct iocblk   *iocp;
14432 	ipha_t		*ipha;
14433 	ip_stack_t	*ipst = ill->ill_ipst;
14434 
14435 #define	rptr    ((uchar_t *)ipha)
14436 
14437 	first_mp = *first_mpp;
14438 	mp = *mpp;
14439 
14440 	ASSERT(first_mp == mp);
14441 
14442 	/*
14443 	 * if db_ref > 1 then copymsg and free original. Packet may be
14444 	 * changed and do not want other entity who has a reference to this
14445 	 * message to trip over the changes. This is a blind change because
14446 	 * trying to catch all places that might change packet is too
14447 	 * difficult (since it may be a module above this one)
14448 	 *
14449 	 * This corresponds to the non-fast path case. We walk down the full
14450 	 * chain in this case, and check the db_ref count of all the dblks,
14451 	 * and do a copymsg if required. It is possible that the db_ref counts
14452 	 * of the data blocks in the mblk chain can be different.
14453 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14454 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14455 	 * 'snoop' is running.
14456 	 */
14457 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14458 		if (mp1->b_datap->db_ref > 1) {
14459 			must_copy = B_TRUE;
14460 			break;
14461 		}
14462 	}
14463 
14464 	if (must_copy) {
14465 		mp1 = copymsg(mp);
14466 		if (mp1 == NULL) {
14467 			for (mp1 = mp; mp1 != NULL;
14468 			    mp1 = mp1->b_cont) {
14469 				mp1->b_next = NULL;
14470 				mp1->b_prev = NULL;
14471 			}
14472 			freemsg(mp);
14473 			if (ill != NULL) {
14474 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14475 			} else {
14476 				BUMP_MIB(&ipst->ips_ip_mib,
14477 				    ipIfStatsInDiscards);
14478 			}
14479 			return (B_TRUE);
14480 		}
14481 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14482 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14483 			/* Copy b_prev - used by ip_mroute_decap */
14484 			to_mp->b_prev = from_mp->b_prev;
14485 			from_mp->b_prev = NULL;
14486 		}
14487 		*first_mpp = first_mp = mp1;
14488 		freemsg(mp);
14489 		mp = mp1;
14490 		*mpp = mp1;
14491 	}
14492 
14493 	ipha = (ipha_t *)mp->b_rptr;
14494 
14495 	/*
14496 	 * previous code has a case for M_DATA.
14497 	 * We want to check how that happens.
14498 	 */
14499 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14500 	switch (first_mp->b_datap->db_type) {
14501 	case M_PROTO:
14502 	case M_PCPROTO:
14503 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14504 		    DL_UNITDATA_IND) {
14505 			/* Go handle anything other than data elsewhere. */
14506 			ip_rput_dlpi(q, mp);
14507 			return (B_TRUE);
14508 		}
14509 
14510 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14511 		/* Ditch the DLPI header. */
14512 		mp1 = mp->b_cont;
14513 		ASSERT(first_mp == mp);
14514 		*first_mpp = mp1;
14515 		freeb(mp);
14516 		*mpp = mp1;
14517 		return (B_FALSE);
14518 	case M_IOCACK:
14519 		ip1dbg(("got iocack "));
14520 		iocp = (struct iocblk *)mp->b_rptr;
14521 		switch (iocp->ioc_cmd) {
14522 		case DL_IOC_HDR_INFO:
14523 			ill = (ill_t *)q->q_ptr;
14524 			ill_fastpath_ack(ill, mp);
14525 			return (B_TRUE);
14526 		case SIOCSTUNPARAM:
14527 		case OSIOCSTUNPARAM:
14528 			/* Go through qwriter_ip */
14529 			break;
14530 		case SIOCGTUNPARAM:
14531 		case OSIOCGTUNPARAM:
14532 			ip_rput_other(NULL, q, mp, NULL);
14533 			return (B_TRUE);
14534 		default:
14535 			putnext(q, mp);
14536 			return (B_TRUE);
14537 		}
14538 		/* FALLTHRU */
14539 	case M_ERROR:
14540 	case M_HANGUP:
14541 		/*
14542 		 * Since this is on the ill stream we unconditionally
14543 		 * bump up the refcount
14544 		 */
14545 		ill_refhold(ill);
14546 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14547 		return (B_TRUE);
14548 	case M_CTL:
14549 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14550 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14551 		    IPHADA_M_CTL)) {
14552 			/*
14553 			 * It's an IPsec accelerated packet.
14554 			 * Make sure that the ill from which we received the
14555 			 * packet has enabled IPsec hardware acceleration.
14556 			 */
14557 			if (!(ill->ill_capabilities &
14558 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14559 				/* IPsec kstats: bean counter */
14560 				freemsg(mp);
14561 				return (B_TRUE);
14562 			}
14563 
14564 			/*
14565 			 * Make mp point to the mblk following the M_CTL,
14566 			 * then process according to type of mp.
14567 			 * After this processing, first_mp will point to
14568 			 * the data-attributes and mp to the pkt following
14569 			 * the M_CTL.
14570 			 */
14571 			mp = first_mp->b_cont;
14572 			if (mp == NULL) {
14573 				freemsg(first_mp);
14574 				return (B_TRUE);
14575 			}
14576 			/*
14577 			 * A Hardware Accelerated packet can only be M_DATA
14578 			 * ESP or AH packet.
14579 			 */
14580 			if (mp->b_datap->db_type != M_DATA) {
14581 				/* non-M_DATA IPsec accelerated packet */
14582 				IPSECHW_DEBUG(IPSECHW_PKT,
14583 				    ("non-M_DATA IPsec accelerated pkt\n"));
14584 				freemsg(first_mp);
14585 				return (B_TRUE);
14586 			}
14587 			ipha = (ipha_t *)mp->b_rptr;
14588 			if (ipha->ipha_protocol != IPPROTO_AH &&
14589 			    ipha->ipha_protocol != IPPROTO_ESP) {
14590 				IPSECHW_DEBUG(IPSECHW_PKT,
14591 				    ("non-M_DATA IPsec accelerated pkt\n"));
14592 				freemsg(first_mp);
14593 				return (B_TRUE);
14594 			}
14595 			*mpp = mp;
14596 			return (B_FALSE);
14597 		}
14598 		putnext(q, mp);
14599 		return (B_TRUE);
14600 	case M_IOCNAK:
14601 		ip1dbg(("got iocnak "));
14602 		iocp = (struct iocblk *)mp->b_rptr;
14603 		switch (iocp->ioc_cmd) {
14604 		case SIOCSTUNPARAM:
14605 		case OSIOCSTUNPARAM:
14606 			/*
14607 			 * Since this is on the ill stream we unconditionally
14608 			 * bump up the refcount
14609 			 */
14610 			ill_refhold(ill);
14611 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14612 			return (B_TRUE);
14613 		case DL_IOC_HDR_INFO:
14614 		case SIOCGTUNPARAM:
14615 		case OSIOCGTUNPARAM:
14616 			ip_rput_other(NULL, q, mp, NULL);
14617 			return (B_TRUE);
14618 		default:
14619 			break;
14620 		}
14621 		/* FALLTHRU */
14622 	default:
14623 		putnext(q, mp);
14624 		return (B_TRUE);
14625 	}
14626 }
14627 
14628 /* Read side put procedure.  Packets coming from the wire arrive here. */
14629 void
14630 ip_rput(queue_t *q, mblk_t *mp)
14631 {
14632 	ill_t	*ill;
14633 	union DL_primitives *dl;
14634 
14635 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14636 
14637 	ill = (ill_t *)q->q_ptr;
14638 
14639 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14640 		/*
14641 		 * If things are opening or closing, only accept high-priority
14642 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14643 		 * created; on close, things hanging off the ill may have been
14644 		 * freed already.)
14645 		 */
14646 		dl = (union DL_primitives *)mp->b_rptr;
14647 		if (DB_TYPE(mp) != M_PCPROTO ||
14648 		    dl->dl_primitive == DL_UNITDATA_IND) {
14649 			/*
14650 			 * SIOC[GS]TUNPARAM ioctls can come here.
14651 			 */
14652 			inet_freemsg(mp);
14653 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14654 			    "ip_rput_end: q %p (%S)", q, "uninit");
14655 			return;
14656 		}
14657 	}
14658 
14659 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14660 	    "ip_rput_end: q %p (%S)", q, "end");
14661 
14662 	ip_input(ill, NULL, mp, NULL);
14663 }
14664 
14665 static mblk_t *
14666 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14667 {
14668 	mblk_t *mp1;
14669 	boolean_t adjusted = B_FALSE;
14670 	ip_stack_t *ipst = ill->ill_ipst;
14671 
14672 	IP_STAT(ipst, ip_db_ref);
14673 	/*
14674 	 * The IP_RECVSLLA option depends on having the
14675 	 * link layer header. First check that:
14676 	 * a> the underlying device is of type ether,
14677 	 * since this option is currently supported only
14678 	 * over ethernet.
14679 	 * b> there is enough room to copy over the link
14680 	 * layer header.
14681 	 *
14682 	 * Once the checks are done, adjust rptr so that
14683 	 * the link layer header will be copied via
14684 	 * copymsg. Note that, IFT_ETHER may be returned
14685 	 * by some non-ethernet drivers but in this case
14686 	 * the second check will fail.
14687 	 */
14688 	if (ill->ill_type == IFT_ETHER &&
14689 	    (mp->b_rptr - mp->b_datap->db_base) >=
14690 	    sizeof (struct ether_header)) {
14691 		mp->b_rptr -= sizeof (struct ether_header);
14692 		adjusted = B_TRUE;
14693 	}
14694 	mp1 = copymsg(mp);
14695 
14696 	if (mp1 == NULL) {
14697 		mp->b_next = NULL;
14698 		/* clear b_prev - used by ip_mroute_decap */
14699 		mp->b_prev = NULL;
14700 		freemsg(mp);
14701 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14702 		return (NULL);
14703 	}
14704 
14705 	if (adjusted) {
14706 		/*
14707 		 * Copy is done. Restore the pointer in
14708 		 * the _new_ mblk
14709 		 */
14710 		mp1->b_rptr += sizeof (struct ether_header);
14711 	}
14712 
14713 	/* Copy b_prev - used by ip_mroute_decap */
14714 	mp1->b_prev = mp->b_prev;
14715 	mp->b_prev = NULL;
14716 
14717 	/* preserve the hardware checksum flags and data, if present */
14718 	if (DB_CKSUMFLAGS(mp) != 0) {
14719 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14720 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14721 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14722 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14723 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14724 	}
14725 
14726 	freemsg(mp);
14727 	return (mp1);
14728 }
14729 
14730 #define	ADD_TO_CHAIN(head, tail, cnt, mp) {    			\
14731 	if (tail != NULL)					\
14732 		tail->b_next = mp;				\
14733 	else							\
14734 		head = mp;					\
14735 	tail = mp;						\
14736 	cnt++;							\
14737 }
14738 
14739 /*
14740  * Direct read side procedure capable of dealing with chains. GLDv3 based
14741  * drivers call this function directly with mblk chains while STREAMS
14742  * read side procedure ip_rput() calls this for single packet with ip_ring
14743  * set to NULL to process one packet at a time.
14744  *
14745  * The ill will always be valid if this function is called directly from
14746  * the driver.
14747  *
14748  * If ip_input() is called from GLDv3:
14749  *
14750  *   - This must be a non-VLAN IP stream.
14751  *   - 'mp' is either an untagged or a special priority-tagged packet.
14752  *   - Any VLAN tag that was in the MAC header has been stripped.
14753  *
14754  * If the IP header in packet is not 32-bit aligned, every message in the
14755  * chain will be aligned before further operations. This is required on SPARC
14756  * platform.
14757  */
14758 /* ARGSUSED */
14759 void
14760 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14761     struct mac_header_info_s *mhip)
14762 {
14763 	ipaddr_t		dst = NULL;
14764 	ipaddr_t		prev_dst;
14765 	ire_t			*ire = NULL;
14766 	ipha_t			*ipha;
14767 	uint_t			pkt_len;
14768 	ssize_t			len;
14769 	uint_t			opt_len;
14770 	int			ll_multicast;
14771 	int			cgtp_flt_pkt;
14772 	queue_t			*q = ill->ill_rq;
14773 	squeue_t		*curr_sqp = NULL;
14774 	mblk_t 			*head = NULL;
14775 	mblk_t			*tail = NULL;
14776 	mblk_t			*first_mp;
14777 	int			cnt = 0;
14778 	ip_stack_t		*ipst = ill->ill_ipst;
14779 	mblk_t			*mp;
14780 	mblk_t			*dmp;
14781 	uint8_t			tag;
14782 
14783 	ASSERT(mp_chain != NULL);
14784 	ASSERT(ill != NULL);
14785 
14786 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14787 
14788 	tag = (ip_ring != NULL) ? SQTAG_IP_INPUT_RX_RING : SQTAG_IP_INPUT;
14789 
14790 #define	rptr	((uchar_t *)ipha)
14791 
14792 	while (mp_chain != NULL) {
14793 		mp = mp_chain;
14794 		mp_chain = mp_chain->b_next;
14795 		mp->b_next = NULL;
14796 		ll_multicast = 0;
14797 
14798 		/*
14799 		 * We do ire caching from one iteration to
14800 		 * another. In the event the packet chain contains
14801 		 * all packets from the same dst, this caching saves
14802 		 * an ire_cache_lookup for each of the succeeding
14803 		 * packets in a packet chain.
14804 		 */
14805 		prev_dst = dst;
14806 
14807 		/*
14808 		 * if db_ref > 1 then copymsg and free original. Packet
14809 		 * may be changed and we do not want the other entity
14810 		 * who has a reference to this message to trip over the
14811 		 * changes. This is a blind change because trying to
14812 		 * catch all places that might change the packet is too
14813 		 * difficult.
14814 		 *
14815 		 * This corresponds to the fast path case, where we have
14816 		 * a chain of M_DATA mblks.  We check the db_ref count
14817 		 * of only the 1st data block in the mblk chain. There
14818 		 * doesn't seem to be a reason why a device driver would
14819 		 * send up data with varying db_ref counts in the mblk
14820 		 * chain. In any case the Fast path is a private
14821 		 * interface, and our drivers don't do such a thing.
14822 		 * Given the above assumption, there is no need to walk
14823 		 * down the entire mblk chain (which could have a
14824 		 * potential performance problem)
14825 		 *
14826 		 * The "(DB_REF(mp) > 1)" check was moved from ip_rput()
14827 		 * to here because of exclusive ip stacks and vnics.
14828 		 * Packets transmitted from exclusive stack over vnic
14829 		 * can have db_ref > 1 and when it gets looped back to
14830 		 * another vnic in a different zone, you have ip_input()
14831 		 * getting dblks with db_ref > 1. So if someone
14832 		 * complains of TCP performance under this scenario,
14833 		 * take a serious look here on the impact of copymsg().
14834 		 */
14835 
14836 		if (DB_REF(mp) > 1) {
14837 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14838 				continue;
14839 		}
14840 
14841 		/*
14842 		 * Check and align the IP header.
14843 		 */
14844 		first_mp = mp;
14845 		if (DB_TYPE(mp) == M_DATA) {
14846 			dmp = mp;
14847 		} else if (DB_TYPE(mp) == M_PROTO &&
14848 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14849 			dmp = mp->b_cont;
14850 		} else {
14851 			dmp = NULL;
14852 		}
14853 		if (dmp != NULL) {
14854 			/*
14855 			 * IP header ptr not aligned?
14856 			 * OR IP header not complete in first mblk
14857 			 */
14858 			if (!OK_32PTR(dmp->b_rptr) ||
14859 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14860 				if (!ip_check_and_align_header(q, dmp, ipst))
14861 					continue;
14862 			}
14863 		}
14864 
14865 		/*
14866 		 * ip_input fast path
14867 		 */
14868 
14869 		/* mblk type is not M_DATA */
14870 		if (DB_TYPE(mp) != M_DATA) {
14871 			if (ip_rput_process_notdata(q, &first_mp, ill,
14872 			    &ll_multicast, &mp))
14873 				continue;
14874 
14875 			/*
14876 			 * The only way we can get here is if we had a
14877 			 * packet that was either a DL_UNITDATA_IND or
14878 			 * an M_CTL for an IPsec accelerated packet.
14879 			 *
14880 			 * In either case, the first_mp will point to
14881 			 * the leading M_PROTO or M_CTL.
14882 			 */
14883 			ASSERT(first_mp != NULL);
14884 		} else if (mhip != NULL) {
14885 			/*
14886 			 * ll_multicast is set here so that it is ready
14887 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
14888 			 * manipulates ll_multicast in the same fashion when
14889 			 * called from ip_rput_process_notdata.
14890 			 */
14891 			switch (mhip->mhi_dsttype) {
14892 			case MAC_ADDRTYPE_MULTICAST :
14893 				ll_multicast = HPE_MULTICAST;
14894 				break;
14895 			case MAC_ADDRTYPE_BROADCAST :
14896 				ll_multicast = HPE_BROADCAST;
14897 				break;
14898 			default :
14899 				break;
14900 			}
14901 		}
14902 
14903 		/* Only M_DATA can come here and it is always aligned */
14904 		ASSERT(DB_TYPE(mp) == M_DATA);
14905 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
14906 
14907 		ipha = (ipha_t *)mp->b_rptr;
14908 		len = mp->b_wptr - rptr;
14909 		pkt_len = ntohs(ipha->ipha_length);
14910 
14911 		/*
14912 		 * We must count all incoming packets, even if they end
14913 		 * up being dropped later on.
14914 		 */
14915 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
14916 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
14917 
14918 		/* multiple mblk or too short */
14919 		len -= pkt_len;
14920 		if (len != 0) {
14921 			/*
14922 			 * Make sure we have data length consistent
14923 			 * with the IP header.
14924 			 */
14925 			if (mp->b_cont == NULL) {
14926 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14927 					BUMP_MIB(ill->ill_ip_mib,
14928 					    ipIfStatsInHdrErrors);
14929 					ip2dbg(("ip_input: drop pkt\n"));
14930 					freemsg(mp);
14931 					continue;
14932 				}
14933 				mp->b_wptr = rptr + pkt_len;
14934 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
14935 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14936 					BUMP_MIB(ill->ill_ip_mib,
14937 					    ipIfStatsInHdrErrors);
14938 					ip2dbg(("ip_input: drop pkt\n"));
14939 					freemsg(mp);
14940 					continue;
14941 				}
14942 				(void) adjmsg(mp, -len);
14943 				IP_STAT(ipst, ip_multimblk3);
14944 			}
14945 		}
14946 
14947 		/* Obtain the dst of the current packet */
14948 		dst = ipha->ipha_dst;
14949 
14950 		DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL,
14951 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *,
14952 		    ipha, ip6_t *, NULL, int, 0);
14953 
14954 		/*
14955 		 * The following test for loopback is faster than
14956 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
14957 		 * operations.
14958 		 * Note that these addresses are always in network byte order
14959 		 */
14960 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
14961 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
14962 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
14963 			freemsg(mp);
14964 			continue;
14965 		}
14966 
14967 		/*
14968 		 * The event for packets being received from a 'physical'
14969 		 * interface is placed after validation of the source and/or
14970 		 * destination address as being local so that packets can be
14971 		 * redirected to loopback addresses using ipnat.
14972 		 */
14973 		DTRACE_PROBE4(ip4__physical__in__start,
14974 		    ill_t *, ill, ill_t *, NULL,
14975 		    ipha_t *, ipha, mblk_t *, first_mp);
14976 
14977 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
14978 		    ipst->ips_ipv4firewall_physical_in,
14979 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
14980 
14981 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
14982 
14983 		if (first_mp == NULL) {
14984 			continue;
14985 		}
14986 		dst = ipha->ipha_dst;
14987 		/*
14988 		 * Attach any necessary label information to
14989 		 * this packet
14990 		 */
14991 		if (is_system_labeled() &&
14992 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
14993 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14994 			freemsg(mp);
14995 			continue;
14996 		}
14997 
14998 		if (ipst->ips_ipobs_enabled) {
14999 			zoneid_t dzone;
15000 
15001 			/*
15002 			 * On the inbound path the src zone will be unknown as
15003 			 * this packet has come from the wire.
15004 			 */
15005 			dzone = ip_get_zoneid_v4(dst, mp, ipst, ALL_ZONES);
15006 			ipobs_hook(mp, IPOBS_HOOK_INBOUND, ALL_ZONES, dzone,
15007 			    ill, IPV4_VERSION, 0, ipst);
15008 		}
15009 
15010 		/*
15011 		 * Reuse the cached ire only if the ipha_dst of the previous
15012 		 * packet is the same as the current packet AND it is not
15013 		 * INADDR_ANY.
15014 		 */
15015 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15016 		    (ire != NULL)) {
15017 			ire_refrele(ire);
15018 			ire = NULL;
15019 		}
15020 
15021 		opt_len = ipha->ipha_version_and_hdr_length -
15022 		    IP_SIMPLE_HDR_VERSION;
15023 
15024 		/*
15025 		 * Check to see if we can take the fastpath.
15026 		 * That is possible if the following conditions are met
15027 		 *	o Tsol disabled
15028 		 *	o CGTP disabled
15029 		 *	o ipp_action_count is 0
15030 		 *	o no options in the packet
15031 		 *	o not a RSVP packet
15032 		 * 	o not a multicast packet
15033 		 *	o ill not in IP_DHCPINIT_IF mode
15034 		 */
15035 		if (!is_system_labeled() &&
15036 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15037 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15038 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15039 			if (ire == NULL)
15040 				ire = ire_cache_lookup_simple(dst, ipst);
15041 			/*
15042 			 * Unless forwarding is enabled, dont call
15043 			 * ip_fast_forward(). Incoming packet is for forwarding
15044 			 */
15045 			if ((ill->ill_flags & ILLF_ROUTER) &&
15046 			    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15047 				ire = ip_fast_forward(ire, dst, ill, mp);
15048 				continue;
15049 			}
15050 			/* incoming packet is for local consumption */
15051 			if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15052 				goto local;
15053 		}
15054 
15055 		/*
15056 		 * Disable ire caching for anything more complex
15057 		 * than the simple fast path case we checked for above.
15058 		 */
15059 		if (ire != NULL) {
15060 			ire_refrele(ire);
15061 			ire = NULL;
15062 		}
15063 
15064 		/*
15065 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15066 		 * server to unicast DHCP packets to a DHCP client using the
15067 		 * IP address it is offering to the client.  This can be
15068 		 * disabled through the "broadcast bit", but not all DHCP
15069 		 * servers honor that bit.  Therefore, to interoperate with as
15070 		 * many DHCP servers as possible, the DHCP client allows the
15071 		 * server to unicast, but we treat those packets as broadcast
15072 		 * here.  Note that we don't rewrite the packet itself since
15073 		 * (a) that would mess up the checksums and (b) the DHCP
15074 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15075 		 * hand it the packet regardless.
15076 		 */
15077 		if (ill->ill_dhcpinit != 0 &&
15078 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15079 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15080 			udpha_t *udpha;
15081 
15082 			/*
15083 			 * Reload ipha since pullupmsg() can change b_rptr.
15084 			 */
15085 			ipha = (ipha_t *)mp->b_rptr;
15086 			udpha = (udpha_t *)&ipha[1];
15087 
15088 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15089 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15090 				    mblk_t *, mp);
15091 				dst = INADDR_BROADCAST;
15092 			}
15093 		}
15094 
15095 		/* Full-blown slow path */
15096 		if (opt_len != 0) {
15097 			if (len != 0)
15098 				IP_STAT(ipst, ip_multimblk4);
15099 			else
15100 				IP_STAT(ipst, ip_ipoptions);
15101 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15102 			    &dst, ipst))
15103 				continue;
15104 		}
15105 
15106 		/*
15107 		 * Invoke the CGTP (multirouting) filtering module to process
15108 		 * the incoming packet. Packets identified as duplicates
15109 		 * must be discarded. Filtering is active only if the
15110 		 * the ip_cgtp_filter ndd variable is non-zero.
15111 		 */
15112 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15113 		if (ipst->ips_ip_cgtp_filter &&
15114 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15115 			netstackid_t stackid;
15116 
15117 			stackid = ipst->ips_netstack->netstack_stackid;
15118 			cgtp_flt_pkt =
15119 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15120 			    ill->ill_phyint->phyint_ifindex, mp);
15121 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15122 				freemsg(first_mp);
15123 				continue;
15124 			}
15125 		}
15126 
15127 		/*
15128 		 * If rsvpd is running, let RSVP daemon handle its processing
15129 		 * and forwarding of RSVP multicast/unicast packets.
15130 		 * If rsvpd is not running but mrouted is running, RSVP
15131 		 * multicast packets are forwarded as multicast traffic
15132 		 * and RSVP unicast packets are forwarded by unicast router.
15133 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15134 		 * packets are not forwarded, but the unicast packets are
15135 		 * forwarded like unicast traffic.
15136 		 */
15137 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15138 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15139 		    NULL) {
15140 			/* RSVP packet and rsvpd running. Treat as ours */
15141 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15142 			/*
15143 			 * This assumes that we deliver to all streams for
15144 			 * multicast and broadcast packets.
15145 			 * We have to force ll_multicast to 1 to handle the
15146 			 * M_DATA messages passed in from ip_mroute_decap.
15147 			 */
15148 			dst = INADDR_BROADCAST;
15149 			ll_multicast = 1;
15150 		} else if (CLASSD(dst)) {
15151 			/* packet is multicast */
15152 			mp->b_next = NULL;
15153 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15154 			    &ll_multicast, &dst))
15155 				continue;
15156 		}
15157 
15158 		if (ire == NULL) {
15159 			ire = ire_cache_lookup(dst, ALL_ZONES,
15160 			    msg_getlabel(mp), ipst);
15161 		}
15162 
15163 		if (ire != NULL && ire->ire_stq != NULL &&
15164 		    ire->ire_zoneid != GLOBAL_ZONEID &&
15165 		    ire->ire_zoneid != ALL_ZONES) {
15166 			/*
15167 			 * Should only use IREs that are visible from the
15168 			 * global zone for forwarding.
15169 			 */
15170 			ire_refrele(ire);
15171 			ire = ire_cache_lookup(dst, GLOBAL_ZONEID,
15172 			    msg_getlabel(mp), ipst);
15173 		}
15174 
15175 		if (ire == NULL) {
15176 			/*
15177 			 * No IRE for this destination, so it can't be for us.
15178 			 * Unless we are forwarding, drop the packet.
15179 			 * We have to let source routed packets through
15180 			 * since we don't yet know if they are 'ping -l'
15181 			 * packets i.e. if they will go out over the
15182 			 * same interface as they came in on.
15183 			 */
15184 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15185 			if (ire == NULL)
15186 				continue;
15187 		}
15188 
15189 		/*
15190 		 * Broadcast IRE may indicate either broadcast or
15191 		 * multicast packet
15192 		 */
15193 		if (ire->ire_type == IRE_BROADCAST) {
15194 			/*
15195 			 * Skip broadcast checks if packet is UDP multicast;
15196 			 * we'd rather not enter ip_rput_process_broadcast()
15197 			 * unless the packet is broadcast for real, since
15198 			 * that routine is a no-op for multicast.
15199 			 */
15200 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15201 			    !CLASSD(ipha->ipha_dst)) {
15202 				ire = ip_rput_process_broadcast(&q, mp,
15203 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15204 				    ll_multicast);
15205 				if (ire == NULL)
15206 					continue;
15207 			}
15208 		} else if (ire->ire_stq != NULL) {
15209 			/* fowarding? */
15210 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15211 			    ll_multicast, B_FALSE);
15212 			/* ip_rput_process_forward consumed the packet */
15213 			continue;
15214 		}
15215 
15216 local:
15217 		/*
15218 		 * If the queue in the ire is different to the ingress queue
15219 		 * then we need to check to see if we can accept the packet.
15220 		 * Note that for multicast packets and broadcast packets sent
15221 		 * to a broadcast address which is shared between multiple
15222 		 * interfaces we should not do this since we just got a random
15223 		 * broadcast ire.
15224 		 */
15225 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15226 			ire = ip_check_multihome(&ipha->ipha_dst, ire, ill);
15227 			if (ire == NULL) {
15228 				/* Drop packet */
15229 				BUMP_MIB(ill->ill_ip_mib,
15230 				    ipIfStatsForwProhibits);
15231 				freemsg(mp);
15232 				continue;
15233 			}
15234 			if (ire->ire_rfq != NULL)
15235 				q = ire->ire_rfq;
15236 		}
15237 
15238 		switch (ipha->ipha_protocol) {
15239 		case IPPROTO_TCP:
15240 			ASSERT(first_mp == mp);
15241 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15242 			    mp, 0, q, ip_ring)) != NULL) {
15243 				if (curr_sqp == NULL) {
15244 					curr_sqp = GET_SQUEUE(mp);
15245 					ASSERT(cnt == 0);
15246 					cnt++;
15247 					head = tail = mp;
15248 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15249 					ASSERT(tail != NULL);
15250 					cnt++;
15251 					tail->b_next = mp;
15252 					tail = mp;
15253 				} else {
15254 					/*
15255 					 * A different squeue. Send the
15256 					 * chain for the previous squeue on
15257 					 * its way. This shouldn't happen
15258 					 * often unless interrupt binding
15259 					 * changes.
15260 					 */
15261 					IP_STAT(ipst, ip_input_multi_squeue);
15262 					SQUEUE_ENTER(curr_sqp, head,
15263 					    tail, cnt, SQ_PROCESS, tag);
15264 					curr_sqp = GET_SQUEUE(mp);
15265 					head = mp;
15266 					tail = mp;
15267 					cnt = 1;
15268 				}
15269 			}
15270 			continue;
15271 		case IPPROTO_UDP:
15272 			ASSERT(first_mp == mp);
15273 			ip_udp_input(q, mp, ipha, ire, ill);
15274 			continue;
15275 		case IPPROTO_SCTP:
15276 			ASSERT(first_mp == mp);
15277 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15278 			    q, dst);
15279 			/* ire has been released by ip_sctp_input */
15280 			ire = NULL;
15281 			continue;
15282 		default:
15283 			ip_proto_input(q, first_mp, ipha, ire, ill, 0);
15284 			continue;
15285 		}
15286 	}
15287 
15288 	if (ire != NULL)
15289 		ire_refrele(ire);
15290 
15291 	if (head != NULL)
15292 		SQUEUE_ENTER(curr_sqp, head, tail, cnt, SQ_PROCESS, tag);
15293 
15294 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15295 	    "ip_input_end: q %p (%S)", q, "end");
15296 #undef  rptr
15297 }
15298 
15299 /*
15300  * ip_accept_tcp() - This function is called by the squeue when it retrieves
15301  * a chain of packets in the poll mode. The packets have gone through the
15302  * data link processing but not IP processing. For performance and latency
15303  * reasons, the squeue wants to process the chain in line instead of feeding
15304  * it back via ip_input path.
15305  *
15306  * So this is a light weight function which checks to see if the packets
15307  * retrived are indeed TCP packets (TCP squeue always polls TCP soft ring
15308  * but we still do the paranoid check) meant for local machine and we don't
15309  * have labels etc enabled. Packets that meet the criterion are returned to
15310  * the squeue and processed inline while the rest go via ip_input path.
15311  */
15312 /*ARGSUSED*/
15313 mblk_t *
15314 ip_accept_tcp(ill_t *ill, ill_rx_ring_t *ip_ring, squeue_t *target_sqp,
15315     mblk_t *mp_chain, mblk_t **last, uint_t *cnt)
15316 {
15317 	mblk_t 		*mp;
15318 	ipaddr_t	dst = NULL;
15319 	ipaddr_t	prev_dst;
15320 	ire_t		*ire = NULL;
15321 	ipha_t		*ipha;
15322 	uint_t		pkt_len;
15323 	ssize_t		len;
15324 	uint_t		opt_len;
15325 	queue_t		*q = ill->ill_rq;
15326 	squeue_t	*curr_sqp;
15327 	mblk_t 		*ahead = NULL;	/* Accepted head */
15328 	mblk_t		*atail = NULL;	/* Accepted tail */
15329 	uint_t		acnt = 0;	/* Accepted count */
15330 	mblk_t		*utail = NULL;	/* Unaccepted head */
15331 	mblk_t		*uhead = NULL;	/* Unaccepted tail */
15332 	uint_t		ucnt = 0;	/* Unaccepted cnt */
15333 	ip_stack_t	*ipst = ill->ill_ipst;
15334 
15335 	*cnt = 0;
15336 
15337 	ASSERT(ill != NULL);
15338 	ASSERT(ip_ring != NULL);
15339 
15340 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_accept_tcp: q %p", q);
15341 
15342 #define	rptr	((uchar_t *)ipha)
15343 
15344 	while (mp_chain != NULL) {
15345 		mp = mp_chain;
15346 		mp_chain = mp_chain->b_next;
15347 		mp->b_next = NULL;
15348 
15349 		/*
15350 		 * We do ire caching from one iteration to
15351 		 * another. In the event the packet chain contains
15352 		 * all packets from the same dst, this caching saves
15353 		 * an ire_cache_lookup for each of the succeeding
15354 		 * packets in a packet chain.
15355 		 */
15356 		prev_dst = dst;
15357 
15358 		ipha = (ipha_t *)mp->b_rptr;
15359 		len = mp->b_wptr - rptr;
15360 
15361 		ASSERT(!MBLK_RX_FANOUT_SLOWPATH(mp, ipha));
15362 
15363 		/*
15364 		 * If it is a non TCP packet, or doesn't have H/W cksum,
15365 		 * or doesn't have min len, reject.
15366 		 */
15367 		if ((ipha->ipha_protocol != IPPROTO_TCP) || (len <
15368 		    (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH))) {
15369 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15370 			continue;
15371 		}
15372 
15373 		pkt_len = ntohs(ipha->ipha_length);
15374 		if (len != pkt_len) {
15375 			if (len > pkt_len) {
15376 				mp->b_wptr = rptr + pkt_len;
15377 			} else {
15378 				ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15379 				continue;
15380 			}
15381 		}
15382 
15383 		opt_len = ipha->ipha_version_and_hdr_length -
15384 		    IP_SIMPLE_HDR_VERSION;
15385 		dst = ipha->ipha_dst;
15386 
15387 		/* IP version bad or there are IP options */
15388 		if (opt_len && (!ip_rput_multimblk_ipoptions(q, ill,
15389 		    mp, &ipha, &dst, ipst)))
15390 			continue;
15391 
15392 		if (is_system_labeled() || (ill->ill_dhcpinit != 0) ||
15393 		    (ipst->ips_ip_cgtp_filter &&
15394 		    ipst->ips_ip_cgtp_filter_ops != NULL)) {
15395 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15396 			continue;
15397 		}
15398 
15399 		/*
15400 		 * Reuse the cached ire only if the ipha_dst of the previous
15401 		 * packet is the same as the current packet AND it is not
15402 		 * INADDR_ANY.
15403 		 */
15404 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15405 		    (ire != NULL)) {
15406 			ire_refrele(ire);
15407 			ire = NULL;
15408 		}
15409 
15410 		if (ire == NULL)
15411 			ire = ire_cache_lookup_simple(dst, ipst);
15412 
15413 		/*
15414 		 * Unless forwarding is enabled, dont call
15415 		 * ip_fast_forward(). Incoming packet is for forwarding
15416 		 */
15417 		if ((ill->ill_flags & ILLF_ROUTER) &&
15418 		    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15419 
15420 			DTRACE_PROBE4(ip4__physical__in__start,
15421 			    ill_t *, ill, ill_t *, NULL,
15422 			    ipha_t *, ipha, mblk_t *, mp);
15423 
15424 			FW_HOOKS(ipst->ips_ip4_physical_in_event,
15425 			    ipst->ips_ipv4firewall_physical_in,
15426 			    ill, NULL, ipha, mp, mp, 0, ipst);
15427 
15428 			DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15429 
15430 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15431 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets,
15432 			    pkt_len);
15433 
15434 			ire = ip_fast_forward(ire, dst, ill, mp);
15435 			continue;
15436 		}
15437 
15438 		/* incoming packet is for local consumption */
15439 		if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15440 			goto local_accept;
15441 
15442 		/*
15443 		 * Disable ire caching for anything more complex
15444 		 * than the simple fast path case we checked for above.
15445 		 */
15446 		if (ire != NULL) {
15447 			ire_refrele(ire);
15448 			ire = NULL;
15449 		}
15450 
15451 		ire = ire_cache_lookup(dst, ALL_ZONES, msg_getlabel(mp),
15452 		    ipst);
15453 		if (ire == NULL || ire->ire_type == IRE_BROADCAST ||
15454 		    ire->ire_stq != NULL) {
15455 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15456 			if (ire != NULL) {
15457 				ire_refrele(ire);
15458 				ire = NULL;
15459 			}
15460 			continue;
15461 		}
15462 
15463 local_accept:
15464 
15465 		if (ire->ire_rfq != q) {
15466 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15467 			if (ire != NULL) {
15468 				ire_refrele(ire);
15469 				ire = NULL;
15470 			}
15471 			continue;
15472 		}
15473 
15474 		/*
15475 		 * The event for packets being received from a 'physical'
15476 		 * interface is placed after validation of the source and/or
15477 		 * destination address as being local so that packets can be
15478 		 * redirected to loopback addresses using ipnat.
15479 		 */
15480 		DTRACE_PROBE4(ip4__physical__in__start,
15481 		    ill_t *, ill, ill_t *, NULL,
15482 		    ipha_t *, ipha, mblk_t *, mp);
15483 
15484 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15485 		    ipst->ips_ipv4firewall_physical_in,
15486 		    ill, NULL, ipha, mp, mp, 0, ipst);
15487 
15488 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15489 
15490 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15491 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15492 
15493 		if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire, mp,
15494 		    0, q, ip_ring)) != NULL) {
15495 			if ((curr_sqp = GET_SQUEUE(mp)) == target_sqp) {
15496 				ADD_TO_CHAIN(ahead, atail, acnt, mp);
15497 			} else {
15498 				SQUEUE_ENTER(curr_sqp, mp, mp, 1,
15499 				    SQ_FILL, SQTAG_IP_INPUT);
15500 			}
15501 		}
15502 	}
15503 
15504 	if (ire != NULL)
15505 		ire_refrele(ire);
15506 
15507 	if (uhead != NULL)
15508 		ip_input(ill, ip_ring, uhead, NULL);
15509 
15510 	if (ahead != NULL) {
15511 		*last = atail;
15512 		*cnt = acnt;
15513 		return (ahead);
15514 	}
15515 
15516 	return (NULL);
15517 #undef  rptr
15518 }
15519 
15520 static void
15521 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15522     t_uscalar_t err)
15523 {
15524 	if (dl_err == DL_SYSERR) {
15525 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15526 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15527 		    ill->ill_name, dl_primstr(prim), err);
15528 		return;
15529 	}
15530 
15531 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15532 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15533 	    dl_errstr(dl_err));
15534 }
15535 
15536 /*
15537  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15538  * than DL_UNITDATA_IND messages. If we need to process this message
15539  * exclusively, we call qwriter_ip, in which case we also need to call
15540  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15541  */
15542 void
15543 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15544 {
15545 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15546 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15547 	ill_t		*ill = q->q_ptr;
15548 	t_uscalar_t	prim = dloa->dl_primitive;
15549 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
15550 
15551 	ip1dbg(("ip_rput_dlpi"));
15552 
15553 	/*
15554 	 * If we received an ACK but didn't send a request for it, then it
15555 	 * can't be part of any pending operation; discard up-front.
15556 	 */
15557 	switch (prim) {
15558 	case DL_ERROR_ACK:
15559 		reqprim = dlea->dl_error_primitive;
15560 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
15561 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
15562 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
15563 		    dlea->dl_unix_errno));
15564 		break;
15565 	case DL_OK_ACK:
15566 		reqprim = dloa->dl_correct_primitive;
15567 		break;
15568 	case DL_INFO_ACK:
15569 		reqprim = DL_INFO_REQ;
15570 		break;
15571 	case DL_BIND_ACK:
15572 		reqprim = DL_BIND_REQ;
15573 		break;
15574 	case DL_PHYS_ADDR_ACK:
15575 		reqprim = DL_PHYS_ADDR_REQ;
15576 		break;
15577 	case DL_NOTIFY_ACK:
15578 		reqprim = DL_NOTIFY_REQ;
15579 		break;
15580 	case DL_CONTROL_ACK:
15581 		reqprim = DL_CONTROL_REQ;
15582 		break;
15583 	case DL_CAPABILITY_ACK:
15584 		reqprim = DL_CAPABILITY_REQ;
15585 		break;
15586 	}
15587 
15588 	if (prim != DL_NOTIFY_IND) {
15589 		if (reqprim == DL_PRIM_INVAL ||
15590 		    !ill_dlpi_pending(ill, reqprim)) {
15591 			/* Not a DLPI message we support or expected */
15592 			freemsg(mp);
15593 			return;
15594 		}
15595 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
15596 		    dl_primstr(reqprim)));
15597 	}
15598 
15599 	switch (reqprim) {
15600 	case DL_UNBIND_REQ:
15601 		/*
15602 		 * NOTE: we mark the unbind as complete even if we got a
15603 		 * DL_ERROR_ACK, since there's not much else we can do.
15604 		 */
15605 		mutex_enter(&ill->ill_lock);
15606 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15607 		cv_signal(&ill->ill_cv);
15608 		mutex_exit(&ill->ill_lock);
15609 		break;
15610 
15611 	case DL_ENABMULTI_REQ:
15612 		if (prim == DL_OK_ACK) {
15613 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15614 				ill->ill_dlpi_multicast_state = IDS_OK;
15615 		}
15616 		break;
15617 	}
15618 
15619 	/*
15620 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
15621 	 * need to become writer to continue to process it.  Because an
15622 	 * exclusive operation doesn't complete until replies to all queued
15623 	 * DLPI messages have been received, we know we're in the middle of an
15624 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
15625 	 *
15626 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15627 	 * Since this is on the ill stream we unconditionally bump up the
15628 	 * refcount without doing ILL_CAN_LOOKUP().
15629 	 */
15630 	ill_refhold(ill);
15631 	if (prim == DL_NOTIFY_IND)
15632 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15633 	else
15634 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15635 }
15636 
15637 /*
15638  * Handling of DLPI messages that require exclusive access to the ipsq.
15639  *
15640  * Need to do ill_pending_mp_release on ioctl completion, which could
15641  * happen here. (along with mi_copy_done)
15642  */
15643 /* ARGSUSED */
15644 static void
15645 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15646 {
15647 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15648 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15649 	int		err = 0;
15650 	ill_t		*ill;
15651 	ipif_t		*ipif = NULL;
15652 	mblk_t		*mp1 = NULL;
15653 	conn_t		*connp = NULL;
15654 	t_uscalar_t	paddrreq;
15655 	mblk_t		*mp_hw;
15656 	boolean_t	success;
15657 	boolean_t	ioctl_aborted = B_FALSE;
15658 	boolean_t	log = B_TRUE;
15659 	ip_stack_t		*ipst;
15660 
15661 	ip1dbg(("ip_rput_dlpi_writer .."));
15662 	ill = (ill_t *)q->q_ptr;
15663 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
15664 	ASSERT(IAM_WRITER_ILL(ill));
15665 
15666 	ipst = ill->ill_ipst;
15667 
15668 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
15669 	/*
15670 	 * The current ioctl could have been aborted by the user and a new
15671 	 * ioctl to bring up another ill could have started. We could still
15672 	 * get a response from the driver later.
15673 	 */
15674 	if (ipif != NULL && ipif->ipif_ill != ill)
15675 		ioctl_aborted = B_TRUE;
15676 
15677 	switch (dloa->dl_primitive) {
15678 	case DL_ERROR_ACK:
15679 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15680 		    dl_primstr(dlea->dl_error_primitive)));
15681 
15682 		switch (dlea->dl_error_primitive) {
15683 		case DL_DISABMULTI_REQ:
15684 			if (!ill->ill_isv6)
15685 				ipsq_current_finish(ipsq);
15686 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15687 			break;
15688 		case DL_PROMISCON_REQ:
15689 		case DL_PROMISCOFF_REQ:
15690 		case DL_UNBIND_REQ:
15691 		case DL_ATTACH_REQ:
15692 		case DL_INFO_REQ:
15693 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15694 			break;
15695 		case DL_NOTIFY_REQ:
15696 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15697 			log = B_FALSE;
15698 			break;
15699 		case DL_PHYS_ADDR_REQ:
15700 			/*
15701 			 * For IPv6 only, there are two additional
15702 			 * phys_addr_req's sent to the driver to get the
15703 			 * IPv6 token and lla. This allows IP to acquire
15704 			 * the hardware address format for a given interface
15705 			 * without having built in knowledge of the hardware
15706 			 * address. ill_phys_addr_pend keeps track of the last
15707 			 * DL_PAR sent so we know which response we are
15708 			 * dealing with. ill_dlpi_done will update
15709 			 * ill_phys_addr_pend when it sends the next req.
15710 			 * We don't complete the IOCTL until all three DL_PARs
15711 			 * have been attempted, so set *_len to 0 and break.
15712 			 */
15713 			paddrreq = ill->ill_phys_addr_pend;
15714 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15715 			if (paddrreq == DL_IPV6_TOKEN) {
15716 				ill->ill_token_length = 0;
15717 				log = B_FALSE;
15718 				break;
15719 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15720 				ill->ill_nd_lla_len = 0;
15721 				log = B_FALSE;
15722 				break;
15723 			}
15724 			/*
15725 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15726 			 * We presumably have an IOCTL hanging out waiting
15727 			 * for completion. Find it and complete the IOCTL
15728 			 * with the error noted.
15729 			 * However, ill_dl_phys was called on an ill queue
15730 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15731 			 * set. But the ioctl is known to be pending on ill_wq.
15732 			 */
15733 			if (!ill->ill_ifname_pending)
15734 				break;
15735 			ill->ill_ifname_pending = 0;
15736 			if (!ioctl_aborted)
15737 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15738 			if (mp1 != NULL) {
15739 				/*
15740 				 * This operation (SIOCSLIFNAME) must have
15741 				 * happened on the ill. Assert there is no conn
15742 				 */
15743 				ASSERT(connp == NULL);
15744 				q = ill->ill_wq;
15745 			}
15746 			break;
15747 		case DL_BIND_REQ:
15748 			ill_dlpi_done(ill, DL_BIND_REQ);
15749 			if (ill->ill_ifname_pending)
15750 				break;
15751 			/*
15752 			 * Something went wrong with the bind.  We presumably
15753 			 * have an IOCTL hanging out waiting for completion.
15754 			 * Find it, take down the interface that was coming
15755 			 * up, and complete the IOCTL with the error noted.
15756 			 */
15757 			if (!ioctl_aborted)
15758 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15759 			if (mp1 != NULL) {
15760 				/*
15761 				 * This operation (SIOCSLIFFLAGS) must have
15762 				 * happened from a conn.
15763 				 */
15764 				ASSERT(connp != NULL);
15765 				q = CONNP_TO_WQ(connp);
15766 				(void) ipif_down(ipif, NULL, NULL);
15767 				/* error is set below the switch */
15768 			}
15769 			break;
15770 		case DL_ENABMULTI_REQ:
15771 			if (!ill->ill_isv6)
15772 				ipsq_current_finish(ipsq);
15773 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15774 
15775 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15776 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15777 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15778 				ipif_t *ipif;
15779 
15780 				printf("ip: joining multicasts failed (%d)"
15781 				    " on %s - will use link layer "
15782 				    "broadcasts for multicast\n",
15783 				    dlea->dl_errno, ill->ill_name);
15784 
15785 				/*
15786 				 * Set up the multicast mapping alone.
15787 				 * writer, so ok to access ill->ill_ipif
15788 				 * without any lock.
15789 				 */
15790 				ipif = ill->ill_ipif;
15791 				mutex_enter(&ill->ill_phyint->phyint_lock);
15792 				ill->ill_phyint->phyint_flags |=
15793 				    PHYI_MULTI_BCAST;
15794 				mutex_exit(&ill->ill_phyint->phyint_lock);
15795 
15796 				if (!ill->ill_isv6) {
15797 					(void) ipif_arp_setup_multicast(ipif,
15798 					    NULL);
15799 				} else {
15800 					(void) ipif_ndp_setup_multicast(ipif,
15801 					    NULL);
15802 				}
15803 			}
15804 			freemsg(mp);	/* Don't want to pass this up */
15805 			return;
15806 		case DL_CONTROL_REQ:
15807 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15808 			    "DL_CONTROL_REQ\n"));
15809 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15810 			freemsg(mp);
15811 			return;
15812 		case DL_CAPABILITY_REQ:
15813 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15814 			    "DL_CAPABILITY REQ\n"));
15815 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
15816 				ill->ill_dlpi_capab_state = IDCS_FAILED;
15817 			ill_capability_done(ill);
15818 			freemsg(mp);
15819 			return;
15820 		}
15821 		/*
15822 		 * Note the error for IOCTL completion (mp1 is set when
15823 		 * ready to complete ioctl). If ill_ifname_pending_err is
15824 		 * set, an error occured during plumbing (ill_ifname_pending),
15825 		 * so we want to report that error.
15826 		 *
15827 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15828 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15829 		 * expected to get errack'd if the driver doesn't support
15830 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15831 		 * if these error conditions are encountered.
15832 		 */
15833 		if (mp1 != NULL) {
15834 			if (ill->ill_ifname_pending_err != 0)  {
15835 				err = ill->ill_ifname_pending_err;
15836 				ill->ill_ifname_pending_err = 0;
15837 			} else {
15838 				err = dlea->dl_unix_errno ?
15839 				    dlea->dl_unix_errno : ENXIO;
15840 			}
15841 		/*
15842 		 * If we're plumbing an interface and an error hasn't already
15843 		 * been saved, set ill_ifname_pending_err to the error passed
15844 		 * up. Ignore the error if log is B_FALSE (see comment above).
15845 		 */
15846 		} else if (log && ill->ill_ifname_pending &&
15847 		    ill->ill_ifname_pending_err == 0) {
15848 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15849 			    dlea->dl_unix_errno : ENXIO;
15850 		}
15851 
15852 		if (log)
15853 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15854 			    dlea->dl_errno, dlea->dl_unix_errno);
15855 		break;
15856 	case DL_CAPABILITY_ACK:
15857 		ill_capability_ack(ill, mp);
15858 		/*
15859 		 * The message has been handed off to ill_capability_ack
15860 		 * and must not be freed below
15861 		 */
15862 		mp = NULL;
15863 		break;
15864 
15865 	case DL_CONTROL_ACK:
15866 		/* We treat all of these as "fire and forget" */
15867 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15868 		break;
15869 	case DL_INFO_ACK:
15870 		/* Call a routine to handle this one. */
15871 		ill_dlpi_done(ill, DL_INFO_REQ);
15872 		ip_ll_subnet_defaults(ill, mp);
15873 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15874 		return;
15875 	case DL_BIND_ACK:
15876 		/*
15877 		 * We should have an IOCTL waiting on this unless
15878 		 * sent by ill_dl_phys, in which case just return
15879 		 */
15880 		ill_dlpi_done(ill, DL_BIND_REQ);
15881 		if (ill->ill_ifname_pending)
15882 			break;
15883 
15884 		if (!ioctl_aborted)
15885 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15886 		if (mp1 == NULL)
15887 			break;
15888 		/*
15889 		 * Because mp1 was added by ill_dl_up(), and it always
15890 		 * passes a valid connp, connp must be valid here.
15891 		 */
15892 		ASSERT(connp != NULL);
15893 		q = CONNP_TO_WQ(connp);
15894 
15895 		/*
15896 		 * We are exclusive. So nothing can change even after
15897 		 * we get the pending mp. If need be we can put it back
15898 		 * and restart, as in calling ipif_arp_up()  below.
15899 		 */
15900 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15901 
15902 		mutex_enter(&ill->ill_lock);
15903 		ill->ill_dl_up = 1;
15904 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
15905 		mutex_exit(&ill->ill_lock);
15906 
15907 		/*
15908 		 * Now bring up the resolver; when that is complete, we'll
15909 		 * create IREs.  Note that we intentionally mirror what
15910 		 * ipif_up() would have done, because we got here by way of
15911 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15912 		 */
15913 		if (ill->ill_isv6) {
15914 			if (ill->ill_flags & ILLF_XRESOLV) {
15915 				mutex_enter(&connp->conn_lock);
15916 				mutex_enter(&ill->ill_lock);
15917 				success = ipsq_pending_mp_add(connp, ipif, q,
15918 				    mp1, 0);
15919 				mutex_exit(&ill->ill_lock);
15920 				mutex_exit(&connp->conn_lock);
15921 				if (success) {
15922 					err = ipif_resolver_up(ipif,
15923 					    Res_act_initial);
15924 					if (err == EINPROGRESS) {
15925 						freemsg(mp);
15926 						return;
15927 					}
15928 					ASSERT(err != 0);
15929 					mp1 = ipsq_pending_mp_get(ipsq, &connp);
15930 					ASSERT(mp1 != NULL);
15931 				} else {
15932 					/* conn has started closing */
15933 					err = EINTR;
15934 				}
15935 			} else { /* Non XRESOLV interface */
15936 				(void) ipif_resolver_up(ipif, Res_act_initial);
15937 				if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
15938 					err = ipif_up_done_v6(ipif);
15939 			}
15940 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15941 			/*
15942 			 * ARP and other v4 external resolvers.
15943 			 * Leave the pending mblk intact so that
15944 			 * the ioctl completes in ip_rput().
15945 			 */
15946 			mutex_enter(&connp->conn_lock);
15947 			mutex_enter(&ill->ill_lock);
15948 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15949 			mutex_exit(&ill->ill_lock);
15950 			mutex_exit(&connp->conn_lock);
15951 			if (success) {
15952 				err = ipif_resolver_up(ipif, Res_act_initial);
15953 				if (err == EINPROGRESS) {
15954 					freemsg(mp);
15955 					return;
15956 				}
15957 				ASSERT(err != 0);
15958 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15959 			} else {
15960 				/* The conn has started closing */
15961 				err = EINTR;
15962 			}
15963 		} else {
15964 			/*
15965 			 * This one is complete. Reply to pending ioctl.
15966 			 */
15967 			(void) ipif_resolver_up(ipif, Res_act_initial);
15968 			err = ipif_up_done(ipif);
15969 		}
15970 
15971 		if ((err == 0) && (ill->ill_up_ipifs)) {
15972 			err = ill_up_ipifs(ill, q, mp1);
15973 			if (err == EINPROGRESS) {
15974 				freemsg(mp);
15975 				return;
15976 			}
15977 		}
15978 
15979 		/*
15980 		 * If we have a moved ipif to bring up, and everything has
15981 		 * succeeded to this point, bring it up on the IPMP ill.
15982 		 * Otherwise, leave it down -- the admin can try to bring it
15983 		 * up by hand if need be.
15984 		 */
15985 		if (ill->ill_move_ipif != NULL) {
15986 			if (err != 0) {
15987 				ill->ill_move_ipif = NULL;
15988 			} else {
15989 				ipif = ill->ill_move_ipif;
15990 				ill->ill_move_ipif = NULL;
15991 				err = ipif_up(ipif, q, mp1);
15992 				if (err == EINPROGRESS) {
15993 					freemsg(mp);
15994 					return;
15995 				}
15996 			}
15997 		}
15998 		break;
15999 
16000 	case DL_NOTIFY_IND: {
16001 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16002 		ire_t *ire;
16003 		uint_t orig_mtu;
16004 		boolean_t need_ire_walk_v4 = B_FALSE;
16005 		boolean_t need_ire_walk_v6 = B_FALSE;
16006 
16007 		switch (notify->dl_notification) {
16008 		case DL_NOTE_PHYS_ADDR:
16009 			err = ill_set_phys_addr(ill, mp);
16010 			break;
16011 
16012 		case DL_NOTE_FASTPATH_FLUSH:
16013 			ill_fastpath_flush(ill);
16014 			break;
16015 
16016 		case DL_NOTE_SDU_SIZE:
16017 			/*
16018 			 * Change the MTU size of the interface, of all
16019 			 * attached ipif's, and of all relevant ire's.  The
16020 			 * new value's a uint32_t at notify->dl_data.
16021 			 * Mtu change Vs. new ire creation - protocol below.
16022 			 *
16023 			 * a Mark the ipif as IPIF_CHANGING.
16024 			 * b Set the new mtu in the ipif.
16025 			 * c Change the ire_max_frag on all affected ires
16026 			 * d Unmark the IPIF_CHANGING
16027 			 *
16028 			 * To see how the protocol works, assume an interface
16029 			 * route is also being added simultaneously by
16030 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16031 			 * the ire. If the ire is created before step a,
16032 			 * it will be cleaned up by step c. If the ire is
16033 			 * created after step d, it will see the new value of
16034 			 * ipif_mtu. Any attempt to create the ire between
16035 			 * steps a to d will fail because of the IPIF_CHANGING
16036 			 * flag. Note that ire_create() is passed a pointer to
16037 			 * the ipif_mtu, and not the value. During ire_add
16038 			 * under the bucket lock, the ire_max_frag of the
16039 			 * new ire being created is set from the ipif/ire from
16040 			 * which it is being derived.
16041 			 */
16042 			mutex_enter(&ill->ill_lock);
16043 
16044 			orig_mtu = ill->ill_max_mtu;
16045 			ill->ill_max_frag = (uint_t)notify->dl_data;
16046 			ill->ill_max_mtu = (uint_t)notify->dl_data;
16047 
16048 			/*
16049 			 * If ill_user_mtu was set (via SIOCSLIFLNKINFO),
16050 			 * clamp ill_max_mtu at it.
16051 			 */
16052 			if (ill->ill_user_mtu != 0 &&
16053 			    ill->ill_user_mtu < ill->ill_max_mtu)
16054 				ill->ill_max_mtu = ill->ill_user_mtu;
16055 
16056 			/*
16057 			 * If the MTU is unchanged, we're done.
16058 			 */
16059 			if (orig_mtu == ill->ill_max_mtu) {
16060 				mutex_exit(&ill->ill_lock);
16061 				break;
16062 			}
16063 
16064 			if (ill->ill_isv6) {
16065 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16066 					ill->ill_max_mtu = IPV6_MIN_MTU;
16067 			} else {
16068 				if (ill->ill_max_mtu < IP_MIN_MTU)
16069 					ill->ill_max_mtu = IP_MIN_MTU;
16070 			}
16071 			for (ipif = ill->ill_ipif; ipif != NULL;
16072 			    ipif = ipif->ipif_next) {
16073 				/*
16074 				 * Don't override the mtu if the user
16075 				 * has explicitly set it.
16076 				 */
16077 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16078 					continue;
16079 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16080 				if (ipif->ipif_isv6)
16081 					ire = ipif_to_ire_v6(ipif);
16082 				else
16083 					ire = ipif_to_ire(ipif);
16084 				if (ire != NULL) {
16085 					ire->ire_max_frag = ipif->ipif_mtu;
16086 					ire_refrele(ire);
16087 				}
16088 				if (ipif->ipif_flags & IPIF_UP) {
16089 					if (ill->ill_isv6)
16090 						need_ire_walk_v6 = B_TRUE;
16091 					else
16092 						need_ire_walk_v4 = B_TRUE;
16093 				}
16094 			}
16095 			mutex_exit(&ill->ill_lock);
16096 			if (need_ire_walk_v4)
16097 				ire_walk_v4(ill_mtu_change, (char *)ill,
16098 				    ALL_ZONES, ipst);
16099 			if (need_ire_walk_v6)
16100 				ire_walk_v6(ill_mtu_change, (char *)ill,
16101 				    ALL_ZONES, ipst);
16102 
16103 			/*
16104 			 * Refresh IPMP meta-interface MTU if necessary.
16105 			 */
16106 			if (IS_UNDER_IPMP(ill))
16107 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
16108 			break;
16109 
16110 		case DL_NOTE_LINK_UP:
16111 		case DL_NOTE_LINK_DOWN: {
16112 			/*
16113 			 * We are writer. ill / phyint / ipsq assocs stable.
16114 			 * The RUNNING flag reflects the state of the link.
16115 			 */
16116 			phyint_t *phyint = ill->ill_phyint;
16117 			uint64_t new_phyint_flags;
16118 			boolean_t changed = B_FALSE;
16119 			boolean_t went_up;
16120 
16121 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16122 			mutex_enter(&phyint->phyint_lock);
16123 
16124 			new_phyint_flags = went_up ?
16125 			    phyint->phyint_flags | PHYI_RUNNING :
16126 			    phyint->phyint_flags & ~PHYI_RUNNING;
16127 
16128 			if (IS_IPMP(ill)) {
16129 				new_phyint_flags = went_up ?
16130 				    new_phyint_flags & ~PHYI_FAILED :
16131 				    new_phyint_flags | PHYI_FAILED;
16132 			}
16133 
16134 			if (new_phyint_flags != phyint->phyint_flags) {
16135 				phyint->phyint_flags = new_phyint_flags;
16136 				changed = B_TRUE;
16137 			}
16138 			mutex_exit(&phyint->phyint_lock);
16139 			/*
16140 			 * ill_restart_dad handles the DAD restart and routing
16141 			 * socket notification logic.
16142 			 */
16143 			if (changed) {
16144 				ill_restart_dad(phyint->phyint_illv4, went_up);
16145 				ill_restart_dad(phyint->phyint_illv6, went_up);
16146 			}
16147 			break;
16148 		}
16149 		case DL_NOTE_PROMISC_ON_PHYS:
16150 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16151 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16152 			mutex_enter(&ill->ill_lock);
16153 			ill->ill_promisc_on_phys = B_TRUE;
16154 			mutex_exit(&ill->ill_lock);
16155 			break;
16156 		case DL_NOTE_PROMISC_OFF_PHYS:
16157 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16158 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16159 			mutex_enter(&ill->ill_lock);
16160 			ill->ill_promisc_on_phys = B_FALSE;
16161 			mutex_exit(&ill->ill_lock);
16162 			break;
16163 		case DL_NOTE_CAPAB_RENEG:
16164 			/*
16165 			 * Something changed on the driver side.
16166 			 * It wants us to renegotiate the capabilities
16167 			 * on this ill. One possible cause is the aggregation
16168 			 * interface under us where a port got added or
16169 			 * went away.
16170 			 *
16171 			 * If the capability negotiation is already done
16172 			 * or is in progress, reset the capabilities and
16173 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16174 			 * so that when the ack comes back, we can start
16175 			 * the renegotiation process.
16176 			 *
16177 			 * Note that if ill_capab_reneg is already B_TRUE
16178 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16179 			 * the capability resetting request has been sent
16180 			 * and the renegotiation has not been started yet;
16181 			 * nothing needs to be done in this case.
16182 			 */
16183 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
16184 			ill_capability_reset(ill, B_TRUE);
16185 			ipsq_current_finish(ipsq);
16186 			break;
16187 		default:
16188 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16189 			    "type 0x%x for DL_NOTIFY_IND\n",
16190 			    notify->dl_notification));
16191 			break;
16192 		}
16193 
16194 		/*
16195 		 * As this is an asynchronous operation, we
16196 		 * should not call ill_dlpi_done
16197 		 */
16198 		break;
16199 	}
16200 	case DL_NOTIFY_ACK: {
16201 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16202 
16203 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16204 			ill->ill_note_link = 1;
16205 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16206 		break;
16207 	}
16208 	case DL_PHYS_ADDR_ACK: {
16209 		/*
16210 		 * As part of plumbing the interface via SIOCSLIFNAME,
16211 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16212 		 * whose answers we receive here.  As each answer is received,
16213 		 * we call ill_dlpi_done() to dispatch the next request as
16214 		 * we're processing the current one.  Once all answers have
16215 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16216 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16217 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16218 		 * available, but we know the ioctl is pending on ill_wq.)
16219 		 */
16220 		uint_t	paddrlen, paddroff;
16221 
16222 		paddrreq = ill->ill_phys_addr_pend;
16223 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16224 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16225 
16226 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16227 		if (paddrreq == DL_IPV6_TOKEN) {
16228 			/*
16229 			 * bcopy to low-order bits of ill_token
16230 			 *
16231 			 * XXX Temporary hack - currently, all known tokens
16232 			 * are 64 bits, so I'll cheat for the moment.
16233 			 */
16234 			bcopy(mp->b_rptr + paddroff,
16235 			    &ill->ill_token.s6_addr32[2], paddrlen);
16236 			ill->ill_token_length = paddrlen;
16237 			break;
16238 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16239 			ASSERT(ill->ill_nd_lla_mp == NULL);
16240 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16241 			mp = NULL;
16242 			break;
16243 		}
16244 
16245 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16246 		ASSERT(ill->ill_phys_addr_mp == NULL);
16247 		if (!ill->ill_ifname_pending)
16248 			break;
16249 		ill->ill_ifname_pending = 0;
16250 		if (!ioctl_aborted)
16251 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16252 		if (mp1 != NULL) {
16253 			ASSERT(connp == NULL);
16254 			q = ill->ill_wq;
16255 		}
16256 		/*
16257 		 * If any error acks received during the plumbing sequence,
16258 		 * ill_ifname_pending_err will be set. Break out and send up
16259 		 * the error to the pending ioctl.
16260 		 */
16261 		if (ill->ill_ifname_pending_err != 0) {
16262 			err = ill->ill_ifname_pending_err;
16263 			ill->ill_ifname_pending_err = 0;
16264 			break;
16265 		}
16266 
16267 		ill->ill_phys_addr_mp = mp;
16268 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16269 		mp = NULL;
16270 
16271 		/*
16272 		 * If paddrlen is zero, the DLPI provider doesn't support
16273 		 * physical addresses.  The other two tests were historical
16274 		 * workarounds for bugs in our former PPP implementation, but
16275 		 * now other things have grown dependencies on them -- e.g.,
16276 		 * the tun module specifies a dl_addr_length of zero in its
16277 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16278 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16279 		 * but only after careful testing ensures that all dependent
16280 		 * broken DLPI providers have been fixed.
16281 		 */
16282 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16283 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16284 			ill->ill_phys_addr = NULL;
16285 		} else if (paddrlen != ill->ill_phys_addr_length) {
16286 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16287 			    paddrlen, ill->ill_phys_addr_length));
16288 			err = EINVAL;
16289 			break;
16290 		}
16291 
16292 		if (ill->ill_nd_lla_mp == NULL) {
16293 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16294 				err = ENOMEM;
16295 				break;
16296 			}
16297 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16298 		}
16299 
16300 		/*
16301 		 * Set the interface token.  If the zeroth interface address
16302 		 * is unspecified, then set it to the link local address.
16303 		 */
16304 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16305 			(void) ill_setdefaulttoken(ill);
16306 
16307 		ASSERT(ill->ill_ipif->ipif_id == 0);
16308 		if (ipif != NULL &&
16309 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16310 			(void) ipif_setlinklocal(ipif);
16311 		}
16312 		break;
16313 	}
16314 	case DL_OK_ACK:
16315 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16316 		    dl_primstr((int)dloa->dl_correct_primitive),
16317 		    dloa->dl_correct_primitive));
16318 		switch (dloa->dl_correct_primitive) {
16319 		case DL_ENABMULTI_REQ:
16320 		case DL_DISABMULTI_REQ:
16321 			if (!ill->ill_isv6)
16322 				ipsq_current_finish(ipsq);
16323 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16324 			break;
16325 		case DL_PROMISCON_REQ:
16326 		case DL_PROMISCOFF_REQ:
16327 		case DL_UNBIND_REQ:
16328 		case DL_ATTACH_REQ:
16329 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16330 			break;
16331 		}
16332 		break;
16333 	default:
16334 		break;
16335 	}
16336 
16337 	freemsg(mp);
16338 	if (mp1 == NULL)
16339 		return;
16340 
16341 	/*
16342 	 * The operation must complete without EINPROGRESS since
16343 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
16344 	 * the operation will be stuck forever inside the IPSQ.
16345 	 */
16346 	ASSERT(err != EINPROGRESS);
16347 
16348 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
16349 	case 0:
16350 		ipsq_current_finish(ipsq);
16351 		break;
16352 
16353 	case SIOCSLIFNAME:
16354 	case IF_UNITSEL: {
16355 		ill_t *ill_other = ILL_OTHER(ill);
16356 
16357 		/*
16358 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
16359 		 * ill has a peer which is in an IPMP group, then place ill
16360 		 * into the same group.  One catch: although ifconfig plumbs
16361 		 * the appropriate IPMP meta-interface prior to plumbing this
16362 		 * ill, it is possible for multiple ifconfig applications to
16363 		 * race (or for another application to adjust plumbing), in
16364 		 * which case the IPMP meta-interface we need will be missing.
16365 		 * If so, kick the phyint out of the group.
16366 		 */
16367 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
16368 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
16369 			ipmp_illgrp_t	*illg;
16370 
16371 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
16372 			if (illg == NULL)
16373 				ipmp_phyint_leave_grp(ill->ill_phyint);
16374 			else
16375 				ipmp_ill_join_illgrp(ill, illg);
16376 		}
16377 
16378 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
16379 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16380 		else
16381 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16382 		break;
16383 	}
16384 	case SIOCLIFADDIF:
16385 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16386 		break;
16387 
16388 	default:
16389 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16390 		break;
16391 	}
16392 }
16393 
16394 /*
16395  * ip_rput_other is called by ip_rput to handle messages modifying the global
16396  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16397  */
16398 /* ARGSUSED */
16399 void
16400 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16401 {
16402 	ill_t		*ill = q->q_ptr;
16403 	struct iocblk	*iocp;
16404 	mblk_t		*mp1;
16405 	conn_t		*connp = NULL;
16406 
16407 	ip1dbg(("ip_rput_other "));
16408 	if (ipsq != NULL) {
16409 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16410 		ASSERT(ipsq->ipsq_xop ==
16411 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
16412 	}
16413 
16414 	switch (mp->b_datap->db_type) {
16415 	case M_ERROR:
16416 	case M_HANGUP:
16417 		/*
16418 		 * The device has a problem.  We force the ILL down.  It can
16419 		 * be brought up again manually using SIOCSIFFLAGS (via
16420 		 * ifconfig or equivalent).
16421 		 */
16422 		ASSERT(ipsq != NULL);
16423 		if (mp->b_rptr < mp->b_wptr)
16424 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16425 		if (ill->ill_error == 0)
16426 			ill->ill_error = ENXIO;
16427 		if (!ill_down_start(q, mp))
16428 			return;
16429 		ipif_all_down_tail(ipsq, q, mp, NULL);
16430 		break;
16431 	case M_IOCACK:
16432 		iocp = (struct iocblk *)mp->b_rptr;
16433 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16434 		switch (iocp->ioc_cmd) {
16435 		case SIOCSTUNPARAM:
16436 		case OSIOCSTUNPARAM:
16437 			ASSERT(ipsq != NULL);
16438 			/*
16439 			 * Finish socket ioctl passed through to tun.
16440 			 * We should have an IOCTL waiting on this.
16441 			 */
16442 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16443 			if (ill->ill_isv6) {
16444 				struct iftun_req *ta;
16445 
16446 				/*
16447 				 * if a source or destination is
16448 				 * being set, try and set the link
16449 				 * local address for the tunnel
16450 				 */
16451 				ta = (struct iftun_req *)mp->b_cont->
16452 				    b_cont->b_rptr;
16453 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16454 					ipif_set_tun_llink(ill, ta);
16455 				}
16456 
16457 			}
16458 			if (mp1 != NULL) {
16459 				/*
16460 				 * Now copy back the b_next/b_prev used by
16461 				 * mi code for the mi_copy* functions.
16462 				 * See ip_sioctl_tunparam() for the reason.
16463 				 * Also protect against missing b_cont.
16464 				 */
16465 				if (mp->b_cont != NULL) {
16466 					mp->b_cont->b_next =
16467 					    mp1->b_cont->b_next;
16468 					mp->b_cont->b_prev =
16469 					    mp1->b_cont->b_prev;
16470 				}
16471 				inet_freemsg(mp1);
16472 				ASSERT(connp != NULL);
16473 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16474 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16475 			} else {
16476 				ASSERT(connp == NULL);
16477 				putnext(q, mp);
16478 			}
16479 			break;
16480 		case SIOCGTUNPARAM:
16481 		case OSIOCGTUNPARAM:
16482 			/*
16483 			 * This is really M_IOCDATA from the tunnel driver.
16484 			 * convert back and complete the ioctl.
16485 			 * We should have an IOCTL waiting on this.
16486 			 */
16487 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16488 			if (mp1) {
16489 				/*
16490 				 * Now copy back the b_next/b_prev used by
16491 				 * mi code for the mi_copy* functions.
16492 				 * See ip_sioctl_tunparam() for the reason.
16493 				 * Also protect against missing b_cont.
16494 				 */
16495 				if (mp->b_cont != NULL) {
16496 					mp->b_cont->b_next =
16497 					    mp1->b_cont->b_next;
16498 					mp->b_cont->b_prev =
16499 					    mp1->b_cont->b_prev;
16500 				}
16501 				inet_freemsg(mp1);
16502 				if (iocp->ioc_error == 0)
16503 					mp->b_datap->db_type = M_IOCDATA;
16504 				ASSERT(connp != NULL);
16505 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16506 				    iocp->ioc_error, COPYOUT, NULL);
16507 			} else {
16508 				ASSERT(connp == NULL);
16509 				putnext(q, mp);
16510 			}
16511 			break;
16512 		default:
16513 			break;
16514 		}
16515 		break;
16516 	case M_IOCNAK:
16517 		iocp = (struct iocblk *)mp->b_rptr;
16518 
16519 		switch (iocp->ioc_cmd) {
16520 			int mode;
16521 
16522 		case DL_IOC_HDR_INFO:
16523 			/*
16524 			 * If this was the first attempt, turn off the
16525 			 * fastpath probing.
16526 			 */
16527 			mutex_enter(&ill->ill_lock);
16528 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16529 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16530 				mutex_exit(&ill->ill_lock);
16531 				ill_fastpath_nack(ill);
16532 				ip1dbg(("ip_rput: DLPI fastpath off on "
16533 				    "interface %s\n",
16534 				    ill->ill_name));
16535 			} else {
16536 				mutex_exit(&ill->ill_lock);
16537 			}
16538 			freemsg(mp);
16539 			break;
16540 			case SIOCSTUNPARAM:
16541 		case OSIOCSTUNPARAM:
16542 			ASSERT(ipsq != NULL);
16543 			/*
16544 			 * Finish socket ioctl passed through to tun
16545 			 * We should have an IOCTL waiting on this.
16546 			 */
16547 			/* FALLTHRU */
16548 		case SIOCGTUNPARAM:
16549 		case OSIOCGTUNPARAM:
16550 			/*
16551 			 * This is really M_IOCDATA from the tunnel driver.
16552 			 * convert back and complete the ioctl.
16553 			 * We should have an IOCTL waiting on this.
16554 			 */
16555 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16556 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16557 				mp1 = ill_pending_mp_get(ill, &connp,
16558 				    iocp->ioc_id);
16559 				mode = COPYOUT;
16560 				ipsq = NULL;
16561 			} else {
16562 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16563 				mode = NO_COPYOUT;
16564 			}
16565 			if (mp1 != NULL) {
16566 				/*
16567 				 * Now copy back the b_next/b_prev used by
16568 				 * mi code for the mi_copy* functions.
16569 				 * See ip_sioctl_tunparam() for the reason.
16570 				 * Also protect against missing b_cont.
16571 				 */
16572 				if (mp->b_cont != NULL) {
16573 					mp->b_cont->b_next =
16574 					    mp1->b_cont->b_next;
16575 					mp->b_cont->b_prev =
16576 					    mp1->b_cont->b_prev;
16577 				}
16578 				inet_freemsg(mp1);
16579 				if (iocp->ioc_error == 0)
16580 					iocp->ioc_error = EINVAL;
16581 				ASSERT(connp != NULL);
16582 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16583 				    iocp->ioc_error, mode, ipsq);
16584 			} else {
16585 				ASSERT(connp == NULL);
16586 				putnext(q, mp);
16587 			}
16588 			break;
16589 		default:
16590 			break;
16591 		}
16592 	default:
16593 		break;
16594 	}
16595 }
16596 
16597 /*
16598  * NOTE : This function does not ire_refrele the ire argument passed in.
16599  *
16600  * IPQoS notes
16601  * IP policy is invoked twice for a forwarded packet, once on the read side
16602  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16603  * enabled. An additional parameter, in_ill, has been added for this purpose.
16604  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16605  * because ip_mroute drops this information.
16606  *
16607  */
16608 void
16609 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16610 {
16611 	uint32_t	old_pkt_len;
16612 	uint32_t	pkt_len;
16613 	queue_t	*q;
16614 	uint32_t	sum;
16615 #define	rptr	((uchar_t *)ipha)
16616 	uint32_t	max_frag;
16617 	uint32_t	ill_index;
16618 	ill_t		*out_ill;
16619 	mib2_ipIfStatsEntry_t *mibptr;
16620 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16621 
16622 	/* Get the ill_index of the incoming ILL */
16623 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16624 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16625 
16626 	/* Initiate Read side IPPF processing */
16627 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16628 		ip_process(IPP_FWD_IN, &mp, ill_index);
16629 		if (mp == NULL) {
16630 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16631 			    "during IPPF processing\n"));
16632 			return;
16633 		}
16634 	}
16635 
16636 	/* Adjust the checksum to reflect the ttl decrement. */
16637 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16638 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16639 
16640 	if (ipha->ipha_ttl-- <= 1) {
16641 		if (ip_csum_hdr(ipha)) {
16642 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16643 			goto drop_pkt;
16644 		}
16645 		/*
16646 		 * Note: ire_stq this will be NULL for multicast
16647 		 * datagrams using the long path through arp (the IRE
16648 		 * is not an IRE_CACHE). This should not cause
16649 		 * problems since we don't generate ICMP errors for
16650 		 * multicast packets.
16651 		 */
16652 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16653 		q = ire->ire_stq;
16654 		if (q != NULL) {
16655 			/* Sent by forwarding path, and router is global zone */
16656 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16657 			    GLOBAL_ZONEID, ipst);
16658 		} else
16659 			freemsg(mp);
16660 		return;
16661 	}
16662 
16663 	/*
16664 	 * Don't forward if the interface is down
16665 	 */
16666 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16667 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16668 		ip2dbg(("ip_rput_forward:interface is down\n"));
16669 		goto drop_pkt;
16670 	}
16671 
16672 	/* Get the ill_index of the outgoing ILL */
16673 	out_ill = ire_to_ill(ire);
16674 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16675 
16676 	DTRACE_PROBE4(ip4__forwarding__start,
16677 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16678 
16679 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16680 	    ipst->ips_ipv4firewall_forwarding,
16681 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16682 
16683 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16684 
16685 	if (mp == NULL)
16686 		return;
16687 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16688 
16689 	if (is_system_labeled()) {
16690 		mblk_t *mp1;
16691 
16692 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16693 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16694 			goto drop_pkt;
16695 		}
16696 		/* Size may have changed */
16697 		mp = mp1;
16698 		ipha = (ipha_t *)mp->b_rptr;
16699 		pkt_len = ntohs(ipha->ipha_length);
16700 	}
16701 
16702 	/* Check if there are options to update */
16703 	if (!IS_SIMPLE_IPH(ipha)) {
16704 		if (ip_csum_hdr(ipha)) {
16705 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16706 			goto drop_pkt;
16707 		}
16708 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16709 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16710 			return;
16711 		}
16712 
16713 		ipha->ipha_hdr_checksum = 0;
16714 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16715 	}
16716 	max_frag = ire->ire_max_frag;
16717 	if (pkt_len > max_frag) {
16718 		/*
16719 		 * It needs fragging on its way out.  We haven't
16720 		 * verified the header checksum yet.  Since we
16721 		 * are going to put a surely good checksum in the
16722 		 * outgoing header, we have to make sure that it
16723 		 * was good coming in.
16724 		 */
16725 		if (ip_csum_hdr(ipha)) {
16726 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16727 			goto drop_pkt;
16728 		}
16729 		/* Initiate Write side IPPF processing */
16730 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16731 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16732 			if (mp == NULL) {
16733 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16734 				    " during IPPF processing\n"));
16735 				return;
16736 			}
16737 		}
16738 		/*
16739 		 * Handle labeled packet resizing.
16740 		 *
16741 		 * If we have added a label, inform ip_wput_frag() of its
16742 		 * effect on the MTU for ICMP messages.
16743 		 */
16744 		if (pkt_len > old_pkt_len) {
16745 			uint32_t secopt_size;
16746 
16747 			secopt_size = pkt_len - old_pkt_len;
16748 			if (secopt_size < max_frag)
16749 				max_frag -= secopt_size;
16750 		}
16751 
16752 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0,
16753 		    GLOBAL_ZONEID, ipst, NULL);
16754 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16755 		return;
16756 	}
16757 
16758 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16759 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16760 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16761 	    ipst->ips_ipv4firewall_physical_out,
16762 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16763 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16764 	if (mp == NULL)
16765 		return;
16766 
16767 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16768 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16769 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE, NULL);
16770 	/* ip_xmit_v4 always consumes the packet */
16771 	return;
16772 
16773 drop_pkt:;
16774 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16775 	freemsg(mp);
16776 #undef	rptr
16777 }
16778 
16779 void
16780 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16781 {
16782 	ire_t	*ire;
16783 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16784 
16785 	ASSERT(!ipif->ipif_isv6);
16786 	/*
16787 	 * Find an IRE which matches the destination and the outgoing
16788 	 * queue in the cache table. All we need is an IRE_CACHE which
16789 	 * is pointing at ipif->ipif_ill.
16790 	 */
16791 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16792 		dst = ipif->ipif_pp_dst_addr;
16793 
16794 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, msg_getlabel(mp),
16795 	    MATCH_IRE_ILL | MATCH_IRE_SECATTR, ipst);
16796 	if (ire == NULL) {
16797 		/*
16798 		 * Mark this packet to make it be delivered to
16799 		 * ip_rput_forward after the new ire has been
16800 		 * created.
16801 		 */
16802 		mp->b_prev = NULL;
16803 		mp->b_next = mp;
16804 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16805 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16806 	} else {
16807 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16808 		IRE_REFRELE(ire);
16809 	}
16810 }
16811 
16812 /* Update any source route, record route or timestamp options */
16813 static int
16814 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16815 {
16816 	ipoptp_t	opts;
16817 	uchar_t		*opt;
16818 	uint8_t		optval;
16819 	uint8_t		optlen;
16820 	ipaddr_t	dst;
16821 	uint32_t	ts;
16822 	ire_t		*dst_ire = NULL;
16823 	ire_t		*tmp_ire = NULL;
16824 	timestruc_t	now;
16825 
16826 	ip2dbg(("ip_rput_forward_options\n"));
16827 	dst = ipha->ipha_dst;
16828 	for (optval = ipoptp_first(&opts, ipha);
16829 	    optval != IPOPT_EOL;
16830 	    optval = ipoptp_next(&opts)) {
16831 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16832 		opt = opts.ipoptp_cur;
16833 		optlen = opts.ipoptp_len;
16834 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16835 		    optval, opts.ipoptp_len));
16836 		switch (optval) {
16837 			uint32_t off;
16838 		case IPOPT_SSRR:
16839 		case IPOPT_LSRR:
16840 			/* Check if adminstratively disabled */
16841 			if (!ipst->ips_ip_forward_src_routed) {
16842 				if (ire->ire_stq != NULL) {
16843 					/*
16844 					 * Sent by forwarding path, and router
16845 					 * is global zone
16846 					 */
16847 					icmp_unreachable(ire->ire_stq, mp,
16848 					    ICMP_SOURCE_ROUTE_FAILED,
16849 					    GLOBAL_ZONEID, ipst);
16850 				} else {
16851 					ip0dbg(("ip_rput_forward_options: "
16852 					    "unable to send unreach\n"));
16853 					freemsg(mp);
16854 				}
16855 				return (-1);
16856 			}
16857 
16858 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16859 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16860 			if (dst_ire == NULL) {
16861 				/*
16862 				 * Must be partial since ip_rput_options
16863 				 * checked for strict.
16864 				 */
16865 				break;
16866 			}
16867 			off = opt[IPOPT_OFFSET];
16868 			off--;
16869 		redo_srr:
16870 			if (optlen < IP_ADDR_LEN ||
16871 			    off > optlen - IP_ADDR_LEN) {
16872 				/* End of source route */
16873 				ip1dbg((
16874 				    "ip_rput_forward_options: end of SR\n"));
16875 				ire_refrele(dst_ire);
16876 				break;
16877 			}
16878 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16879 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16880 			    IP_ADDR_LEN);
16881 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16882 			    ntohl(dst)));
16883 
16884 			/*
16885 			 * Check if our address is present more than
16886 			 * once as consecutive hops in source route.
16887 			 */
16888 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16889 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16890 			if (tmp_ire != NULL) {
16891 				ire_refrele(tmp_ire);
16892 				off += IP_ADDR_LEN;
16893 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16894 				goto redo_srr;
16895 			}
16896 			ipha->ipha_dst = dst;
16897 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16898 			ire_refrele(dst_ire);
16899 			break;
16900 		case IPOPT_RR:
16901 			off = opt[IPOPT_OFFSET];
16902 			off--;
16903 			if (optlen < IP_ADDR_LEN ||
16904 			    off > optlen - IP_ADDR_LEN) {
16905 				/* No more room - ignore */
16906 				ip1dbg((
16907 				    "ip_rput_forward_options: end of RR\n"));
16908 				break;
16909 			}
16910 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16911 			    IP_ADDR_LEN);
16912 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16913 			break;
16914 		case IPOPT_TS:
16915 			/* Insert timestamp if there is room */
16916 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16917 			case IPOPT_TS_TSONLY:
16918 				off = IPOPT_TS_TIMELEN;
16919 				break;
16920 			case IPOPT_TS_PRESPEC:
16921 			case IPOPT_TS_PRESPEC_RFC791:
16922 				/* Verify that the address matched */
16923 				off = opt[IPOPT_OFFSET] - 1;
16924 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16925 				dst_ire = ire_ctable_lookup(dst, 0,
16926 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16927 				    MATCH_IRE_TYPE, ipst);
16928 				if (dst_ire == NULL) {
16929 					/* Not for us */
16930 					break;
16931 				}
16932 				ire_refrele(dst_ire);
16933 				/* FALLTHRU */
16934 			case IPOPT_TS_TSANDADDR:
16935 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16936 				break;
16937 			default:
16938 				/*
16939 				 * ip_*put_options should have already
16940 				 * dropped this packet.
16941 				 */
16942 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16943 				    "unknown IT - bug in ip_rput_options?\n");
16944 				return (0);	/* Keep "lint" happy */
16945 			}
16946 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16947 				/* Increase overflow counter */
16948 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16949 				opt[IPOPT_POS_OV_FLG] =
16950 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16951 				    (off << 4));
16952 				break;
16953 			}
16954 			off = opt[IPOPT_OFFSET] - 1;
16955 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16956 			case IPOPT_TS_PRESPEC:
16957 			case IPOPT_TS_PRESPEC_RFC791:
16958 			case IPOPT_TS_TSANDADDR:
16959 				bcopy(&ire->ire_src_addr,
16960 				    (char *)opt + off, IP_ADDR_LEN);
16961 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16962 				/* FALLTHRU */
16963 			case IPOPT_TS_TSONLY:
16964 				off = opt[IPOPT_OFFSET] - 1;
16965 				/* Compute # of milliseconds since midnight */
16966 				gethrestime(&now);
16967 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16968 				    now.tv_nsec / (NANOSEC / MILLISEC);
16969 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16970 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16971 				break;
16972 			}
16973 			break;
16974 		}
16975 	}
16976 	return (0);
16977 }
16978 
16979 /*
16980  * This is called after processing at least one of AH/ESP headers.
16981  *
16982  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16983  * the actual, physical interface on which the packet was received,
16984  * but, when ip_strict_dst_multihoming is set to 1, could be the
16985  * interface which had the ipha_dst configured when the packet went
16986  * through ip_rput. The ill_index corresponding to the recv_ill
16987  * is saved in ipsec_in_rill_index
16988  *
16989  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16990  * cannot assume "ire" points to valid data for any IPv6 cases.
16991  */
16992 void
16993 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16994 {
16995 	mblk_t *mp;
16996 	ipaddr_t dst;
16997 	in6_addr_t *v6dstp;
16998 	ipha_t *ipha;
16999 	ip6_t *ip6h;
17000 	ipsec_in_t *ii;
17001 	boolean_t ill_need_rele = B_FALSE;
17002 	boolean_t rill_need_rele = B_FALSE;
17003 	boolean_t ire_need_rele = B_FALSE;
17004 	netstack_t	*ns;
17005 	ip_stack_t	*ipst;
17006 
17007 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
17008 	ASSERT(ii->ipsec_in_ill_index != 0);
17009 	ns = ii->ipsec_in_ns;
17010 	ASSERT(ii->ipsec_in_ns != NULL);
17011 	ipst = ns->netstack_ip;
17012 
17013 	mp = ipsec_mp->b_cont;
17014 	ASSERT(mp != NULL);
17015 
17016 	if (ill == NULL) {
17017 		ASSERT(recv_ill == NULL);
17018 		/*
17019 		 * We need to get the original queue on which ip_rput_local
17020 		 * or ip_rput_data_v6 was called.
17021 		 */
17022 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
17023 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
17024 		ill_need_rele = B_TRUE;
17025 
17026 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
17027 			recv_ill = ill_lookup_on_ifindex(
17028 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
17029 			    NULL, NULL, NULL, NULL, ipst);
17030 			rill_need_rele = B_TRUE;
17031 		} else {
17032 			recv_ill = ill;
17033 		}
17034 
17035 		if ((ill == NULL) || (recv_ill == NULL)) {
17036 			ip0dbg(("ip_fanout_proto_again: interface "
17037 			    "disappeared\n"));
17038 			if (ill != NULL)
17039 				ill_refrele(ill);
17040 			if (recv_ill != NULL)
17041 				ill_refrele(recv_ill);
17042 			freemsg(ipsec_mp);
17043 			return;
17044 		}
17045 	}
17046 
17047 	ASSERT(ill != NULL && recv_ill != NULL);
17048 
17049 	if (mp->b_datap->db_type == M_CTL) {
17050 		/*
17051 		 * AH/ESP is returning the ICMP message after
17052 		 * removing their headers. Fanout again till
17053 		 * it gets to the right protocol.
17054 		 */
17055 		if (ii->ipsec_in_v4) {
17056 			icmph_t *icmph;
17057 			int iph_hdr_length;
17058 			int hdr_length;
17059 
17060 			ipha = (ipha_t *)mp->b_rptr;
17061 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17062 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17063 			ipha = (ipha_t *)&icmph[1];
17064 			hdr_length = IPH_HDR_LENGTH(ipha);
17065 			/*
17066 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17067 			 * Reset the type to M_DATA.
17068 			 */
17069 			mp->b_datap->db_type = M_DATA;
17070 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17071 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17072 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17073 		} else {
17074 			icmp6_t *icmp6;
17075 			int hdr_length;
17076 
17077 			ip6h = (ip6_t *)mp->b_rptr;
17078 			/* Don't call hdr_length_v6() unless you have to. */
17079 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17080 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17081 			else
17082 				hdr_length = IPV6_HDR_LEN;
17083 
17084 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17085 			/*
17086 			 * icmp_inbound_error_fanout_v6 may need to do
17087 			 * pullupmsg.  Reset the type to M_DATA.
17088 			 */
17089 			mp->b_datap->db_type = M_DATA;
17090 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17091 			    ip6h, icmp6, ill, recv_ill, B_TRUE,
17092 			    ii->ipsec_in_zoneid);
17093 		}
17094 		if (ill_need_rele)
17095 			ill_refrele(ill);
17096 		if (rill_need_rele)
17097 			ill_refrele(recv_ill);
17098 		return;
17099 	}
17100 
17101 	if (ii->ipsec_in_v4) {
17102 		ipha = (ipha_t *)mp->b_rptr;
17103 		dst = ipha->ipha_dst;
17104 		if (CLASSD(dst)) {
17105 			/*
17106 			 * Multicast has to be delivered to all streams.
17107 			 */
17108 			dst = INADDR_BROADCAST;
17109 		}
17110 
17111 		if (ire == NULL) {
17112 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17113 			    msg_getlabel(mp), ipst);
17114 			if (ire == NULL) {
17115 				if (ill_need_rele)
17116 					ill_refrele(ill);
17117 				if (rill_need_rele)
17118 					ill_refrele(recv_ill);
17119 				ip1dbg(("ip_fanout_proto_again: "
17120 				    "IRE not found"));
17121 				freemsg(ipsec_mp);
17122 				return;
17123 			}
17124 			ire_need_rele = B_TRUE;
17125 		}
17126 
17127 		switch (ipha->ipha_protocol) {
17128 		case IPPROTO_UDP:
17129 			ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17130 			    recv_ill);
17131 			if (ire_need_rele)
17132 				ire_refrele(ire);
17133 			break;
17134 		case IPPROTO_TCP:
17135 			if (!ire_need_rele)
17136 				IRE_REFHOLD(ire);
17137 			mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17138 			    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17139 			IRE_REFRELE(ire);
17140 			if (mp != NULL) {
17141 				SQUEUE_ENTER(GET_SQUEUE(mp), mp,
17142 				    mp, 1, SQ_PROCESS,
17143 				    SQTAG_IP_PROTO_AGAIN);
17144 			}
17145 			break;
17146 		case IPPROTO_SCTP:
17147 			if (!ire_need_rele)
17148 				IRE_REFHOLD(ire);
17149 			ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17150 			    ipsec_mp, 0, ill->ill_rq, dst);
17151 			break;
17152 		default:
17153 			ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17154 			    recv_ill, 0);
17155 			if (ire_need_rele)
17156 				ire_refrele(ire);
17157 			break;
17158 		}
17159 	} else {
17160 		uint32_t rput_flags = 0;
17161 
17162 		ip6h = (ip6_t *)mp->b_rptr;
17163 		v6dstp = &ip6h->ip6_dst;
17164 		/*
17165 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17166 		 * address.
17167 		 *
17168 		 * Currently, we don't store that state in the IPSEC_IN
17169 		 * message, and we may need to.
17170 		 */
17171 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17172 		    IP6_IN_LLMCAST : 0);
17173 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17174 		    NULL, NULL);
17175 	}
17176 	if (ill_need_rele)
17177 		ill_refrele(ill);
17178 	if (rill_need_rele)
17179 		ill_refrele(recv_ill);
17180 }
17181 
17182 /*
17183  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17184  * returns 'true' if there are still fragments left on the queue, in
17185  * which case we restart the timer.
17186  */
17187 void
17188 ill_frag_timer(void *arg)
17189 {
17190 	ill_t	*ill = (ill_t *)arg;
17191 	boolean_t frag_pending;
17192 	ip_stack_t	*ipst = ill->ill_ipst;
17193 
17194 	mutex_enter(&ill->ill_lock);
17195 	ASSERT(!ill->ill_fragtimer_executing);
17196 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17197 		ill->ill_frag_timer_id = 0;
17198 		mutex_exit(&ill->ill_lock);
17199 		return;
17200 	}
17201 	ill->ill_fragtimer_executing = 1;
17202 	mutex_exit(&ill->ill_lock);
17203 
17204 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17205 
17206 	/*
17207 	 * Restart the timer, if we have fragments pending or if someone
17208 	 * wanted us to be scheduled again.
17209 	 */
17210 	mutex_enter(&ill->ill_lock);
17211 	ill->ill_fragtimer_executing = 0;
17212 	ill->ill_frag_timer_id = 0;
17213 	if (frag_pending || ill->ill_fragtimer_needrestart)
17214 		ill_frag_timer_start(ill);
17215 	mutex_exit(&ill->ill_lock);
17216 }
17217 
17218 void
17219 ill_frag_timer_start(ill_t *ill)
17220 {
17221 	ip_stack_t	*ipst = ill->ill_ipst;
17222 
17223 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17224 
17225 	/* If the ill is closing or opening don't proceed */
17226 	if (ill->ill_state_flags & ILL_CONDEMNED)
17227 		return;
17228 
17229 	if (ill->ill_fragtimer_executing) {
17230 		/*
17231 		 * ill_frag_timer is currently executing. Just record the
17232 		 * the fact that we want the timer to be restarted.
17233 		 * ill_frag_timer will post a timeout before it returns,
17234 		 * ensuring it will be called again.
17235 		 */
17236 		ill->ill_fragtimer_needrestart = 1;
17237 		return;
17238 	}
17239 
17240 	if (ill->ill_frag_timer_id == 0) {
17241 		/*
17242 		 * The timer is neither running nor is the timeout handler
17243 		 * executing. Post a timeout so that ill_frag_timer will be
17244 		 * called
17245 		 */
17246 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17247 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17248 		ill->ill_fragtimer_needrestart = 0;
17249 	}
17250 }
17251 
17252 /*
17253  * This routine is needed for loopback when forwarding multicasts.
17254  *
17255  * IPQoS Notes:
17256  * IPPF processing is done in fanout routines.
17257  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17258  * processing for IPsec packets is done when it comes back in clear.
17259  * NOTE : The callers of this function need to do the ire_refrele for the
17260  *	  ire that is being passed in.
17261  */
17262 void
17263 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17264     ill_t *recv_ill, uint32_t esp_udp_ports)
17265 {
17266 	boolean_t esp_in_udp_packet = (esp_udp_ports != 0);
17267 	ill_t	*ill = (ill_t *)q->q_ptr;
17268 	uint32_t	sum;
17269 	uint32_t	u1;
17270 	uint32_t	u2;
17271 	int		hdr_length;
17272 	boolean_t	mctl_present;
17273 	mblk_t		*first_mp = mp;
17274 	mblk_t		*hada_mp = NULL;
17275 	ipha_t		*inner_ipha;
17276 	ip_stack_t	*ipst;
17277 
17278 	ASSERT(recv_ill != NULL);
17279 	ipst = recv_ill->ill_ipst;
17280 
17281 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17282 	    "ip_rput_locl_start: q %p", q);
17283 
17284 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17285 	ASSERT(ill != NULL);
17286 
17287 #define	rptr	((uchar_t *)ipha)
17288 #define	iphs	((uint16_t *)ipha)
17289 
17290 	/*
17291 	 * no UDP or TCP packet should come here anymore.
17292 	 */
17293 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17294 	    ipha->ipha_protocol != IPPROTO_UDP);
17295 
17296 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17297 	if (mctl_present &&
17298 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17299 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17300 
17301 		/*
17302 		 * It's an IPsec accelerated packet.
17303 		 * Keep a pointer to the data attributes around until
17304 		 * we allocate the ipsec_info_t.
17305 		 */
17306 		IPSECHW_DEBUG(IPSECHW_PKT,
17307 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17308 		hada_mp = first_mp;
17309 		hada_mp->b_cont = NULL;
17310 		/*
17311 		 * Since it is accelerated, it comes directly from
17312 		 * the ill and the data attributes is followed by
17313 		 * the packet data.
17314 		 */
17315 		ASSERT(mp->b_datap->db_type != M_CTL);
17316 		first_mp = mp;
17317 		mctl_present = B_FALSE;
17318 	}
17319 
17320 	/*
17321 	 * IF M_CTL is not present, then ipsec_in_is_secure
17322 	 * should return B_TRUE. There is a case where loopback
17323 	 * packets has an M_CTL in the front with all the
17324 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17325 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17326 	 * packets never comes here, it is safe to ASSERT the
17327 	 * following.
17328 	 */
17329 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17330 
17331 	/*
17332 	 * Also, we should never have an mctl_present if this is an
17333 	 * ESP-in-UDP packet.
17334 	 */
17335 	ASSERT(!mctl_present || !esp_in_udp_packet);
17336 
17337 	/* u1 is # words of IP options */
17338 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17339 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17340 
17341 	/*
17342 	 * Don't verify header checksum if we just removed UDP header or
17343 	 * packet is coming back from AH/ESP.
17344 	 */
17345 	if (!esp_in_udp_packet && !mctl_present) {
17346 		if (u1) {
17347 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17348 				if (hada_mp != NULL)
17349 					freemsg(hada_mp);
17350 				return;
17351 			}
17352 		} else {
17353 			/* Check the IP header checksum.  */
17354 #define	uph	((uint16_t *)ipha)
17355 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17356 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17357 #undef  uph
17358 			/* finish doing IP checksum */
17359 			sum = (sum & 0xFFFF) + (sum >> 16);
17360 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17361 			if (sum && sum != 0xFFFF) {
17362 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17363 				goto drop_pkt;
17364 			}
17365 		}
17366 	}
17367 
17368 	/*
17369 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17370 	 * might be called more than once for secure packets, count only
17371 	 * the first time.
17372 	 */
17373 	if (!mctl_present) {
17374 		UPDATE_IB_PKT_COUNT(ire);
17375 		ire->ire_last_used_time = lbolt;
17376 	}
17377 
17378 	/* Check for fragmentation offset. */
17379 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17380 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17381 	if (u1) {
17382 		/*
17383 		 * We re-assemble fragments before we do the AH/ESP
17384 		 * processing. Thus, M_CTL should not be present
17385 		 * while we are re-assembling.
17386 		 */
17387 		ASSERT(!mctl_present);
17388 		ASSERT(first_mp == mp);
17389 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
17390 			return;
17391 
17392 		/*
17393 		 * Make sure that first_mp points back to mp as
17394 		 * the mp we came in with could have changed in
17395 		 * ip_rput_fragment().
17396 		 */
17397 		ipha = (ipha_t *)mp->b_rptr;
17398 		first_mp = mp;
17399 	}
17400 
17401 	/*
17402 	 * Clear hardware checksumming flag as it is currently only
17403 	 * used by TCP and UDP.
17404 	 */
17405 	DB_CKSUMFLAGS(mp) = 0;
17406 
17407 	/* Now we have a complete datagram, destined for this machine. */
17408 	u1 = IPH_HDR_LENGTH(ipha);
17409 	switch (ipha->ipha_protocol) {
17410 	case IPPROTO_ICMP: {
17411 		ire_t		*ire_zone;
17412 		ilm_t		*ilm;
17413 		mblk_t		*mp1;
17414 		zoneid_t	last_zoneid;
17415 		ilm_walker_t	ilw;
17416 
17417 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17418 			ASSERT(ire->ire_type == IRE_BROADCAST);
17419 
17420 			/*
17421 			 * In the multicast case, applications may have joined
17422 			 * the group from different zones, so we need to deliver
17423 			 * the packet to each of them. Loop through the
17424 			 * multicast memberships structures (ilm) on the receive
17425 			 * ill and send a copy of the packet up each matching
17426 			 * one. However, we don't do this for multicasts sent on
17427 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17428 			 * they must stay in the sender's zone.
17429 			 *
17430 			 * ilm_add_v6() ensures that ilms in the same zone are
17431 			 * contiguous in the ill_ilm list. We use this property
17432 			 * to avoid sending duplicates needed when two
17433 			 * applications in the same zone join the same group on
17434 			 * different logical interfaces: we ignore the ilm if
17435 			 * its zoneid is the same as the last matching one.
17436 			 * In addition, the sending of the packet for
17437 			 * ire_zoneid is delayed until all of the other ilms
17438 			 * have been exhausted.
17439 			 */
17440 			last_zoneid = -1;
17441 			ilm = ilm_walker_start(&ilw, recv_ill);
17442 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
17443 				if (ipha->ipha_dst != ilm->ilm_addr ||
17444 				    ilm->ilm_zoneid == last_zoneid ||
17445 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17446 				    ilm->ilm_zoneid == ALL_ZONES ||
17447 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17448 					continue;
17449 				mp1 = ip_copymsg(first_mp);
17450 				if (mp1 == NULL)
17451 					continue;
17452 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
17453 				    0, sum, mctl_present, B_TRUE,
17454 				    recv_ill, ilm->ilm_zoneid);
17455 				last_zoneid = ilm->ilm_zoneid;
17456 			}
17457 			ilm_walker_finish(&ilw);
17458 		} else if (ire->ire_type == IRE_BROADCAST) {
17459 			/*
17460 			 * In the broadcast case, there may be many zones
17461 			 * which need a copy of the packet delivered to them.
17462 			 * There is one IRE_BROADCAST per broadcast address
17463 			 * and per zone; we walk those using a helper function.
17464 			 * In addition, the sending of the packet for ire is
17465 			 * delayed until all of the other ires have been
17466 			 * processed.
17467 			 */
17468 			IRB_REFHOLD(ire->ire_bucket);
17469 			ire_zone = NULL;
17470 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17471 			    ire)) != NULL) {
17472 				mp1 = ip_copymsg(first_mp);
17473 				if (mp1 == NULL)
17474 					continue;
17475 
17476 				UPDATE_IB_PKT_COUNT(ire_zone);
17477 				ire_zone->ire_last_used_time = lbolt;
17478 				icmp_inbound(q, mp1, B_TRUE, ill,
17479 				    0, sum, mctl_present, B_TRUE,
17480 				    recv_ill, ire_zone->ire_zoneid);
17481 			}
17482 			IRB_REFRELE(ire->ire_bucket);
17483 		}
17484 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17485 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17486 		    ire->ire_zoneid);
17487 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17488 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17489 		return;
17490 	}
17491 	case IPPROTO_IGMP:
17492 		/*
17493 		 * If we are not willing to accept IGMP packets in clear,
17494 		 * then check with global policy.
17495 		 */
17496 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17497 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17498 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17499 			if (first_mp == NULL)
17500 				return;
17501 		}
17502 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17503 			freemsg(first_mp);
17504 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17505 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17506 			return;
17507 		}
17508 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17509 			/* Bad packet - discarded by igmp_input */
17510 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17511 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17512 			if (mctl_present)
17513 				freeb(first_mp);
17514 			return;
17515 		}
17516 		/*
17517 		 * igmp_input() may have returned the pulled up message.
17518 		 * So first_mp and ipha need to be reinitialized.
17519 		 */
17520 		ipha = (ipha_t *)mp->b_rptr;
17521 		if (mctl_present)
17522 			first_mp->b_cont = mp;
17523 		else
17524 			first_mp = mp;
17525 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17526 		    connf_head != NULL) {
17527 			/* No user-level listener for IGMP packets */
17528 			goto drop_pkt;
17529 		}
17530 		/* deliver to local raw users */
17531 		break;
17532 	case IPPROTO_PIM:
17533 		/*
17534 		 * If we are not willing to accept PIM packets in clear,
17535 		 * then check with global policy.
17536 		 */
17537 		if (ipst->ips_pim_accept_clear_messages == 0) {
17538 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17539 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17540 			if (first_mp == NULL)
17541 				return;
17542 		}
17543 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17544 			freemsg(first_mp);
17545 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17546 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17547 			return;
17548 		}
17549 		if (pim_input(q, mp, ill) != 0) {
17550 			/* Bad packet - discarded by pim_input */
17551 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17552 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17553 			if (mctl_present)
17554 				freeb(first_mp);
17555 			return;
17556 		}
17557 
17558 		/*
17559 		 * pim_input() may have pulled up the message so ipha needs to
17560 		 * be reinitialized.
17561 		 */
17562 		ipha = (ipha_t *)mp->b_rptr;
17563 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17564 		    connf_head != NULL) {
17565 			/* No user-level listener for PIM packets */
17566 			goto drop_pkt;
17567 		}
17568 		/* deliver to local raw users */
17569 		break;
17570 	case IPPROTO_ENCAP:
17571 		/*
17572 		 * Handle self-encapsulated packets (IP-in-IP where
17573 		 * the inner addresses == the outer addresses).
17574 		 */
17575 		hdr_length = IPH_HDR_LENGTH(ipha);
17576 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17577 		    mp->b_wptr) {
17578 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17579 			    sizeof (ipha_t) - mp->b_rptr)) {
17580 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17581 				freemsg(first_mp);
17582 				return;
17583 			}
17584 			ipha = (ipha_t *)mp->b_rptr;
17585 		}
17586 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17587 		/*
17588 		 * Check the sanity of the inner IP header.
17589 		 */
17590 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17591 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17592 			freemsg(first_mp);
17593 			return;
17594 		}
17595 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17596 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17597 			freemsg(first_mp);
17598 			return;
17599 		}
17600 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17601 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17602 			ipsec_in_t *ii;
17603 
17604 			/*
17605 			 * Self-encapsulated tunnel packet. Remove
17606 			 * the outer IP header and fanout again.
17607 			 * We also need to make sure that the inner
17608 			 * header is pulled up until options.
17609 			 */
17610 			mp->b_rptr = (uchar_t *)inner_ipha;
17611 			ipha = inner_ipha;
17612 			hdr_length = IPH_HDR_LENGTH(ipha);
17613 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17614 				if (!pullupmsg(mp, (uchar_t *)ipha +
17615 				    + hdr_length - mp->b_rptr)) {
17616 					freemsg(first_mp);
17617 					return;
17618 				}
17619 				ipha = (ipha_t *)mp->b_rptr;
17620 			}
17621 			if (hdr_length > sizeof (ipha_t)) {
17622 				/* We got options on the inner packet. */
17623 				ipaddr_t dst = ipha->ipha_dst;
17624 
17625 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17626 				    -1) {
17627 					/* Bad options! */
17628 					return;
17629 				}
17630 				if (dst != ipha->ipha_dst) {
17631 					/*
17632 					 * Someone put a source-route in
17633 					 * the inside header of a self-
17634 					 * encapsulated packet.  Drop it
17635 					 * with extreme prejudice and let
17636 					 * the sender know.
17637 					 */
17638 					icmp_unreachable(q, first_mp,
17639 					    ICMP_SOURCE_ROUTE_FAILED,
17640 					    recv_ill->ill_zoneid, ipst);
17641 					return;
17642 				}
17643 			}
17644 			if (!mctl_present) {
17645 				ASSERT(first_mp == mp);
17646 				/*
17647 				 * This means that somebody is sending
17648 				 * Self-encapsualted packets without AH/ESP.
17649 				 * If AH/ESP was present, we would have already
17650 				 * allocated the first_mp.
17651 				 *
17652 				 * Send this packet to find a tunnel endpoint.
17653 				 * if I can't find one, an ICMP
17654 				 * PROTOCOL_UNREACHABLE will get sent.
17655 				 */
17656 				goto fanout;
17657 			}
17658 			/*
17659 			 * We generally store the ill_index if we need to
17660 			 * do IPsec processing as we lose the ill queue when
17661 			 * we come back. But in this case, we never should
17662 			 * have to store the ill_index here as it should have
17663 			 * been stored previously when we processed the
17664 			 * AH/ESP header in this routine or for non-ipsec
17665 			 * cases, we still have the queue. But for some bad
17666 			 * packets from the wire, we can get to IPsec after
17667 			 * this and we better store the index for that case.
17668 			 */
17669 			ill = (ill_t *)q->q_ptr;
17670 			ii = (ipsec_in_t *)first_mp->b_rptr;
17671 			ii->ipsec_in_ill_index =
17672 			    ill->ill_phyint->phyint_ifindex;
17673 			ii->ipsec_in_rill_index =
17674 			    recv_ill->ill_phyint->phyint_ifindex;
17675 			if (ii->ipsec_in_decaps) {
17676 				/*
17677 				 * This packet is self-encapsulated multiple
17678 				 * times. We don't want to recurse infinitely.
17679 				 * To keep it simple, drop the packet.
17680 				 */
17681 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17682 				freemsg(first_mp);
17683 				return;
17684 			}
17685 			ii->ipsec_in_decaps = B_TRUE;
17686 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17687 			    ire);
17688 			return;
17689 		}
17690 		break;
17691 	case IPPROTO_AH:
17692 	case IPPROTO_ESP: {
17693 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17694 
17695 		/*
17696 		 * Fast path for AH/ESP. If this is the first time
17697 		 * we are sending a datagram to AH/ESP, allocate
17698 		 * a IPSEC_IN message and prepend it. Otherwise,
17699 		 * just fanout.
17700 		 */
17701 
17702 		int ipsec_rc;
17703 		ipsec_in_t *ii;
17704 		netstack_t *ns = ipst->ips_netstack;
17705 
17706 		IP_STAT(ipst, ipsec_proto_ahesp);
17707 		if (!mctl_present) {
17708 			ASSERT(first_mp == mp);
17709 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17710 			if (first_mp == NULL) {
17711 				ip1dbg(("ip_proto_input: IPSEC_IN "
17712 				    "allocation failure.\n"));
17713 				freemsg(hada_mp); /* okay ifnull */
17714 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17715 				freemsg(mp);
17716 				return;
17717 			}
17718 			/*
17719 			 * Store the ill_index so that when we come back
17720 			 * from IPsec we ride on the same queue.
17721 			 */
17722 			ill = (ill_t *)q->q_ptr;
17723 			ii = (ipsec_in_t *)first_mp->b_rptr;
17724 			ii->ipsec_in_ill_index =
17725 			    ill->ill_phyint->phyint_ifindex;
17726 			ii->ipsec_in_rill_index =
17727 			    recv_ill->ill_phyint->phyint_ifindex;
17728 			first_mp->b_cont = mp;
17729 			/*
17730 			 * Cache hardware acceleration info.
17731 			 */
17732 			if (hada_mp != NULL) {
17733 				IPSECHW_DEBUG(IPSECHW_PKT,
17734 				    ("ip_rput_local: caching data attr.\n"));
17735 				ii->ipsec_in_accelerated = B_TRUE;
17736 				ii->ipsec_in_da = hada_mp;
17737 				hada_mp = NULL;
17738 			}
17739 		} else {
17740 			ii = (ipsec_in_t *)first_mp->b_rptr;
17741 		}
17742 
17743 		ii->ipsec_in_esp_udp_ports = esp_udp_ports;
17744 
17745 		if (!ipsec_loaded(ipss)) {
17746 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17747 			    ire->ire_zoneid, ipst);
17748 			return;
17749 		}
17750 
17751 		ns = ipst->ips_netstack;
17752 		/* select inbound SA and have IPsec process the pkt */
17753 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17754 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17755 			boolean_t esp_in_udp_sa;
17756 			if (esph == NULL)
17757 				return;
17758 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17759 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17760 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17761 			    IPSA_F_NATT) != 0);
17762 			/*
17763 			 * The following is a fancy, but quick, way of saying:
17764 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17765 			 *    OR
17766 			 * ESP SA and ESP-in-UDP packet --> drop
17767 			 */
17768 			if (esp_in_udp_sa != esp_in_udp_packet) {
17769 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17770 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17771 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17772 				    &ns->netstack_ipsec->ipsec_dropper);
17773 				return;
17774 			}
17775 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17776 			    first_mp, esph);
17777 		} else {
17778 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17779 			if (ah == NULL)
17780 				return;
17781 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17782 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17783 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17784 			    first_mp, ah);
17785 		}
17786 
17787 		switch (ipsec_rc) {
17788 		case IPSEC_STATUS_SUCCESS:
17789 			break;
17790 		case IPSEC_STATUS_FAILED:
17791 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17792 			/* FALLTHRU */
17793 		case IPSEC_STATUS_PENDING:
17794 			return;
17795 		}
17796 		/* we're done with IPsec processing, send it up */
17797 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17798 		return;
17799 	}
17800 	default:
17801 		break;
17802 	}
17803 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17804 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17805 		    ire->ire_zoneid));
17806 		goto drop_pkt;
17807 	}
17808 	/*
17809 	 * Handle protocols with which IP is less intimate.  There
17810 	 * can be more than one stream bound to a particular
17811 	 * protocol.  When this is the case, each one gets a copy
17812 	 * of any incoming packets.
17813 	 */
17814 fanout:
17815 	ip_fanout_proto(q, first_mp, ill, ipha,
17816 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17817 	    B_TRUE, recv_ill, ire->ire_zoneid);
17818 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17819 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17820 	return;
17821 
17822 drop_pkt:
17823 	freemsg(first_mp);
17824 	if (hada_mp != NULL)
17825 		freeb(hada_mp);
17826 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17827 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17828 #undef	rptr
17829 #undef  iphs
17830 
17831 }
17832 
17833 /*
17834  * Update any source route, record route or timestamp options.
17835  * Check that we are at end of strict source route.
17836  * The options have already been checked for sanity in ip_rput_options().
17837  */
17838 static boolean_t
17839 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17840     ip_stack_t *ipst)
17841 {
17842 	ipoptp_t	opts;
17843 	uchar_t		*opt;
17844 	uint8_t		optval;
17845 	uint8_t		optlen;
17846 	ipaddr_t	dst;
17847 	uint32_t	ts;
17848 	ire_t		*dst_ire;
17849 	timestruc_t	now;
17850 	zoneid_t	zoneid;
17851 	ill_t		*ill;
17852 
17853 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17854 
17855 	ip2dbg(("ip_rput_local_options\n"));
17856 
17857 	for (optval = ipoptp_first(&opts, ipha);
17858 	    optval != IPOPT_EOL;
17859 	    optval = ipoptp_next(&opts)) {
17860 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17861 		opt = opts.ipoptp_cur;
17862 		optlen = opts.ipoptp_len;
17863 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17864 		    optval, optlen));
17865 		switch (optval) {
17866 			uint32_t off;
17867 		case IPOPT_SSRR:
17868 		case IPOPT_LSRR:
17869 			off = opt[IPOPT_OFFSET];
17870 			off--;
17871 			if (optlen < IP_ADDR_LEN ||
17872 			    off > optlen - IP_ADDR_LEN) {
17873 				/* End of source route */
17874 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17875 				break;
17876 			}
17877 			/*
17878 			 * This will only happen if two consecutive entries
17879 			 * in the source route contains our address or if
17880 			 * it is a packet with a loose source route which
17881 			 * reaches us before consuming the whole source route
17882 			 */
17883 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17884 			if (optval == IPOPT_SSRR) {
17885 				goto bad_src_route;
17886 			}
17887 			/*
17888 			 * Hack: instead of dropping the packet truncate the
17889 			 * source route to what has been used by filling the
17890 			 * rest with IPOPT_NOP.
17891 			 */
17892 			opt[IPOPT_OLEN] = (uint8_t)off;
17893 			while (off < optlen) {
17894 				opt[off++] = IPOPT_NOP;
17895 			}
17896 			break;
17897 		case IPOPT_RR:
17898 			off = opt[IPOPT_OFFSET];
17899 			off--;
17900 			if (optlen < IP_ADDR_LEN ||
17901 			    off > optlen - IP_ADDR_LEN) {
17902 				/* No more room - ignore */
17903 				ip1dbg((
17904 				    "ip_rput_local_options: end of RR\n"));
17905 				break;
17906 			}
17907 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17908 			    IP_ADDR_LEN);
17909 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17910 			break;
17911 		case IPOPT_TS:
17912 			/* Insert timestamp if there is romm */
17913 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17914 			case IPOPT_TS_TSONLY:
17915 				off = IPOPT_TS_TIMELEN;
17916 				break;
17917 			case IPOPT_TS_PRESPEC:
17918 			case IPOPT_TS_PRESPEC_RFC791:
17919 				/* Verify that the address matched */
17920 				off = opt[IPOPT_OFFSET] - 1;
17921 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17922 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17923 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17924 				    ipst);
17925 				if (dst_ire == NULL) {
17926 					/* Not for us */
17927 					break;
17928 				}
17929 				ire_refrele(dst_ire);
17930 				/* FALLTHRU */
17931 			case IPOPT_TS_TSANDADDR:
17932 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17933 				break;
17934 			default:
17935 				/*
17936 				 * ip_*put_options should have already
17937 				 * dropped this packet.
17938 				 */
17939 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17940 				    "unknown IT - bug in ip_rput_options?\n");
17941 				return (B_TRUE);	/* Keep "lint" happy */
17942 			}
17943 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17944 				/* Increase overflow counter */
17945 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17946 				opt[IPOPT_POS_OV_FLG] =
17947 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17948 				    (off << 4));
17949 				break;
17950 			}
17951 			off = opt[IPOPT_OFFSET] - 1;
17952 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17953 			case IPOPT_TS_PRESPEC:
17954 			case IPOPT_TS_PRESPEC_RFC791:
17955 			case IPOPT_TS_TSANDADDR:
17956 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17957 				    IP_ADDR_LEN);
17958 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17959 				/* FALLTHRU */
17960 			case IPOPT_TS_TSONLY:
17961 				off = opt[IPOPT_OFFSET] - 1;
17962 				/* Compute # of milliseconds since midnight */
17963 				gethrestime(&now);
17964 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17965 				    now.tv_nsec / (NANOSEC / MILLISEC);
17966 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17967 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17968 				break;
17969 			}
17970 			break;
17971 		}
17972 	}
17973 	return (B_TRUE);
17974 
17975 bad_src_route:
17976 	q = WR(q);
17977 	if (q->q_next != NULL)
17978 		ill = q->q_ptr;
17979 	else
17980 		ill = NULL;
17981 
17982 	/* make sure we clear any indication of a hardware checksum */
17983 	DB_CKSUMFLAGS(mp) = 0;
17984 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17985 	if (zoneid == ALL_ZONES)
17986 		freemsg(mp);
17987 	else
17988 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17989 	return (B_FALSE);
17990 
17991 }
17992 
17993 /*
17994  * Process IP options in an inbound packet.  If an option affects the
17995  * effective destination address, return the next hop address via dstp.
17996  * Returns -1 if something fails in which case an ICMP error has been sent
17997  * and mp freed.
17998  */
17999 static int
18000 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
18001     ip_stack_t *ipst)
18002 {
18003 	ipoptp_t	opts;
18004 	uchar_t		*opt;
18005 	uint8_t		optval;
18006 	uint8_t		optlen;
18007 	ipaddr_t	dst;
18008 	intptr_t	code = 0;
18009 	ire_t		*ire = NULL;
18010 	zoneid_t	zoneid;
18011 	ill_t		*ill;
18012 
18013 	ip2dbg(("ip_rput_options\n"));
18014 	dst = ipha->ipha_dst;
18015 	for (optval = ipoptp_first(&opts, ipha);
18016 	    optval != IPOPT_EOL;
18017 	    optval = ipoptp_next(&opts)) {
18018 		opt = opts.ipoptp_cur;
18019 		optlen = opts.ipoptp_len;
18020 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
18021 		    optval, optlen));
18022 		/*
18023 		 * Note: we need to verify the checksum before we
18024 		 * modify anything thus this routine only extracts the next
18025 		 * hop dst from any source route.
18026 		 */
18027 		switch (optval) {
18028 			uint32_t off;
18029 		case IPOPT_SSRR:
18030 		case IPOPT_LSRR:
18031 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18032 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18033 			if (ire == NULL) {
18034 				if (optval == IPOPT_SSRR) {
18035 					ip1dbg(("ip_rput_options: not next"
18036 					    " strict source route 0x%x\n",
18037 					    ntohl(dst)));
18038 					code = (char *)&ipha->ipha_dst -
18039 					    (char *)ipha;
18040 					goto param_prob; /* RouterReq's */
18041 				}
18042 				ip2dbg(("ip_rput_options: "
18043 				    "not next source route 0x%x\n",
18044 				    ntohl(dst)));
18045 				break;
18046 			}
18047 			ire_refrele(ire);
18048 
18049 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18050 				ip1dbg((
18051 				    "ip_rput_options: bad option offset\n"));
18052 				code = (char *)&opt[IPOPT_OLEN] -
18053 				    (char *)ipha;
18054 				goto param_prob;
18055 			}
18056 			off = opt[IPOPT_OFFSET];
18057 			off--;
18058 		redo_srr:
18059 			if (optlen < IP_ADDR_LEN ||
18060 			    off > optlen - IP_ADDR_LEN) {
18061 				/* End of source route */
18062 				ip1dbg(("ip_rput_options: end of SR\n"));
18063 				break;
18064 			}
18065 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18066 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18067 			    ntohl(dst)));
18068 
18069 			/*
18070 			 * Check if our address is present more than
18071 			 * once as consecutive hops in source route.
18072 			 * XXX verify per-interface ip_forwarding
18073 			 * for source route?
18074 			 */
18075 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18076 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18077 
18078 			if (ire != NULL) {
18079 				ire_refrele(ire);
18080 				off += IP_ADDR_LEN;
18081 				goto redo_srr;
18082 			}
18083 
18084 			if (dst == htonl(INADDR_LOOPBACK)) {
18085 				ip1dbg(("ip_rput_options: loopback addr in "
18086 				    "source route!\n"));
18087 				goto bad_src_route;
18088 			}
18089 			/*
18090 			 * For strict: verify that dst is directly
18091 			 * reachable.
18092 			 */
18093 			if (optval == IPOPT_SSRR) {
18094 				ire = ire_ftable_lookup(dst, 0, 0,
18095 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18096 				    msg_getlabel(mp),
18097 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18098 				if (ire == NULL) {
18099 					ip1dbg(("ip_rput_options: SSRR not "
18100 					    "directly reachable: 0x%x\n",
18101 					    ntohl(dst)));
18102 					goto bad_src_route;
18103 				}
18104 				ire_refrele(ire);
18105 			}
18106 			/*
18107 			 * Defer update of the offset and the record route
18108 			 * until the packet is forwarded.
18109 			 */
18110 			break;
18111 		case IPOPT_RR:
18112 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18113 				ip1dbg((
18114 				    "ip_rput_options: bad option offset\n"));
18115 				code = (char *)&opt[IPOPT_OLEN] -
18116 				    (char *)ipha;
18117 				goto param_prob;
18118 			}
18119 			break;
18120 		case IPOPT_TS:
18121 			/*
18122 			 * Verify that length >= 5 and that there is either
18123 			 * room for another timestamp or that the overflow
18124 			 * counter is not maxed out.
18125 			 */
18126 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18127 			if (optlen < IPOPT_MINLEN_IT) {
18128 				goto param_prob;
18129 			}
18130 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18131 				ip1dbg((
18132 				    "ip_rput_options: bad option offset\n"));
18133 				code = (char *)&opt[IPOPT_OFFSET] -
18134 				    (char *)ipha;
18135 				goto param_prob;
18136 			}
18137 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18138 			case IPOPT_TS_TSONLY:
18139 				off = IPOPT_TS_TIMELEN;
18140 				break;
18141 			case IPOPT_TS_TSANDADDR:
18142 			case IPOPT_TS_PRESPEC:
18143 			case IPOPT_TS_PRESPEC_RFC791:
18144 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18145 				break;
18146 			default:
18147 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18148 				    (char *)ipha;
18149 				goto param_prob;
18150 			}
18151 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18152 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18153 				/*
18154 				 * No room and the overflow counter is 15
18155 				 * already.
18156 				 */
18157 				goto param_prob;
18158 			}
18159 			break;
18160 		}
18161 	}
18162 
18163 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18164 		*dstp = dst;
18165 		return (0);
18166 	}
18167 
18168 	ip1dbg(("ip_rput_options: error processing IP options."));
18169 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18170 
18171 param_prob:
18172 	q = WR(q);
18173 	if (q->q_next != NULL)
18174 		ill = q->q_ptr;
18175 	else
18176 		ill = NULL;
18177 
18178 	/* make sure we clear any indication of a hardware checksum */
18179 	DB_CKSUMFLAGS(mp) = 0;
18180 	/* Don't know whether this is for non-global or global/forwarding */
18181 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18182 	if (zoneid == ALL_ZONES)
18183 		freemsg(mp);
18184 	else
18185 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18186 	return (-1);
18187 
18188 bad_src_route:
18189 	q = WR(q);
18190 	if (q->q_next != NULL)
18191 		ill = q->q_ptr;
18192 	else
18193 		ill = NULL;
18194 
18195 	/* make sure we clear any indication of a hardware checksum */
18196 	DB_CKSUMFLAGS(mp) = 0;
18197 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18198 	if (zoneid == ALL_ZONES)
18199 		freemsg(mp);
18200 	else
18201 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18202 	return (-1);
18203 }
18204 
18205 /*
18206  * IP & ICMP info in >=14 msg's ...
18207  *  - ip fixed part (mib2_ip_t)
18208  *  - icmp fixed part (mib2_icmp_t)
18209  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18210  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18211  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18212  *  - ipRouteAttributeTable (ip 102)	labeled routes
18213  *  - ip multicast membership (ip_member_t)
18214  *  - ip multicast source filtering (ip_grpsrc_t)
18215  *  - igmp fixed part (struct igmpstat)
18216  *  - multicast routing stats (struct mrtstat)
18217  *  - multicast routing vifs (array of struct vifctl)
18218  *  - multicast routing routes (array of struct mfcctl)
18219  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18220  *					One per ill plus one generic
18221  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18222  *					One per ill plus one generic
18223  *  - ipv6RouteEntry			all IPv6 IREs
18224  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18225  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18226  *  - ipv6AddrEntry			all IPv6 ipifs
18227  *  - ipv6 multicast membership (ipv6_member_t)
18228  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18229  *
18230  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18231  *
18232  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18233  * already filled in by the caller.
18234  * Return value of 0 indicates that no messages were sent and caller
18235  * should free mpctl.
18236  */
18237 int
18238 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18239 {
18240 	ip_stack_t *ipst;
18241 	sctp_stack_t *sctps;
18242 
18243 	if (q->q_next != NULL) {
18244 		ipst = ILLQ_TO_IPST(q);
18245 	} else {
18246 		ipst = CONNQ_TO_IPST(q);
18247 	}
18248 	ASSERT(ipst != NULL);
18249 	sctps = ipst->ips_netstack->netstack_sctp;
18250 
18251 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18252 		return (0);
18253 	}
18254 
18255 	/*
18256 	 * For the purposes of the (broken) packet shell use
18257 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18258 	 * to make TCP and UDP appear first in the list of mib items.
18259 	 * TBD: We could expand this and use it in netstat so that
18260 	 * the kernel doesn't have to produce large tables (connections,
18261 	 * routes, etc) when netstat only wants the statistics or a particular
18262 	 * table.
18263 	 */
18264 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18265 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18266 			return (1);
18267 		}
18268 	}
18269 
18270 	if (level != MIB2_TCP) {
18271 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18272 			return (1);
18273 		}
18274 	}
18275 
18276 	if (level != MIB2_UDP) {
18277 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18278 			return (1);
18279 		}
18280 	}
18281 
18282 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18283 	    ipst)) == NULL) {
18284 		return (1);
18285 	}
18286 
18287 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18288 		return (1);
18289 	}
18290 
18291 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18292 		return (1);
18293 	}
18294 
18295 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18296 		return (1);
18297 	}
18298 
18299 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18300 		return (1);
18301 	}
18302 
18303 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18304 		return (1);
18305 	}
18306 
18307 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18308 		return (1);
18309 	}
18310 
18311 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18312 		return (1);
18313 	}
18314 
18315 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18316 		return (1);
18317 	}
18318 
18319 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18320 		return (1);
18321 	}
18322 
18323 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18324 		return (1);
18325 	}
18326 
18327 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18328 		return (1);
18329 	}
18330 
18331 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18332 		return (1);
18333 	}
18334 
18335 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18336 		return (1);
18337 	}
18338 
18339 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
18340 	if (mpctl == NULL)
18341 		return (1);
18342 
18343 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
18344 	if (mpctl == NULL)
18345 		return (1);
18346 
18347 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18348 		return (1);
18349 	}
18350 	freemsg(mpctl);
18351 	return (1);
18352 }
18353 
18354 /* Get global (legacy) IPv4 statistics */
18355 static mblk_t *
18356 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18357     ip_stack_t *ipst)
18358 {
18359 	mib2_ip_t		old_ip_mib;
18360 	struct opthdr		*optp;
18361 	mblk_t			*mp2ctl;
18362 
18363 	/*
18364 	 * make a copy of the original message
18365 	 */
18366 	mp2ctl = copymsg(mpctl);
18367 
18368 	/* fixed length IP structure... */
18369 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18370 	optp->level = MIB2_IP;
18371 	optp->name = 0;
18372 	SET_MIB(old_ip_mib.ipForwarding,
18373 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18374 	SET_MIB(old_ip_mib.ipDefaultTTL,
18375 	    (uint32_t)ipst->ips_ip_def_ttl);
18376 	SET_MIB(old_ip_mib.ipReasmTimeout,
18377 	    ipst->ips_ip_g_frag_timeout);
18378 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18379 	    sizeof (mib2_ipAddrEntry_t));
18380 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18381 	    sizeof (mib2_ipRouteEntry_t));
18382 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18383 	    sizeof (mib2_ipNetToMediaEntry_t));
18384 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18385 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18386 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18387 	    sizeof (mib2_ipAttributeEntry_t));
18388 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18389 
18390 	/*
18391 	 * Grab the statistics from the new IP MIB
18392 	 */
18393 	SET_MIB(old_ip_mib.ipInReceives,
18394 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18395 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18396 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18397 	SET_MIB(old_ip_mib.ipForwDatagrams,
18398 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18399 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18400 	    ipmib->ipIfStatsInUnknownProtos);
18401 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18402 	SET_MIB(old_ip_mib.ipInDelivers,
18403 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18404 	SET_MIB(old_ip_mib.ipOutRequests,
18405 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18406 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18407 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18408 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18409 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18410 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18411 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18412 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18413 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18414 
18415 	/* ipRoutingDiscards is not being used */
18416 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18417 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18418 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18419 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18420 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18421 	    ipmib->ipIfStatsReasmDuplicates);
18422 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18423 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18424 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18425 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18426 	SET_MIB(old_ip_mib.rawipInOverflows,
18427 	    ipmib->rawipIfStatsInOverflows);
18428 
18429 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18430 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18431 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18432 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18433 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18434 	    ipmib->ipIfStatsOutSwitchIPVersion);
18435 
18436 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18437 	    (int)sizeof (old_ip_mib))) {
18438 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18439 		    (uint_t)sizeof (old_ip_mib)));
18440 	}
18441 
18442 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18443 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18444 	    (int)optp->level, (int)optp->name, (int)optp->len));
18445 	qreply(q, mpctl);
18446 	return (mp2ctl);
18447 }
18448 
18449 /* Per interface IPv4 statistics */
18450 static mblk_t *
18451 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18452 {
18453 	struct opthdr		*optp;
18454 	mblk_t			*mp2ctl;
18455 	ill_t			*ill;
18456 	ill_walk_context_t	ctx;
18457 	mblk_t			*mp_tail = NULL;
18458 	mib2_ipIfStatsEntry_t	global_ip_mib;
18459 
18460 	/*
18461 	 * Make a copy of the original message
18462 	 */
18463 	mp2ctl = copymsg(mpctl);
18464 
18465 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18466 	optp->level = MIB2_IP;
18467 	optp->name = MIB2_IP_TRAFFIC_STATS;
18468 	/* Include "unknown interface" ip_mib */
18469 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18470 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18471 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18472 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18473 	    (ipst->ips_ip_g_forward ? 1 : 2));
18474 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18475 	    (uint32_t)ipst->ips_ip_def_ttl);
18476 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18477 	    sizeof (mib2_ipIfStatsEntry_t));
18478 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18479 	    sizeof (mib2_ipAddrEntry_t));
18480 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18481 	    sizeof (mib2_ipRouteEntry_t));
18482 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18483 	    sizeof (mib2_ipNetToMediaEntry_t));
18484 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18485 	    sizeof (ip_member_t));
18486 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18487 	    sizeof (ip_grpsrc_t));
18488 
18489 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18490 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18491 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18492 		    "failed to allocate %u bytes\n",
18493 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18494 	}
18495 
18496 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18497 
18498 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18499 	ill = ILL_START_WALK_V4(&ctx, ipst);
18500 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18501 		ill->ill_ip_mib->ipIfStatsIfIndex =
18502 		    ill->ill_phyint->phyint_ifindex;
18503 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18504 		    (ipst->ips_ip_g_forward ? 1 : 2));
18505 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18506 		    (uint32_t)ipst->ips_ip_def_ttl);
18507 
18508 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18509 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18510 		    (char *)ill->ill_ip_mib,
18511 		    (int)sizeof (*ill->ill_ip_mib))) {
18512 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18513 			    "failed to allocate %u bytes\n",
18514 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18515 		}
18516 	}
18517 	rw_exit(&ipst->ips_ill_g_lock);
18518 
18519 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18520 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18521 	    "level %d, name %d, len %d\n",
18522 	    (int)optp->level, (int)optp->name, (int)optp->len));
18523 	qreply(q, mpctl);
18524 
18525 	if (mp2ctl == NULL)
18526 		return (NULL);
18527 
18528 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18529 }
18530 
18531 /* Global IPv4 ICMP statistics */
18532 static mblk_t *
18533 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18534 {
18535 	struct opthdr		*optp;
18536 	mblk_t			*mp2ctl;
18537 
18538 	/*
18539 	 * Make a copy of the original message
18540 	 */
18541 	mp2ctl = copymsg(mpctl);
18542 
18543 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18544 	optp->level = MIB2_ICMP;
18545 	optp->name = 0;
18546 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18547 	    (int)sizeof (ipst->ips_icmp_mib))) {
18548 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18549 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18550 	}
18551 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18552 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18553 	    (int)optp->level, (int)optp->name, (int)optp->len));
18554 	qreply(q, mpctl);
18555 	return (mp2ctl);
18556 }
18557 
18558 /* Global IPv4 IGMP statistics */
18559 static mblk_t *
18560 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18561 {
18562 	struct opthdr		*optp;
18563 	mblk_t			*mp2ctl;
18564 
18565 	/*
18566 	 * make a copy of the original message
18567 	 */
18568 	mp2ctl = copymsg(mpctl);
18569 
18570 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18571 	optp->level = EXPER_IGMP;
18572 	optp->name = 0;
18573 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18574 	    (int)sizeof (ipst->ips_igmpstat))) {
18575 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18576 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18577 	}
18578 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18579 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18580 	    (int)optp->level, (int)optp->name, (int)optp->len));
18581 	qreply(q, mpctl);
18582 	return (mp2ctl);
18583 }
18584 
18585 /* Global IPv4 Multicast Routing statistics */
18586 static mblk_t *
18587 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18588 {
18589 	struct opthdr		*optp;
18590 	mblk_t			*mp2ctl;
18591 
18592 	/*
18593 	 * make a copy of the original message
18594 	 */
18595 	mp2ctl = copymsg(mpctl);
18596 
18597 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18598 	optp->level = EXPER_DVMRP;
18599 	optp->name = 0;
18600 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18601 		ip0dbg(("ip_mroute_stats: failed\n"));
18602 	}
18603 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18604 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18605 	    (int)optp->level, (int)optp->name, (int)optp->len));
18606 	qreply(q, mpctl);
18607 	return (mp2ctl);
18608 }
18609 
18610 /* IPv4 address information */
18611 static mblk_t *
18612 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18613 {
18614 	struct opthdr		*optp;
18615 	mblk_t			*mp2ctl;
18616 	mblk_t			*mp_tail = NULL;
18617 	ill_t			*ill;
18618 	ipif_t			*ipif;
18619 	uint_t			bitval;
18620 	mib2_ipAddrEntry_t	mae;
18621 	zoneid_t		zoneid;
18622 	ill_walk_context_t ctx;
18623 
18624 	/*
18625 	 * make a copy of the original message
18626 	 */
18627 	mp2ctl = copymsg(mpctl);
18628 
18629 	/* ipAddrEntryTable */
18630 
18631 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18632 	optp->level = MIB2_IP;
18633 	optp->name = MIB2_IP_ADDR;
18634 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18635 
18636 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18637 	ill = ILL_START_WALK_V4(&ctx, ipst);
18638 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18639 		for (ipif = ill->ill_ipif; ipif != NULL;
18640 		    ipif = ipif->ipif_next) {
18641 			if (ipif->ipif_zoneid != zoneid &&
18642 			    ipif->ipif_zoneid != ALL_ZONES)
18643 				continue;
18644 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18645 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18646 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18647 
18648 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18649 			    OCTET_LENGTH);
18650 			mae.ipAdEntIfIndex.o_length =
18651 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18652 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18653 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18654 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18655 			mae.ipAdEntInfo.ae_subnet_len =
18656 			    ip_mask_to_plen(ipif->ipif_net_mask);
18657 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18658 			for (bitval = 1;
18659 			    bitval &&
18660 			    !(bitval & ipif->ipif_brd_addr);
18661 			    bitval <<= 1)
18662 				noop;
18663 			mae.ipAdEntBcastAddr = bitval;
18664 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18665 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18666 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18667 			mae.ipAdEntInfo.ae_broadcast_addr =
18668 			    ipif->ipif_brd_addr;
18669 			mae.ipAdEntInfo.ae_pp_dst_addr =
18670 			    ipif->ipif_pp_dst_addr;
18671 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18672 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18673 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18674 
18675 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18676 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18677 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18678 				    "allocate %u bytes\n",
18679 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18680 			}
18681 		}
18682 	}
18683 	rw_exit(&ipst->ips_ill_g_lock);
18684 
18685 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18686 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18687 	    (int)optp->level, (int)optp->name, (int)optp->len));
18688 	qreply(q, mpctl);
18689 	return (mp2ctl);
18690 }
18691 
18692 /* IPv6 address information */
18693 static mblk_t *
18694 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18695 {
18696 	struct opthdr		*optp;
18697 	mblk_t			*mp2ctl;
18698 	mblk_t			*mp_tail = NULL;
18699 	ill_t			*ill;
18700 	ipif_t			*ipif;
18701 	mib2_ipv6AddrEntry_t	mae6;
18702 	zoneid_t		zoneid;
18703 	ill_walk_context_t	ctx;
18704 
18705 	/*
18706 	 * make a copy of the original message
18707 	 */
18708 	mp2ctl = copymsg(mpctl);
18709 
18710 	/* ipv6AddrEntryTable */
18711 
18712 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18713 	optp->level = MIB2_IP6;
18714 	optp->name = MIB2_IP6_ADDR;
18715 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18716 
18717 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18718 	ill = ILL_START_WALK_V6(&ctx, ipst);
18719 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18720 		for (ipif = ill->ill_ipif; ipif != NULL;
18721 		    ipif = ipif->ipif_next) {
18722 			if (ipif->ipif_zoneid != zoneid &&
18723 			    ipif->ipif_zoneid != ALL_ZONES)
18724 				continue;
18725 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18726 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18727 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18728 
18729 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18730 			    OCTET_LENGTH);
18731 			mae6.ipv6AddrIfIndex.o_length =
18732 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18733 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18734 			mae6.ipv6AddrPfxLength =
18735 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18736 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18737 			mae6.ipv6AddrInfo.ae_subnet_len =
18738 			    mae6.ipv6AddrPfxLength;
18739 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18740 
18741 			/* Type: stateless(1), stateful(2), unknown(3) */
18742 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18743 				mae6.ipv6AddrType = 1;
18744 			else
18745 				mae6.ipv6AddrType = 2;
18746 			/* Anycast: true(1), false(2) */
18747 			if (ipif->ipif_flags & IPIF_ANYCAST)
18748 				mae6.ipv6AddrAnycastFlag = 1;
18749 			else
18750 				mae6.ipv6AddrAnycastFlag = 2;
18751 
18752 			/*
18753 			 * Address status: preferred(1), deprecated(2),
18754 			 * invalid(3), inaccessible(4), unknown(5)
18755 			 */
18756 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18757 				mae6.ipv6AddrStatus = 3;
18758 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18759 				mae6.ipv6AddrStatus = 2;
18760 			else
18761 				mae6.ipv6AddrStatus = 1;
18762 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18763 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18764 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18765 			    ipif->ipif_v6pp_dst_addr;
18766 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18767 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18768 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18769 			mae6.ipv6AddrIdentifier = ill->ill_token;
18770 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18771 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18772 			mae6.ipv6AddrRetransmitTime =
18773 			    ill->ill_reachable_retrans_time;
18774 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18775 			    (char *)&mae6,
18776 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18777 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18778 				    "allocate %u bytes\n",
18779 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18780 			}
18781 		}
18782 	}
18783 	rw_exit(&ipst->ips_ill_g_lock);
18784 
18785 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18786 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18787 	    (int)optp->level, (int)optp->name, (int)optp->len));
18788 	qreply(q, mpctl);
18789 	return (mp2ctl);
18790 }
18791 
18792 /* IPv4 multicast group membership. */
18793 static mblk_t *
18794 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18795 {
18796 	struct opthdr		*optp;
18797 	mblk_t			*mp2ctl;
18798 	ill_t			*ill;
18799 	ipif_t			*ipif;
18800 	ilm_t			*ilm;
18801 	ip_member_t		ipm;
18802 	mblk_t			*mp_tail = NULL;
18803 	ill_walk_context_t	ctx;
18804 	zoneid_t		zoneid;
18805 	ilm_walker_t		ilw;
18806 
18807 	/*
18808 	 * make a copy of the original message
18809 	 */
18810 	mp2ctl = copymsg(mpctl);
18811 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18812 
18813 	/* ipGroupMember table */
18814 	optp = (struct opthdr *)&mpctl->b_rptr[
18815 	    sizeof (struct T_optmgmt_ack)];
18816 	optp->level = MIB2_IP;
18817 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18818 
18819 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18820 	ill = ILL_START_WALK_V4(&ctx, ipst);
18821 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18822 		if (IS_UNDER_IPMP(ill))
18823 			continue;
18824 
18825 		ilm = ilm_walker_start(&ilw, ill);
18826 		for (ipif = ill->ill_ipif; ipif != NULL;
18827 		    ipif = ipif->ipif_next) {
18828 			if (ipif->ipif_zoneid != zoneid &&
18829 			    ipif->ipif_zoneid != ALL_ZONES)
18830 				continue;	/* not this zone */
18831 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18832 			    OCTET_LENGTH);
18833 			ipm.ipGroupMemberIfIndex.o_length =
18834 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18835 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18836 				ASSERT(ilm->ilm_ipif != NULL);
18837 				ASSERT(ilm->ilm_ill == NULL);
18838 				if (ilm->ilm_ipif != ipif)
18839 					continue;
18840 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18841 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18842 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18843 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18844 				    (char *)&ipm, (int)sizeof (ipm))) {
18845 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18846 					    "failed to allocate %u bytes\n",
18847 					    (uint_t)sizeof (ipm)));
18848 				}
18849 			}
18850 		}
18851 		ilm_walker_finish(&ilw);
18852 	}
18853 	rw_exit(&ipst->ips_ill_g_lock);
18854 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18855 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18856 	    (int)optp->level, (int)optp->name, (int)optp->len));
18857 	qreply(q, mpctl);
18858 	return (mp2ctl);
18859 }
18860 
18861 /* IPv6 multicast group membership. */
18862 static mblk_t *
18863 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18864 {
18865 	struct opthdr		*optp;
18866 	mblk_t			*mp2ctl;
18867 	ill_t			*ill;
18868 	ilm_t			*ilm;
18869 	ipv6_member_t		ipm6;
18870 	mblk_t			*mp_tail = NULL;
18871 	ill_walk_context_t	ctx;
18872 	zoneid_t		zoneid;
18873 	ilm_walker_t		ilw;
18874 
18875 	/*
18876 	 * make a copy of the original message
18877 	 */
18878 	mp2ctl = copymsg(mpctl);
18879 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18880 
18881 	/* ip6GroupMember table */
18882 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18883 	optp->level = MIB2_IP6;
18884 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18885 
18886 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18887 	ill = ILL_START_WALK_V6(&ctx, ipst);
18888 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18889 		if (IS_UNDER_IPMP(ill))
18890 			continue;
18891 
18892 		ilm = ilm_walker_start(&ilw, ill);
18893 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18894 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18895 			ASSERT(ilm->ilm_ipif == NULL);
18896 			ASSERT(ilm->ilm_ill != NULL);
18897 			if (ilm->ilm_zoneid != zoneid)
18898 				continue;	/* not this zone */
18899 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18900 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18901 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18902 			if (!snmp_append_data2(mpctl->b_cont,
18903 			    &mp_tail,
18904 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18905 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18906 				    "failed to allocate %u bytes\n",
18907 				    (uint_t)sizeof (ipm6)));
18908 			}
18909 		}
18910 		ilm_walker_finish(&ilw);
18911 	}
18912 	rw_exit(&ipst->ips_ill_g_lock);
18913 
18914 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18915 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18916 	    (int)optp->level, (int)optp->name, (int)optp->len));
18917 	qreply(q, mpctl);
18918 	return (mp2ctl);
18919 }
18920 
18921 /* IP multicast filtered sources */
18922 static mblk_t *
18923 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18924 {
18925 	struct opthdr		*optp;
18926 	mblk_t			*mp2ctl;
18927 	ill_t			*ill;
18928 	ipif_t			*ipif;
18929 	ilm_t			*ilm;
18930 	ip_grpsrc_t		ips;
18931 	mblk_t			*mp_tail = NULL;
18932 	ill_walk_context_t	ctx;
18933 	zoneid_t		zoneid;
18934 	int			i;
18935 	slist_t			*sl;
18936 	ilm_walker_t		ilw;
18937 
18938 	/*
18939 	 * make a copy of the original message
18940 	 */
18941 	mp2ctl = copymsg(mpctl);
18942 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18943 
18944 	/* ipGroupSource table */
18945 	optp = (struct opthdr *)&mpctl->b_rptr[
18946 	    sizeof (struct T_optmgmt_ack)];
18947 	optp->level = MIB2_IP;
18948 	optp->name = EXPER_IP_GROUP_SOURCES;
18949 
18950 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18951 	ill = ILL_START_WALK_V4(&ctx, ipst);
18952 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18953 		if (IS_UNDER_IPMP(ill))
18954 			continue;
18955 
18956 		ilm = ilm_walker_start(&ilw, ill);
18957 		for (ipif = ill->ill_ipif; ipif != NULL;
18958 		    ipif = ipif->ipif_next) {
18959 			if (ipif->ipif_zoneid != zoneid)
18960 				continue;	/* not this zone */
18961 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18962 			    OCTET_LENGTH);
18963 			ips.ipGroupSourceIfIndex.o_length =
18964 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18965 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18966 				ASSERT(ilm->ilm_ipif != NULL);
18967 				ASSERT(ilm->ilm_ill == NULL);
18968 				sl = ilm->ilm_filter;
18969 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18970 					continue;
18971 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18972 				for (i = 0; i < sl->sl_numsrc; i++) {
18973 					if (!IN6_IS_ADDR_V4MAPPED(
18974 					    &sl->sl_addr[i]))
18975 						continue;
18976 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18977 					    ips.ipGroupSourceAddress);
18978 					if (snmp_append_data2(mpctl->b_cont,
18979 					    &mp_tail, (char *)&ips,
18980 					    (int)sizeof (ips)) == 0) {
18981 						ip1dbg(("ip_snmp_get_mib2_"
18982 						    "ip_group_src: failed to "
18983 						    "allocate %u bytes\n",
18984 						    (uint_t)sizeof (ips)));
18985 					}
18986 				}
18987 			}
18988 		}
18989 		ilm_walker_finish(&ilw);
18990 	}
18991 	rw_exit(&ipst->ips_ill_g_lock);
18992 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18993 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18994 	    (int)optp->level, (int)optp->name, (int)optp->len));
18995 	qreply(q, mpctl);
18996 	return (mp2ctl);
18997 }
18998 
18999 /* IPv6 multicast filtered sources. */
19000 static mblk_t *
19001 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19002 {
19003 	struct opthdr		*optp;
19004 	mblk_t			*mp2ctl;
19005 	ill_t			*ill;
19006 	ilm_t			*ilm;
19007 	ipv6_grpsrc_t		ips6;
19008 	mblk_t			*mp_tail = NULL;
19009 	ill_walk_context_t	ctx;
19010 	zoneid_t		zoneid;
19011 	int			i;
19012 	slist_t			*sl;
19013 	ilm_walker_t		ilw;
19014 
19015 	/*
19016 	 * make a copy of the original message
19017 	 */
19018 	mp2ctl = copymsg(mpctl);
19019 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19020 
19021 	/* ip6GroupMember table */
19022 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19023 	optp->level = MIB2_IP6;
19024 	optp->name = EXPER_IP6_GROUP_SOURCES;
19025 
19026 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19027 	ill = ILL_START_WALK_V6(&ctx, ipst);
19028 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19029 		if (IS_UNDER_IPMP(ill))
19030 			continue;
19031 
19032 		ilm = ilm_walker_start(&ilw, ill);
19033 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
19034 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19035 			ASSERT(ilm->ilm_ipif == NULL);
19036 			ASSERT(ilm->ilm_ill != NULL);
19037 			sl = ilm->ilm_filter;
19038 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
19039 				continue;
19040 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
19041 			for (i = 0; i < sl->sl_numsrc; i++) {
19042 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
19043 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19044 				    (char *)&ips6, (int)sizeof (ips6))) {
19045 					ip1dbg(("ip_snmp_get_mib2_ip6_"
19046 					    "group_src: failed to allocate "
19047 					    "%u bytes\n",
19048 					    (uint_t)sizeof (ips6)));
19049 				}
19050 			}
19051 		}
19052 		ilm_walker_finish(&ilw);
19053 	}
19054 	rw_exit(&ipst->ips_ill_g_lock);
19055 
19056 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19057 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19058 	    (int)optp->level, (int)optp->name, (int)optp->len));
19059 	qreply(q, mpctl);
19060 	return (mp2ctl);
19061 }
19062 
19063 /* Multicast routing virtual interface table. */
19064 static mblk_t *
19065 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19066 {
19067 	struct opthdr		*optp;
19068 	mblk_t			*mp2ctl;
19069 
19070 	/*
19071 	 * make a copy of the original message
19072 	 */
19073 	mp2ctl = copymsg(mpctl);
19074 
19075 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19076 	optp->level = EXPER_DVMRP;
19077 	optp->name = EXPER_DVMRP_VIF;
19078 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
19079 		ip0dbg(("ip_mroute_vif: failed\n"));
19080 	}
19081 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19082 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19083 	    (int)optp->level, (int)optp->name, (int)optp->len));
19084 	qreply(q, mpctl);
19085 	return (mp2ctl);
19086 }
19087 
19088 /* Multicast routing table. */
19089 static mblk_t *
19090 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19091 {
19092 	struct opthdr		*optp;
19093 	mblk_t			*mp2ctl;
19094 
19095 	/*
19096 	 * make a copy of the original message
19097 	 */
19098 	mp2ctl = copymsg(mpctl);
19099 
19100 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19101 	optp->level = EXPER_DVMRP;
19102 	optp->name = EXPER_DVMRP_MRT;
19103 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19104 		ip0dbg(("ip_mroute_mrt: failed\n"));
19105 	}
19106 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19107 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19108 	    (int)optp->level, (int)optp->name, (int)optp->len));
19109 	qreply(q, mpctl);
19110 	return (mp2ctl);
19111 }
19112 
19113 /*
19114  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19115  * in one IRE walk.
19116  */
19117 static mblk_t *
19118 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
19119     ip_stack_t *ipst)
19120 {
19121 	struct opthdr	*optp;
19122 	mblk_t		*mp2ctl;	/* Returned */
19123 	mblk_t		*mp3ctl;	/* nettomedia */
19124 	mblk_t		*mp4ctl;	/* routeattrs */
19125 	iproutedata_t	ird;
19126 	zoneid_t	zoneid;
19127 
19128 	/*
19129 	 * make copies of the original message
19130 	 *	- mp2ctl is returned unchanged to the caller for his use
19131 	 *	- mpctl is sent upstream as ipRouteEntryTable
19132 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19133 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19134 	 */
19135 	mp2ctl = copymsg(mpctl);
19136 	mp3ctl = copymsg(mpctl);
19137 	mp4ctl = copymsg(mpctl);
19138 	if (mp3ctl == NULL || mp4ctl == NULL) {
19139 		freemsg(mp4ctl);
19140 		freemsg(mp3ctl);
19141 		freemsg(mp2ctl);
19142 		freemsg(mpctl);
19143 		return (NULL);
19144 	}
19145 
19146 	bzero(&ird, sizeof (ird));
19147 
19148 	ird.ird_route.lp_head = mpctl->b_cont;
19149 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19150 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19151 	/*
19152 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19153 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19154 	 * intended a temporary solution until a proper MIB API is provided
19155 	 * that provides complete filtering/caller-opt-in.
19156 	 */
19157 	if (level == EXPER_IP_AND_TESTHIDDEN)
19158 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19159 
19160 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19161 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19162 
19163 	/* ipRouteEntryTable in mpctl */
19164 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19165 	optp->level = MIB2_IP;
19166 	optp->name = MIB2_IP_ROUTE;
19167 	optp->len = msgdsize(ird.ird_route.lp_head);
19168 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19169 	    (int)optp->level, (int)optp->name, (int)optp->len));
19170 	qreply(q, mpctl);
19171 
19172 	/* ipNetToMediaEntryTable in mp3ctl */
19173 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19174 	optp->level = MIB2_IP;
19175 	optp->name = MIB2_IP_MEDIA;
19176 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19177 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19178 	    (int)optp->level, (int)optp->name, (int)optp->len));
19179 	qreply(q, mp3ctl);
19180 
19181 	/* ipRouteAttributeTable in mp4ctl */
19182 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19183 	optp->level = MIB2_IP;
19184 	optp->name = EXPER_IP_RTATTR;
19185 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19186 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19187 	    (int)optp->level, (int)optp->name, (int)optp->len));
19188 	if (optp->len == 0)
19189 		freemsg(mp4ctl);
19190 	else
19191 		qreply(q, mp4ctl);
19192 
19193 	return (mp2ctl);
19194 }
19195 
19196 /*
19197  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19198  * ipv6NetToMediaEntryTable in an NDP walk.
19199  */
19200 static mblk_t *
19201 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
19202     ip_stack_t *ipst)
19203 {
19204 	struct opthdr	*optp;
19205 	mblk_t		*mp2ctl;	/* Returned */
19206 	mblk_t		*mp3ctl;	/* nettomedia */
19207 	mblk_t		*mp4ctl;	/* routeattrs */
19208 	iproutedata_t	ird;
19209 	zoneid_t	zoneid;
19210 
19211 	/*
19212 	 * make copies of the original message
19213 	 *	- mp2ctl is returned unchanged to the caller for his use
19214 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19215 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19216 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19217 	 */
19218 	mp2ctl = copymsg(mpctl);
19219 	mp3ctl = copymsg(mpctl);
19220 	mp4ctl = copymsg(mpctl);
19221 	if (mp3ctl == NULL || mp4ctl == NULL) {
19222 		freemsg(mp4ctl);
19223 		freemsg(mp3ctl);
19224 		freemsg(mp2ctl);
19225 		freemsg(mpctl);
19226 		return (NULL);
19227 	}
19228 
19229 	bzero(&ird, sizeof (ird));
19230 
19231 	ird.ird_route.lp_head = mpctl->b_cont;
19232 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19233 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19234 	/*
19235 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19236 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19237 	 * intended a temporary solution until a proper MIB API is provided
19238 	 * that provides complete filtering/caller-opt-in.
19239 	 */
19240 	if (level == EXPER_IP_AND_TESTHIDDEN)
19241 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19242 
19243 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19244 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19245 
19246 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19247 	optp->level = MIB2_IP6;
19248 	optp->name = MIB2_IP6_ROUTE;
19249 	optp->len = msgdsize(ird.ird_route.lp_head);
19250 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19251 	    (int)optp->level, (int)optp->name, (int)optp->len));
19252 	qreply(q, mpctl);
19253 
19254 	/* ipv6NetToMediaEntryTable in mp3ctl */
19255 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19256 
19257 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19258 	optp->level = MIB2_IP6;
19259 	optp->name = MIB2_IP6_MEDIA;
19260 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19261 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19262 	    (int)optp->level, (int)optp->name, (int)optp->len));
19263 	qreply(q, mp3ctl);
19264 
19265 	/* ipv6RouteAttributeTable in mp4ctl */
19266 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19267 	optp->level = MIB2_IP6;
19268 	optp->name = EXPER_IP_RTATTR;
19269 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19270 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19271 	    (int)optp->level, (int)optp->name, (int)optp->len));
19272 	if (optp->len == 0)
19273 		freemsg(mp4ctl);
19274 	else
19275 		qreply(q, mp4ctl);
19276 
19277 	return (mp2ctl);
19278 }
19279 
19280 /*
19281  * IPv6 mib: One per ill
19282  */
19283 static mblk_t *
19284 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19285 {
19286 	struct opthdr		*optp;
19287 	mblk_t			*mp2ctl;
19288 	ill_t			*ill;
19289 	ill_walk_context_t	ctx;
19290 	mblk_t			*mp_tail = NULL;
19291 
19292 	/*
19293 	 * Make a copy of the original message
19294 	 */
19295 	mp2ctl = copymsg(mpctl);
19296 
19297 	/* fixed length IPv6 structure ... */
19298 
19299 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19300 	optp->level = MIB2_IP6;
19301 	optp->name = 0;
19302 	/* Include "unknown interface" ip6_mib */
19303 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19304 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19305 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19306 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19307 	    ipst->ips_ipv6_forward ? 1 : 2);
19308 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19309 	    ipst->ips_ipv6_def_hops);
19310 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19311 	    sizeof (mib2_ipIfStatsEntry_t));
19312 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19313 	    sizeof (mib2_ipv6AddrEntry_t));
19314 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19315 	    sizeof (mib2_ipv6RouteEntry_t));
19316 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19317 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19318 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19319 	    sizeof (ipv6_member_t));
19320 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19321 	    sizeof (ipv6_grpsrc_t));
19322 
19323 	/*
19324 	 * Synchronize 64- and 32-bit counters
19325 	 */
19326 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19327 	    ipIfStatsHCInReceives);
19328 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19329 	    ipIfStatsHCInDelivers);
19330 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19331 	    ipIfStatsHCOutRequests);
19332 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19333 	    ipIfStatsHCOutForwDatagrams);
19334 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19335 	    ipIfStatsHCOutMcastPkts);
19336 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19337 	    ipIfStatsHCInMcastPkts);
19338 
19339 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19340 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19341 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19342 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19343 	}
19344 
19345 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19346 	ill = ILL_START_WALK_V6(&ctx, ipst);
19347 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19348 		ill->ill_ip_mib->ipIfStatsIfIndex =
19349 		    ill->ill_phyint->phyint_ifindex;
19350 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19351 		    ipst->ips_ipv6_forward ? 1 : 2);
19352 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19353 		    ill->ill_max_hops);
19354 
19355 		/*
19356 		 * Synchronize 64- and 32-bit counters
19357 		 */
19358 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19359 		    ipIfStatsHCInReceives);
19360 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19361 		    ipIfStatsHCInDelivers);
19362 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19363 		    ipIfStatsHCOutRequests);
19364 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19365 		    ipIfStatsHCOutForwDatagrams);
19366 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19367 		    ipIfStatsHCOutMcastPkts);
19368 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19369 		    ipIfStatsHCInMcastPkts);
19370 
19371 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19372 		    (char *)ill->ill_ip_mib,
19373 		    (int)sizeof (*ill->ill_ip_mib))) {
19374 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19375 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19376 		}
19377 	}
19378 	rw_exit(&ipst->ips_ill_g_lock);
19379 
19380 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19381 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19382 	    (int)optp->level, (int)optp->name, (int)optp->len));
19383 	qreply(q, mpctl);
19384 	return (mp2ctl);
19385 }
19386 
19387 /*
19388  * ICMPv6 mib: One per ill
19389  */
19390 static mblk_t *
19391 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19392 {
19393 	struct opthdr		*optp;
19394 	mblk_t			*mp2ctl;
19395 	ill_t			*ill;
19396 	ill_walk_context_t	ctx;
19397 	mblk_t			*mp_tail = NULL;
19398 	/*
19399 	 * Make a copy of the original message
19400 	 */
19401 	mp2ctl = copymsg(mpctl);
19402 
19403 	/* fixed length ICMPv6 structure ... */
19404 
19405 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19406 	optp->level = MIB2_ICMP6;
19407 	optp->name = 0;
19408 	/* Include "unknown interface" icmp6_mib */
19409 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19410 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19411 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19412 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19413 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19414 	    (char *)&ipst->ips_icmp6_mib,
19415 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19416 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19417 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19418 	}
19419 
19420 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19421 	ill = ILL_START_WALK_V6(&ctx, ipst);
19422 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19423 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19424 		    ill->ill_phyint->phyint_ifindex;
19425 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19426 		    (char *)ill->ill_icmp6_mib,
19427 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19428 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19429 			    "%u bytes\n",
19430 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19431 		}
19432 	}
19433 	rw_exit(&ipst->ips_ill_g_lock);
19434 
19435 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19436 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19437 	    (int)optp->level, (int)optp->name, (int)optp->len));
19438 	qreply(q, mpctl);
19439 	return (mp2ctl);
19440 }
19441 
19442 /*
19443  * ire_walk routine to create both ipRouteEntryTable and
19444  * ipRouteAttributeTable in one IRE walk
19445  */
19446 static void
19447 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19448 {
19449 	ill_t				*ill;
19450 	ipif_t				*ipif;
19451 	mib2_ipRouteEntry_t		*re;
19452 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19453 	ipaddr_t			gw_addr;
19454 	tsol_ire_gw_secattr_t		*attrp;
19455 	tsol_gc_t			*gc = NULL;
19456 	tsol_gcgrp_t			*gcgrp = NULL;
19457 	uint_t				sacnt = 0;
19458 	int				i;
19459 
19460 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19461 
19462 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19463 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19464 		return;
19465 	}
19466 
19467 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19468 		return;
19469 
19470 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19471 		mutex_enter(&attrp->igsa_lock);
19472 		if ((gc = attrp->igsa_gc) != NULL) {
19473 			gcgrp = gc->gc_grp;
19474 			ASSERT(gcgrp != NULL);
19475 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19476 			sacnt = 1;
19477 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19478 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19479 			gc = gcgrp->gcgrp_head;
19480 			sacnt = gcgrp->gcgrp_count;
19481 		}
19482 		mutex_exit(&attrp->igsa_lock);
19483 
19484 		/* do nothing if there's no gc to report */
19485 		if (gc == NULL) {
19486 			ASSERT(sacnt == 0);
19487 			if (gcgrp != NULL) {
19488 				/* we might as well drop the lock now */
19489 				rw_exit(&gcgrp->gcgrp_rwlock);
19490 				gcgrp = NULL;
19491 			}
19492 			attrp = NULL;
19493 		}
19494 
19495 		ASSERT(gc == NULL || (gcgrp != NULL &&
19496 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19497 	}
19498 	ASSERT(sacnt == 0 || gc != NULL);
19499 
19500 	if (sacnt != 0 &&
19501 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19502 		kmem_free(re, sizeof (*re));
19503 		rw_exit(&gcgrp->gcgrp_rwlock);
19504 		return;
19505 	}
19506 
19507 	/*
19508 	 * Return all IRE types for route table... let caller pick and choose
19509 	 */
19510 	re->ipRouteDest = ire->ire_addr;
19511 	ipif = ire->ire_ipif;
19512 	re->ipRouteIfIndex.o_length = 0;
19513 	if (ire->ire_type == IRE_CACHE) {
19514 		ill = (ill_t *)ire->ire_stq->q_ptr;
19515 		re->ipRouteIfIndex.o_length =
19516 		    ill->ill_name_length == 0 ? 0 :
19517 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19518 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19519 		    re->ipRouteIfIndex.o_length);
19520 	} else if (ipif != NULL) {
19521 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19522 		re->ipRouteIfIndex.o_length =
19523 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19524 	}
19525 	re->ipRouteMetric1 = -1;
19526 	re->ipRouteMetric2 = -1;
19527 	re->ipRouteMetric3 = -1;
19528 	re->ipRouteMetric4 = -1;
19529 
19530 	gw_addr = ire->ire_gateway_addr;
19531 
19532 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19533 		re->ipRouteNextHop = ire->ire_src_addr;
19534 	else
19535 		re->ipRouteNextHop = gw_addr;
19536 	/* indirect(4), direct(3), or invalid(2) */
19537 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19538 		re->ipRouteType = 2;
19539 	else
19540 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19541 	re->ipRouteProto = -1;
19542 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19543 	re->ipRouteMask = ire->ire_mask;
19544 	re->ipRouteMetric5 = -1;
19545 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19546 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19547 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19548 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19549 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19550 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19551 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19552 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19553 
19554 	if (ire->ire_flags & RTF_DYNAMIC) {
19555 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19556 	} else {
19557 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19558 	}
19559 
19560 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19561 	    (char *)re, (int)sizeof (*re))) {
19562 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19563 		    (uint_t)sizeof (*re)));
19564 	}
19565 
19566 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19567 		iaeptr->iae_routeidx = ird->ird_idx;
19568 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19569 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19570 	}
19571 
19572 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19573 	    (char *)iae, sacnt * sizeof (*iae))) {
19574 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19575 		    (unsigned)(sacnt * sizeof (*iae))));
19576 	}
19577 
19578 	/* bump route index for next pass */
19579 	ird->ird_idx++;
19580 
19581 	kmem_free(re, sizeof (*re));
19582 	if (sacnt != 0)
19583 		kmem_free(iae, sacnt * sizeof (*iae));
19584 
19585 	if (gcgrp != NULL)
19586 		rw_exit(&gcgrp->gcgrp_rwlock);
19587 }
19588 
19589 /*
19590  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19591  */
19592 static void
19593 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19594 {
19595 	ill_t				*ill;
19596 	ipif_t				*ipif;
19597 	mib2_ipv6RouteEntry_t		*re;
19598 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19599 	in6_addr_t			gw_addr_v6;
19600 	tsol_ire_gw_secattr_t		*attrp;
19601 	tsol_gc_t			*gc = NULL;
19602 	tsol_gcgrp_t			*gcgrp = NULL;
19603 	uint_t				sacnt = 0;
19604 	int				i;
19605 
19606 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19607 
19608 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19609 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19610 		return;
19611 	}
19612 
19613 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19614 		return;
19615 
19616 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19617 		mutex_enter(&attrp->igsa_lock);
19618 		if ((gc = attrp->igsa_gc) != NULL) {
19619 			gcgrp = gc->gc_grp;
19620 			ASSERT(gcgrp != NULL);
19621 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19622 			sacnt = 1;
19623 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19624 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19625 			gc = gcgrp->gcgrp_head;
19626 			sacnt = gcgrp->gcgrp_count;
19627 		}
19628 		mutex_exit(&attrp->igsa_lock);
19629 
19630 		/* do nothing if there's no gc to report */
19631 		if (gc == NULL) {
19632 			ASSERT(sacnt == 0);
19633 			if (gcgrp != NULL) {
19634 				/* we might as well drop the lock now */
19635 				rw_exit(&gcgrp->gcgrp_rwlock);
19636 				gcgrp = NULL;
19637 			}
19638 			attrp = NULL;
19639 		}
19640 
19641 		ASSERT(gc == NULL || (gcgrp != NULL &&
19642 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19643 	}
19644 	ASSERT(sacnt == 0 || gc != NULL);
19645 
19646 	if (sacnt != 0 &&
19647 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19648 		kmem_free(re, sizeof (*re));
19649 		rw_exit(&gcgrp->gcgrp_rwlock);
19650 		return;
19651 	}
19652 
19653 	/*
19654 	 * Return all IRE types for route table... let caller pick and choose
19655 	 */
19656 	re->ipv6RouteDest = ire->ire_addr_v6;
19657 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19658 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19659 	re->ipv6RouteIfIndex.o_length = 0;
19660 	ipif = ire->ire_ipif;
19661 	if (ire->ire_type == IRE_CACHE) {
19662 		ill = (ill_t *)ire->ire_stq->q_ptr;
19663 		re->ipv6RouteIfIndex.o_length =
19664 		    ill->ill_name_length == 0 ? 0 :
19665 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19666 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19667 		    re->ipv6RouteIfIndex.o_length);
19668 	} else if (ipif != NULL) {
19669 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19670 		re->ipv6RouteIfIndex.o_length =
19671 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19672 	}
19673 
19674 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19675 
19676 	mutex_enter(&ire->ire_lock);
19677 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19678 	mutex_exit(&ire->ire_lock);
19679 
19680 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19681 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19682 	else
19683 		re->ipv6RouteNextHop = gw_addr_v6;
19684 
19685 	/* remote(4), local(3), or discard(2) */
19686 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19687 		re->ipv6RouteType = 2;
19688 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19689 		re->ipv6RouteType = 3;
19690 	else
19691 		re->ipv6RouteType = 4;
19692 
19693 	re->ipv6RouteProtocol	= -1;
19694 	re->ipv6RoutePolicy	= 0;
19695 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19696 	re->ipv6RouteNextHopRDI	= 0;
19697 	re->ipv6RouteWeight	= 0;
19698 	re->ipv6RouteMetric	= 0;
19699 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19700 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19701 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19702 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19703 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19704 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19705 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19706 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19707 
19708 	if (ire->ire_flags & RTF_DYNAMIC) {
19709 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19710 	} else {
19711 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19712 	}
19713 
19714 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19715 	    (char *)re, (int)sizeof (*re))) {
19716 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19717 		    (uint_t)sizeof (*re)));
19718 	}
19719 
19720 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19721 		iaeptr->iae_routeidx = ird->ird_idx;
19722 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19723 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19724 	}
19725 
19726 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19727 	    (char *)iae, sacnt * sizeof (*iae))) {
19728 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19729 		    (unsigned)(sacnt * sizeof (*iae))));
19730 	}
19731 
19732 	/* bump route index for next pass */
19733 	ird->ird_idx++;
19734 
19735 	kmem_free(re, sizeof (*re));
19736 	if (sacnt != 0)
19737 		kmem_free(iae, sacnt * sizeof (*iae));
19738 
19739 	if (gcgrp != NULL)
19740 		rw_exit(&gcgrp->gcgrp_rwlock);
19741 }
19742 
19743 /*
19744  * ndp_walk routine to create ipv6NetToMediaEntryTable
19745  */
19746 static int
19747 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19748 {
19749 	ill_t				*ill;
19750 	mib2_ipv6NetToMediaEntry_t	ntme;
19751 	dl_unitdata_req_t		*dl;
19752 
19753 	ill = nce->nce_ill;
19754 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19755 		return (0);
19756 
19757 	/*
19758 	 * Neighbor cache entry attached to IRE with on-link
19759 	 * destination.
19760 	 */
19761 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19762 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19763 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19764 	    (nce->nce_res_mp != NULL)) {
19765 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19766 		ntme.ipv6NetToMediaPhysAddress.o_length =
19767 		    dl->dl_dest_addr_length;
19768 	} else {
19769 		ntme.ipv6NetToMediaPhysAddress.o_length =
19770 		    ill->ill_phys_addr_length;
19771 	}
19772 	if (nce->nce_res_mp != NULL) {
19773 		bcopy((char *)nce->nce_res_mp->b_rptr +
19774 		    NCE_LL_ADDR_OFFSET(ill),
19775 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19776 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19777 	} else {
19778 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19779 		    ill->ill_phys_addr_length);
19780 	}
19781 	/*
19782 	 * Note: Returns ND_* states. Should be:
19783 	 * reachable(1), stale(2), delay(3), probe(4),
19784 	 * invalid(5), unknown(6)
19785 	 */
19786 	ntme.ipv6NetToMediaState = nce->nce_state;
19787 	ntme.ipv6NetToMediaLastUpdated = 0;
19788 
19789 	/* other(1), dynamic(2), static(3), local(4) */
19790 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19791 		ntme.ipv6NetToMediaType = 4;
19792 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19793 		ntme.ipv6NetToMediaType = 1;
19794 	} else {
19795 		ntme.ipv6NetToMediaType = 2;
19796 	}
19797 
19798 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19799 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19800 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19801 		    (uint_t)sizeof (ntme)));
19802 	}
19803 	return (0);
19804 }
19805 
19806 /*
19807  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19808  */
19809 /* ARGSUSED */
19810 int
19811 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19812 {
19813 	switch (level) {
19814 	case MIB2_IP:
19815 	case MIB2_ICMP:
19816 		switch (name) {
19817 		default:
19818 			break;
19819 		}
19820 		return (1);
19821 	default:
19822 		return (1);
19823 	}
19824 }
19825 
19826 /*
19827  * When there exists both a 64- and 32-bit counter of a particular type
19828  * (i.e., InReceives), only the 64-bit counters are added.
19829  */
19830 void
19831 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19832 {
19833 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19834 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19835 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19836 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19837 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19838 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19839 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19840 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19841 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19842 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19843 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19844 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19845 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19846 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19847 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19848 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19849 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19850 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19851 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19852 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19853 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19854 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19855 	    o2->ipIfStatsInWrongIPVersion);
19856 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19857 	    o2->ipIfStatsInWrongIPVersion);
19858 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19859 	    o2->ipIfStatsOutSwitchIPVersion);
19860 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19861 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19862 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19863 	    o2->ipIfStatsHCInForwDatagrams);
19864 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19865 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19866 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19867 	    o2->ipIfStatsHCOutForwDatagrams);
19868 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19869 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19870 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19871 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19872 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19873 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19874 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19875 	    o2->ipIfStatsHCOutMcastOctets);
19876 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19877 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19878 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19879 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19880 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19881 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19882 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19883 }
19884 
19885 void
19886 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19887 {
19888 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19889 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19890 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19891 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19892 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19893 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19894 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19895 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19896 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19897 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19898 	    o2->ipv6IfIcmpInRouterSolicits);
19899 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19900 	    o2->ipv6IfIcmpInRouterAdvertisements);
19901 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19902 	    o2->ipv6IfIcmpInNeighborSolicits);
19903 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19904 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19905 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19906 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19907 	    o2->ipv6IfIcmpInGroupMembQueries);
19908 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19909 	    o2->ipv6IfIcmpInGroupMembResponses);
19910 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19911 	    o2->ipv6IfIcmpInGroupMembReductions);
19912 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19913 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19914 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19915 	    o2->ipv6IfIcmpOutDestUnreachs);
19916 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19917 	    o2->ipv6IfIcmpOutAdminProhibs);
19918 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19919 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19920 	    o2->ipv6IfIcmpOutParmProblems);
19921 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19922 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19923 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19924 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19925 	    o2->ipv6IfIcmpOutRouterSolicits);
19926 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19927 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19928 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19929 	    o2->ipv6IfIcmpOutNeighborSolicits);
19930 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19931 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19932 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19933 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19934 	    o2->ipv6IfIcmpOutGroupMembQueries);
19935 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19936 	    o2->ipv6IfIcmpOutGroupMembResponses);
19937 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19938 	    o2->ipv6IfIcmpOutGroupMembReductions);
19939 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19940 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19941 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19942 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19943 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19944 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19945 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19946 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19947 	    o2->ipv6IfIcmpInGroupMembTotal);
19948 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19949 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19950 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19951 	    o2->ipv6IfIcmpInGroupMembBadReports);
19952 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19953 	    o2->ipv6IfIcmpInGroupMembOurReports);
19954 }
19955 
19956 /*
19957  * Called before the options are updated to check if this packet will
19958  * be source routed from here.
19959  * This routine assumes that the options are well formed i.e. that they
19960  * have already been checked.
19961  */
19962 static boolean_t
19963 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19964 {
19965 	ipoptp_t	opts;
19966 	uchar_t		*opt;
19967 	uint8_t		optval;
19968 	uint8_t		optlen;
19969 	ipaddr_t	dst;
19970 	ire_t		*ire;
19971 
19972 	if (IS_SIMPLE_IPH(ipha)) {
19973 		ip2dbg(("not source routed\n"));
19974 		return (B_FALSE);
19975 	}
19976 	dst = ipha->ipha_dst;
19977 	for (optval = ipoptp_first(&opts, ipha);
19978 	    optval != IPOPT_EOL;
19979 	    optval = ipoptp_next(&opts)) {
19980 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19981 		opt = opts.ipoptp_cur;
19982 		optlen = opts.ipoptp_len;
19983 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19984 		    optval, optlen));
19985 		switch (optval) {
19986 			uint32_t off;
19987 		case IPOPT_SSRR:
19988 		case IPOPT_LSRR:
19989 			/*
19990 			 * If dst is one of our addresses and there are some
19991 			 * entries left in the source route return (true).
19992 			 */
19993 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19994 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19995 			if (ire == NULL) {
19996 				ip2dbg(("ip_source_routed: not next"
19997 				    " source route 0x%x\n",
19998 				    ntohl(dst)));
19999 				return (B_FALSE);
20000 			}
20001 			ire_refrele(ire);
20002 			off = opt[IPOPT_OFFSET];
20003 			off--;
20004 			if (optlen < IP_ADDR_LEN ||
20005 			    off > optlen - IP_ADDR_LEN) {
20006 				/* End of source route */
20007 				ip1dbg(("ip_source_routed: end of SR\n"));
20008 				return (B_FALSE);
20009 			}
20010 			return (B_TRUE);
20011 		}
20012 	}
20013 	ip2dbg(("not source routed\n"));
20014 	return (B_FALSE);
20015 }
20016 
20017 /*
20018  * Check if the packet contains any source route.
20019  */
20020 static boolean_t
20021 ip_source_route_included(ipha_t *ipha)
20022 {
20023 	ipoptp_t	opts;
20024 	uint8_t		optval;
20025 
20026 	if (IS_SIMPLE_IPH(ipha))
20027 		return (B_FALSE);
20028 	for (optval = ipoptp_first(&opts, ipha);
20029 	    optval != IPOPT_EOL;
20030 	    optval = ipoptp_next(&opts)) {
20031 		switch (optval) {
20032 		case IPOPT_SSRR:
20033 		case IPOPT_LSRR:
20034 			return (B_TRUE);
20035 		}
20036 	}
20037 	return (B_FALSE);
20038 }
20039 
20040 /*
20041  * Called when the IRE expiration timer fires.
20042  */
20043 void
20044 ip_trash_timer_expire(void *args)
20045 {
20046 	int			flush_flag = 0;
20047 	ire_expire_arg_t	iea;
20048 	ip_stack_t		*ipst = (ip_stack_t *)args;
20049 
20050 	iea.iea_ipst = ipst;	/* No netstack_hold */
20051 
20052 	/*
20053 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
20054 	 * This lock makes sure that a new invocation of this function
20055 	 * that occurs due to an almost immediate timer firing will not
20056 	 * progress beyond this point until the current invocation is done
20057 	 */
20058 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20059 	ipst->ips_ip_ire_expire_id = 0;
20060 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20061 
20062 	/* Periodic timer */
20063 	if (ipst->ips_ip_ire_arp_time_elapsed >=
20064 	    ipst->ips_ip_ire_arp_interval) {
20065 		/*
20066 		 * Remove all IRE_CACHE entries since they might
20067 		 * contain arp information.
20068 		 */
20069 		flush_flag |= FLUSH_ARP_TIME;
20070 		ipst->ips_ip_ire_arp_time_elapsed = 0;
20071 		IP_STAT(ipst, ip_ire_arp_timer_expired);
20072 	}
20073 	if (ipst->ips_ip_ire_rd_time_elapsed >=
20074 	    ipst->ips_ip_ire_redir_interval) {
20075 		/* Remove all redirects */
20076 		flush_flag |= FLUSH_REDIRECT_TIME;
20077 		ipst->ips_ip_ire_rd_time_elapsed = 0;
20078 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
20079 	}
20080 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
20081 	    ipst->ips_ip_ire_pathmtu_interval) {
20082 		/* Increase path mtu */
20083 		flush_flag |= FLUSH_MTU_TIME;
20084 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20085 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20086 	}
20087 
20088 	/*
20089 	 * Optimize for the case when there are no redirects in the
20090 	 * ftable, that is, no need to walk the ftable in that case.
20091 	 */
20092 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20093 		iea.iea_flush_flag = flush_flag;
20094 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20095 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20096 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20097 		    NULL, ALL_ZONES, ipst);
20098 	}
20099 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20100 	    ipst->ips_ip_redirect_cnt > 0) {
20101 		iea.iea_flush_flag = flush_flag;
20102 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20103 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20104 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20105 	}
20106 	if (flush_flag & FLUSH_MTU_TIME) {
20107 		/*
20108 		 * Walk all IPv6 IRE's and update them
20109 		 * Note that ARP and redirect timers are not
20110 		 * needed since NUD handles stale entries.
20111 		 */
20112 		flush_flag = FLUSH_MTU_TIME;
20113 		iea.iea_flush_flag = flush_flag;
20114 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20115 		    ALL_ZONES, ipst);
20116 	}
20117 
20118 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20119 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20120 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20121 
20122 	/*
20123 	 * Hold the lock to serialize timeout calls and prevent
20124 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20125 	 * for the timer to fire and a new invocation of this function
20126 	 * to start before the return value of timeout has been stored
20127 	 * in ip_ire_expire_id by the current invocation.
20128 	 */
20129 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20130 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20131 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20132 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20133 }
20134 
20135 /*
20136  * Called by the memory allocator subsystem directly, when the system
20137  * is running low on memory.
20138  */
20139 /* ARGSUSED */
20140 void
20141 ip_trash_ire_reclaim(void *args)
20142 {
20143 	netstack_handle_t nh;
20144 	netstack_t *ns;
20145 
20146 	netstack_next_init(&nh);
20147 	while ((ns = netstack_next(&nh)) != NULL) {
20148 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20149 		netstack_rele(ns);
20150 	}
20151 	netstack_next_fini(&nh);
20152 }
20153 
20154 static void
20155 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20156 {
20157 	ire_cache_count_t icc;
20158 	ire_cache_reclaim_t icr;
20159 	ncc_cache_count_t ncc;
20160 	nce_cache_reclaim_t ncr;
20161 	uint_t delete_cnt;
20162 	/*
20163 	 * Memory reclaim call back.
20164 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20165 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20166 	 * entries, determine what fraction to free for
20167 	 * each category of IRE_CACHE entries giving absolute priority
20168 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20169 	 * entry will be freed unless all offlink entries are freed).
20170 	 */
20171 	icc.icc_total = 0;
20172 	icc.icc_unused = 0;
20173 	icc.icc_offlink = 0;
20174 	icc.icc_pmtu = 0;
20175 	icc.icc_onlink = 0;
20176 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20177 
20178 	/*
20179 	 * Free NCEs for IPv6 like the onlink ires.
20180 	 */
20181 	ncc.ncc_total = 0;
20182 	ncc.ncc_host = 0;
20183 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20184 
20185 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20186 	    icc.icc_pmtu + icc.icc_onlink);
20187 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20188 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20189 	if (delete_cnt == 0)
20190 		return;
20191 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20192 	/* Always delete all unused offlink entries */
20193 	icr.icr_ipst = ipst;
20194 	icr.icr_unused = 1;
20195 	if (delete_cnt <= icc.icc_unused) {
20196 		/*
20197 		 * Only need to free unused entries.  In other words,
20198 		 * there are enough unused entries to free to meet our
20199 		 * target number of freed ire cache entries.
20200 		 */
20201 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20202 		ncr.ncr_host = 0;
20203 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20204 		/*
20205 		 * Only need to free unused entries, plus a fraction of offlink
20206 		 * entries.  It follows from the first if statement that
20207 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20208 		 */
20209 		delete_cnt -= icc.icc_unused;
20210 		/* Round up # deleted by truncating fraction */
20211 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20212 		icr.icr_pmtu = icr.icr_onlink = 0;
20213 		ncr.ncr_host = 0;
20214 	} else if (delete_cnt <=
20215 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20216 		/*
20217 		 * Free all unused and offlink entries, plus a fraction of
20218 		 * pmtu entries.  It follows from the previous if statement
20219 		 * that icc_pmtu is non-zero, and that
20220 		 * delete_cnt != icc_unused + icc_offlink.
20221 		 */
20222 		icr.icr_offlink = 1;
20223 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20224 		/* Round up # deleted by truncating fraction */
20225 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20226 		icr.icr_onlink = 0;
20227 		ncr.ncr_host = 0;
20228 	} else {
20229 		/*
20230 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20231 		 * of onlink entries.  If we're here, then we know that
20232 		 * icc_onlink is non-zero, and that
20233 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20234 		 */
20235 		icr.icr_offlink = icr.icr_pmtu = 1;
20236 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20237 		    icc.icc_pmtu;
20238 		/* Round up # deleted by truncating fraction */
20239 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20240 		/* Using the same delete fraction as for onlink IREs */
20241 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20242 	}
20243 #ifdef DEBUG
20244 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20245 	    "fractions %d/%d/%d/%d\n",
20246 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20247 	    icc.icc_unused, icc.icc_offlink,
20248 	    icc.icc_pmtu, icc.icc_onlink,
20249 	    icr.icr_unused, icr.icr_offlink,
20250 	    icr.icr_pmtu, icr.icr_onlink));
20251 #endif
20252 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20253 	if (ncr.ncr_host != 0)
20254 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20255 		    (uchar_t *)&ncr, ipst);
20256 #ifdef DEBUG
20257 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20258 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20259 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20260 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20261 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20262 	    icc.icc_pmtu, icc.icc_onlink));
20263 #endif
20264 }
20265 
20266 /*
20267  * ip_unbind is called when a copy of an unbind request is received from the
20268  * upper level protocol.  We remove this conn from any fanout hash list it is
20269  * on, and zero out the bind information.  No reply is expected up above.
20270  */
20271 void
20272 ip_unbind(conn_t *connp)
20273 {
20274 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20275 
20276 	if (is_system_labeled() && connp->conn_anon_port) {
20277 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20278 		    connp->conn_mlp_type, connp->conn_ulp,
20279 		    ntohs(connp->conn_lport), B_FALSE);
20280 		connp->conn_anon_port = 0;
20281 	}
20282 	connp->conn_mlp_type = mlptSingle;
20283 
20284 	ipcl_hash_remove(connp);
20285 
20286 }
20287 
20288 /*
20289  * Write side put procedure.  Outbound data, IOCTLs, responses from
20290  * resolvers, etc, come down through here.
20291  *
20292  * arg2 is always a queue_t *.
20293  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20294  * the zoneid.
20295  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20296  */
20297 void
20298 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20299 {
20300 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20301 }
20302 
20303 void
20304 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20305     ip_opt_info_t *infop)
20306 {
20307 	conn_t		*connp = NULL;
20308 	queue_t		*q = (queue_t *)arg2;
20309 	ipha_t		*ipha;
20310 #define	rptr	((uchar_t *)ipha)
20311 	ire_t		*ire = NULL;
20312 	ire_t		*sctp_ire = NULL;
20313 	uint32_t	v_hlen_tos_len;
20314 	ipaddr_t	dst;
20315 	mblk_t		*first_mp = NULL;
20316 	boolean_t	mctl_present;
20317 	ipsec_out_t	*io;
20318 	int		match_flags;
20319 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20320 	ipif_t		*dst_ipif;
20321 	boolean_t	multirt_need_resolve = B_FALSE;
20322 	mblk_t		*copy_mp = NULL;
20323 	int		err;
20324 	zoneid_t	zoneid;
20325 	boolean_t	need_decref = B_FALSE;
20326 	boolean_t	ignore_dontroute = B_FALSE;
20327 	boolean_t	ignore_nexthop = B_FALSE;
20328 	boolean_t	ip_nexthop = B_FALSE;
20329 	ipaddr_t	nexthop_addr;
20330 	ip_stack_t	*ipst;
20331 
20332 #ifdef	_BIG_ENDIAN
20333 #define	V_HLEN	(v_hlen_tos_len >> 24)
20334 #else
20335 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20336 #endif
20337 
20338 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20339 	    "ip_wput_start: q %p", q);
20340 
20341 	/*
20342 	 * ip_wput fast path
20343 	 */
20344 
20345 	/* is packet from ARP ? */
20346 	if (q->q_next != NULL) {
20347 		zoneid = (zoneid_t)(uintptr_t)arg;
20348 		goto qnext;
20349 	}
20350 
20351 	connp = (conn_t *)arg;
20352 	ASSERT(connp != NULL);
20353 	zoneid = connp->conn_zoneid;
20354 	ipst = connp->conn_netstack->netstack_ip;
20355 	ASSERT(ipst != NULL);
20356 
20357 	/* is queue flow controlled? */
20358 	if ((q->q_first != NULL || connp->conn_draining) &&
20359 	    (caller == IP_WPUT)) {
20360 		ASSERT(!need_decref);
20361 		ASSERT(!IP_FLOW_CONTROLLED_ULP(connp->conn_ulp));
20362 		(void) putq(q, mp);
20363 		return;
20364 	}
20365 
20366 	/* Multidata transmit? */
20367 	if (DB_TYPE(mp) == M_MULTIDATA) {
20368 		/*
20369 		 * We should never get here, since all Multidata messages
20370 		 * originating from tcp should have been directed over to
20371 		 * tcp_multisend() in the first place.
20372 		 */
20373 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20374 		freemsg(mp);
20375 		return;
20376 	} else if (DB_TYPE(mp) != M_DATA)
20377 		goto notdata;
20378 
20379 	if (mp->b_flag & MSGHASREF) {
20380 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20381 		mp->b_flag &= ~MSGHASREF;
20382 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20383 		need_decref = B_TRUE;
20384 	}
20385 	ipha = (ipha_t *)mp->b_rptr;
20386 
20387 	/* is IP header non-aligned or mblk smaller than basic IP header */
20388 #ifndef SAFETY_BEFORE_SPEED
20389 	if (!OK_32PTR(rptr) ||
20390 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20391 		goto hdrtoosmall;
20392 #endif
20393 
20394 	ASSERT(OK_32PTR(ipha));
20395 
20396 	/*
20397 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20398 	 * wrong version, we'll catch it again in ip_output_v6.
20399 	 *
20400 	 * Note that this is *only* locally-generated output here, and never
20401 	 * forwarded data, and that we need to deal only with transports that
20402 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20403 	 * label.)
20404 	 */
20405 	if (is_system_labeled() &&
20406 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20407 	    !connp->conn_ulp_labeled) {
20408 		err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20409 		    connp->conn_mac_exempt, ipst);
20410 		ipha = (ipha_t *)mp->b_rptr;
20411 		if (err != 0) {
20412 			first_mp = mp;
20413 			if (err == EINVAL)
20414 				goto icmp_parameter_problem;
20415 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20416 			goto discard_pkt;
20417 		}
20418 	}
20419 
20420 	ASSERT(infop != NULL);
20421 
20422 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20423 		/*
20424 		 * IP_PKTINFO ancillary option is present.
20425 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20426 		 * allows using address of any zone as the source address.
20427 		 */
20428 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20429 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20430 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20431 		if (ire == NULL)
20432 			goto drop_pkt;
20433 		ire_refrele(ire);
20434 		ire = NULL;
20435 	}
20436 
20437 	/*
20438 	 * IP_BOUND_IF has precedence over the ill index passed in IP_PKTINFO.
20439 	 */
20440 	if (infop->ip_opt_ill_index != 0 && connp->conn_outgoing_ill == NULL) {
20441 		xmit_ill = ill_lookup_on_ifindex(infop->ip_opt_ill_index,
20442 		    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20443 
20444 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20445 			goto drop_pkt;
20446 		/*
20447 		 * check that there is an ipif belonging
20448 		 * to our zone. IPCL_ZONEID is not used because
20449 		 * IP_ALLZONES option is valid only when the ill is
20450 		 * accessible from all zones i.e has a valid ipif in
20451 		 * all zones.
20452 		 */
20453 		if (!ipif_lookup_zoneid(xmit_ill, zoneid, 0, NULL)) {
20454 			goto drop_pkt;
20455 		}
20456 	}
20457 
20458 	/*
20459 	 * If there is a policy, try to attach an ipsec_out in
20460 	 * the front. At the end, first_mp either points to a
20461 	 * M_DATA message or IPSEC_OUT message linked to a
20462 	 * M_DATA message. We have to do it now as we might
20463 	 * lose the "conn" if we go through ip_newroute.
20464 	 */
20465 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20466 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20467 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20468 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20469 			if (need_decref)
20470 				CONN_DEC_REF(connp);
20471 			return;
20472 		} else {
20473 			ASSERT(mp->b_datap->db_type == M_CTL);
20474 			first_mp = mp;
20475 			mp = mp->b_cont;
20476 			mctl_present = B_TRUE;
20477 		}
20478 	} else {
20479 		first_mp = mp;
20480 		mctl_present = B_FALSE;
20481 	}
20482 
20483 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20484 
20485 	/* is wrong version or IP options present */
20486 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20487 		goto version_hdrlen_check;
20488 	dst = ipha->ipha_dst;
20489 
20490 	/* If IP_BOUND_IF has been set, use that ill. */
20491 	if (connp->conn_outgoing_ill != NULL) {
20492 		xmit_ill = conn_get_held_ill(connp,
20493 		    &connp->conn_outgoing_ill, &err);
20494 		if (err == ILL_LOOKUP_FAILED)
20495 			goto drop_pkt;
20496 
20497 		goto send_from_ill;
20498 	}
20499 
20500 	/* is packet multicast? */
20501 	if (CLASSD(dst))
20502 		goto multicast;
20503 
20504 	/*
20505 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20506 	 * takes precedence over conn_dontroute and conn_nexthop_set
20507 	 */
20508 	if (xmit_ill != NULL)
20509 		goto send_from_ill;
20510 
20511 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20512 		/*
20513 		 * If the destination is a broadcast, local, or loopback
20514 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20515 		 * standard path.
20516 		 */
20517 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20518 		if ((ire == NULL) || (ire->ire_type &
20519 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20520 			if (ire != NULL) {
20521 				ire_refrele(ire);
20522 				/* No more access to ire */
20523 				ire = NULL;
20524 			}
20525 			/*
20526 			 * bypass routing checks and go directly to interface.
20527 			 */
20528 			if (connp->conn_dontroute)
20529 				goto dontroute;
20530 
20531 			ASSERT(connp->conn_nexthop_set);
20532 			ip_nexthop = B_TRUE;
20533 			nexthop_addr = connp->conn_nexthop_v4;
20534 			goto send_from_ill;
20535 		}
20536 
20537 		/* Must be a broadcast, a loopback or a local ire */
20538 		ire_refrele(ire);
20539 		/* No more access to ire */
20540 		ire = NULL;
20541 	}
20542 
20543 	/*
20544 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20545 	 * this for the tcp global queue and listen end point
20546 	 * as it does not really have a real destination to
20547 	 * talk to.  This is also true for SCTP.
20548 	 */
20549 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20550 	    !connp->conn_fully_bound) {
20551 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20552 		if (ire == NULL)
20553 			goto noirefound;
20554 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20555 		    "ip_wput_end: q %p (%S)", q, "end");
20556 
20557 		/*
20558 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20559 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20560 		 */
20561 		if (ire->ire_flags & RTF_MULTIRT) {
20562 
20563 			/*
20564 			 * Force the TTL of multirouted packets if required.
20565 			 * The TTL of such packets is bounded by the
20566 			 * ip_multirt_ttl ndd variable.
20567 			 */
20568 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20569 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20570 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20571 				    "(was %d), dst 0x%08x\n",
20572 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20573 				    ntohl(ire->ire_addr)));
20574 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20575 			}
20576 			/*
20577 			 * We look at this point if there are pending
20578 			 * unresolved routes. ire_multirt_resolvable()
20579 			 * checks in O(n) that all IRE_OFFSUBNET ire
20580 			 * entries for the packet's destination and
20581 			 * flagged RTF_MULTIRT are currently resolved.
20582 			 * If some remain unresolved, we make a copy
20583 			 * of the current message. It will be used
20584 			 * to initiate additional route resolutions.
20585 			 */
20586 			multirt_need_resolve =
20587 			    ire_multirt_need_resolve(ire->ire_addr,
20588 			    msg_getlabel(first_mp), ipst);
20589 			ip2dbg(("ip_wput[TCP]: ire %p, "
20590 			    "multirt_need_resolve %d, first_mp %p\n",
20591 			    (void *)ire, multirt_need_resolve,
20592 			    (void *)first_mp));
20593 			if (multirt_need_resolve) {
20594 				copy_mp = copymsg(first_mp);
20595 				if (copy_mp != NULL) {
20596 					MULTIRT_DEBUG_TAG(copy_mp);
20597 				}
20598 			}
20599 		}
20600 
20601 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20602 
20603 		/*
20604 		 * Try to resolve another multiroute if
20605 		 * ire_multirt_need_resolve() deemed it necessary.
20606 		 */
20607 		if (copy_mp != NULL)
20608 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20609 		if (need_decref)
20610 			CONN_DEC_REF(connp);
20611 		return;
20612 	}
20613 
20614 	/*
20615 	 * Access to conn_ire_cache. (protected by conn_lock)
20616 	 *
20617 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20618 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20619 	 * send a packet or two with the IRE_CACHE that is going away.
20620 	 * Access to the ire requires an ire refhold on the ire prior to
20621 	 * its use since an interface unplumb thread may delete the cached
20622 	 * ire and release the refhold at any time.
20623 	 *
20624 	 * Caching an ire in the conn_ire_cache
20625 	 *
20626 	 * o Caching an ire pointer in the conn requires a strict check for
20627 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20628 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20629 	 * in the conn is done after making sure under the bucket lock that the
20630 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20631 	 * caching an ire after the unplumb thread has cleaned up the conn.
20632 	 * If the conn does not send a packet subsequently the unplumb thread
20633 	 * will be hanging waiting for the ire count to drop to zero.
20634 	 *
20635 	 * o We also need to atomically test for a null conn_ire_cache and
20636 	 * set the conn_ire_cache under the the protection of the conn_lock
20637 	 * to avoid races among concurrent threads trying to simultaneously
20638 	 * cache an ire in the conn_ire_cache.
20639 	 */
20640 	mutex_enter(&connp->conn_lock);
20641 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20642 
20643 	if (ire != NULL && ire->ire_addr == dst &&
20644 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20645 
20646 		IRE_REFHOLD(ire);
20647 		mutex_exit(&connp->conn_lock);
20648 
20649 	} else {
20650 		boolean_t cached = B_FALSE;
20651 		connp->conn_ire_cache = NULL;
20652 		mutex_exit(&connp->conn_lock);
20653 		/* Release the old ire */
20654 		if (ire != NULL && sctp_ire == NULL)
20655 			IRE_REFRELE_NOTR(ire);
20656 
20657 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20658 		if (ire == NULL)
20659 			goto noirefound;
20660 		IRE_REFHOLD_NOTR(ire);
20661 
20662 		mutex_enter(&connp->conn_lock);
20663 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20664 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20665 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20666 				if (connp->conn_ulp == IPPROTO_TCP)
20667 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20668 				connp->conn_ire_cache = ire;
20669 				cached = B_TRUE;
20670 			}
20671 			rw_exit(&ire->ire_bucket->irb_lock);
20672 		}
20673 		mutex_exit(&connp->conn_lock);
20674 
20675 		/*
20676 		 * We can continue to use the ire but since it was
20677 		 * not cached, we should drop the extra reference.
20678 		 */
20679 		if (!cached)
20680 			IRE_REFRELE_NOTR(ire);
20681 	}
20682 
20683 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20684 	    "ip_wput_end: q %p (%S)", q, "end");
20685 
20686 	/*
20687 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20688 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20689 	 */
20690 	if (ire->ire_flags & RTF_MULTIRT) {
20691 		/*
20692 		 * Force the TTL of multirouted packets if required.
20693 		 * The TTL of such packets is bounded by the
20694 		 * ip_multirt_ttl ndd variable.
20695 		 */
20696 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20697 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20698 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20699 			    "(was %d), dst 0x%08x\n",
20700 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20701 			    ntohl(ire->ire_addr)));
20702 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20703 		}
20704 
20705 		/*
20706 		 * At this point, we check to see if there are any pending
20707 		 * unresolved routes. ire_multirt_resolvable()
20708 		 * checks in O(n) that all IRE_OFFSUBNET ire
20709 		 * entries for the packet's destination and
20710 		 * flagged RTF_MULTIRT are currently resolved.
20711 		 * If some remain unresolved, we make a copy
20712 		 * of the current message. It will be used
20713 		 * to initiate additional route resolutions.
20714 		 */
20715 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20716 		    msg_getlabel(first_mp), ipst);
20717 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20718 		    "multirt_need_resolve %d, first_mp %p\n",
20719 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20720 		if (multirt_need_resolve) {
20721 			copy_mp = copymsg(first_mp);
20722 			if (copy_mp != NULL) {
20723 				MULTIRT_DEBUG_TAG(copy_mp);
20724 			}
20725 		}
20726 	}
20727 
20728 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20729 
20730 	/*
20731 	 * Try to resolve another multiroute if
20732 	 * ire_multirt_resolvable() deemed it necessary
20733 	 */
20734 	if (copy_mp != NULL)
20735 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20736 	if (need_decref)
20737 		CONN_DEC_REF(connp);
20738 	return;
20739 
20740 qnext:
20741 	/*
20742 	 * Upper Level Protocols pass down complete IP datagrams
20743 	 * as M_DATA messages.	Everything else is a sideshow.
20744 	 *
20745 	 * 1) We could be re-entering ip_wput because of ip_neworute
20746 	 *    in which case we could have a IPSEC_OUT message. We
20747 	 *    need to pass through ip_wput like other datagrams and
20748 	 *    hence cannot branch to ip_wput_nondata.
20749 	 *
20750 	 * 2) ARP, AH, ESP, and other clients who are on the module
20751 	 *    instance of IP stream, give us something to deal with.
20752 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20753 	 *
20754 	 * 3) ICMP replies also could come here.
20755 	 */
20756 	ipst = ILLQ_TO_IPST(q);
20757 
20758 	if (DB_TYPE(mp) != M_DATA) {
20759 notdata:
20760 		if (DB_TYPE(mp) == M_CTL) {
20761 			/*
20762 			 * M_CTL messages are used by ARP, AH and ESP to
20763 			 * communicate with IP. We deal with IPSEC_IN and
20764 			 * IPSEC_OUT here. ip_wput_nondata handles other
20765 			 * cases.
20766 			 */
20767 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20768 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20769 				first_mp = mp->b_cont;
20770 				first_mp->b_flag &= ~MSGHASREF;
20771 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20772 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20773 				CONN_DEC_REF(connp);
20774 				connp = NULL;
20775 			}
20776 			if (ii->ipsec_info_type == IPSEC_IN) {
20777 				/*
20778 				 * Either this message goes back to
20779 				 * IPsec for further processing or to
20780 				 * ULP after policy checks.
20781 				 */
20782 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20783 				return;
20784 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20785 				io = (ipsec_out_t *)ii;
20786 				if (io->ipsec_out_proc_begin) {
20787 					/*
20788 					 * IPsec processing has already started.
20789 					 * Complete it.
20790 					 * IPQoS notes: We don't care what is
20791 					 * in ipsec_out_ill_index since this
20792 					 * won't be processed for IPQoS policies
20793 					 * in ipsec_out_process.
20794 					 */
20795 					ipsec_out_process(q, mp, NULL,
20796 					    io->ipsec_out_ill_index);
20797 					return;
20798 				} else {
20799 					connp = (q->q_next != NULL) ?
20800 					    NULL : Q_TO_CONN(q);
20801 					first_mp = mp;
20802 					mp = mp->b_cont;
20803 					mctl_present = B_TRUE;
20804 				}
20805 				zoneid = io->ipsec_out_zoneid;
20806 				ASSERT(zoneid != ALL_ZONES);
20807 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20808 				/*
20809 				 * It's an IPsec control message requesting
20810 				 * an SADB update to be sent to the IPsec
20811 				 * hardware acceleration capable ills.
20812 				 */
20813 				ipsec_ctl_t *ipsec_ctl =
20814 				    (ipsec_ctl_t *)mp->b_rptr;
20815 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20816 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20817 				mblk_t *cmp = mp->b_cont;
20818 
20819 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20820 				ASSERT(cmp != NULL);
20821 
20822 				freeb(mp);
20823 				ill_ipsec_capab_send_all(satype, cmp, sa,
20824 				    ipst->ips_netstack);
20825 				return;
20826 			} else {
20827 				/*
20828 				 * This must be ARP or special TSOL signaling.
20829 				 */
20830 				ip_wput_nondata(NULL, q, mp, NULL);
20831 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20832 				    "ip_wput_end: q %p (%S)", q, "nondata");
20833 				return;
20834 			}
20835 		} else {
20836 			/*
20837 			 * This must be non-(ARP/AH/ESP) messages.
20838 			 */
20839 			ASSERT(!need_decref);
20840 			ip_wput_nondata(NULL, q, mp, NULL);
20841 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20842 			    "ip_wput_end: q %p (%S)", q, "nondata");
20843 			return;
20844 		}
20845 	} else {
20846 		first_mp = mp;
20847 		mctl_present = B_FALSE;
20848 	}
20849 
20850 	ASSERT(first_mp != NULL);
20851 
20852 	if (mctl_present) {
20853 		io = (ipsec_out_t *)first_mp->b_rptr;
20854 		if (io->ipsec_out_ip_nexthop) {
20855 			/*
20856 			 * We may have lost the conn context if we are
20857 			 * coming here from ip_newroute(). Copy the
20858 			 * nexthop information.
20859 			 */
20860 			ip_nexthop = B_TRUE;
20861 			nexthop_addr = io->ipsec_out_nexthop_addr;
20862 
20863 			ipha = (ipha_t *)mp->b_rptr;
20864 			dst = ipha->ipha_dst;
20865 			goto send_from_ill;
20866 		}
20867 	}
20868 
20869 	ASSERT(xmit_ill == NULL);
20870 
20871 	/* We have a complete IP datagram heading outbound. */
20872 	ipha = (ipha_t *)mp->b_rptr;
20873 
20874 #ifndef SPEED_BEFORE_SAFETY
20875 	/*
20876 	 * Make sure we have a full-word aligned message and that at least
20877 	 * a simple IP header is accessible in the first message.  If not,
20878 	 * try a pullup.  For labeled systems we need to always take this
20879 	 * path as M_CTLs are "notdata" but have trailing data to process.
20880 	 */
20881 	if (!OK_32PTR(rptr) ||
20882 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
20883 hdrtoosmall:
20884 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20885 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20886 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20887 			if (first_mp == NULL)
20888 				first_mp = mp;
20889 			goto discard_pkt;
20890 		}
20891 
20892 		/* This function assumes that mp points to an IPv4 packet. */
20893 		if (is_system_labeled() && q->q_next == NULL &&
20894 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20895 		    !connp->conn_ulp_labeled) {
20896 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20897 			    connp->conn_mac_exempt, ipst);
20898 			ipha = (ipha_t *)mp->b_rptr;
20899 			if (first_mp != NULL)
20900 				first_mp->b_cont = mp;
20901 			if (err != 0) {
20902 				if (first_mp == NULL)
20903 					first_mp = mp;
20904 				if (err == EINVAL)
20905 					goto icmp_parameter_problem;
20906 				ip2dbg(("ip_wput: label check failed (%d)\n",
20907 				    err));
20908 				goto discard_pkt;
20909 			}
20910 		}
20911 
20912 		ipha = (ipha_t *)mp->b_rptr;
20913 		if (first_mp == NULL) {
20914 			ASSERT(xmit_ill == NULL);
20915 			/*
20916 			 * If we got here because of "goto hdrtoosmall"
20917 			 * We need to attach a IPSEC_OUT.
20918 			 */
20919 			if (connp->conn_out_enforce_policy) {
20920 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20921 				    NULL, ipha->ipha_protocol,
20922 				    ipst->ips_netstack)) == NULL)) {
20923 					BUMP_MIB(&ipst->ips_ip_mib,
20924 					    ipIfStatsOutDiscards);
20925 					if (need_decref)
20926 						CONN_DEC_REF(connp);
20927 					return;
20928 				} else {
20929 					ASSERT(mp->b_datap->db_type == M_CTL);
20930 					first_mp = mp;
20931 					mp = mp->b_cont;
20932 					mctl_present = B_TRUE;
20933 				}
20934 			} else {
20935 				first_mp = mp;
20936 				mctl_present = B_FALSE;
20937 			}
20938 		}
20939 	}
20940 #endif
20941 
20942 	/* Most of the code below is written for speed, not readability */
20943 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20944 
20945 	/*
20946 	 * If ip_newroute() fails, we're going to need a full
20947 	 * header for the icmp wraparound.
20948 	 */
20949 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20950 		uint_t	v_hlen;
20951 version_hdrlen_check:
20952 		ASSERT(first_mp != NULL);
20953 		v_hlen = V_HLEN;
20954 		/*
20955 		 * siphon off IPv6 packets coming down from transport
20956 		 * layer modules here.
20957 		 * Note: high-order bit carries NUD reachability confirmation
20958 		 */
20959 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20960 			/*
20961 			 * FIXME: assume that callers of ip_output* call
20962 			 * the right version?
20963 			 */
20964 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20965 			ASSERT(xmit_ill == NULL);
20966 			if (need_decref)
20967 				mp->b_flag |= MSGHASREF;
20968 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20969 			return;
20970 		}
20971 
20972 		if ((v_hlen >> 4) != IP_VERSION) {
20973 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20974 			    "ip_wput_end: q %p (%S)", q, "badvers");
20975 			goto discard_pkt;
20976 		}
20977 		/*
20978 		 * Is the header length at least 20 bytes?
20979 		 *
20980 		 * Are there enough bytes accessible in the header?  If
20981 		 * not, try a pullup.
20982 		 */
20983 		v_hlen &= 0xF;
20984 		v_hlen <<= 2;
20985 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20986 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20987 			    "ip_wput_end: q %p (%S)", q, "badlen");
20988 			goto discard_pkt;
20989 		}
20990 		if (v_hlen > (mp->b_wptr - rptr)) {
20991 			if (!pullupmsg(mp, v_hlen)) {
20992 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20993 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20994 				goto discard_pkt;
20995 			}
20996 			ipha = (ipha_t *)mp->b_rptr;
20997 		}
20998 		/*
20999 		 * Move first entry from any source route into ipha_dst and
21000 		 * verify the options
21001 		 */
21002 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
21003 		    zoneid, ipst)) {
21004 			ASSERT(xmit_ill == NULL);
21005 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21006 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21007 			    "ip_wput_end: q %p (%S)", q, "badopts");
21008 			if (need_decref)
21009 				CONN_DEC_REF(connp);
21010 			return;
21011 		}
21012 	}
21013 	dst = ipha->ipha_dst;
21014 
21015 	/*
21016 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
21017 	 * we have to run the packet through ip_newroute which will take
21018 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
21019 	 * a resolver, or assigning a default gateway, etc.
21020 	 */
21021 	if (CLASSD(dst)) {
21022 		ipif_t	*ipif;
21023 		uint32_t setsrc = 0;
21024 
21025 multicast:
21026 		ASSERT(first_mp != NULL);
21027 		ip2dbg(("ip_wput: CLASSD\n"));
21028 		if (connp == NULL) {
21029 			/*
21030 			 * Use the first good ipif on the ill.
21031 			 * XXX Should this ever happen? (Appears
21032 			 * to show up with just ppp and no ethernet due
21033 			 * to in.rdisc.)
21034 			 * However, ire_send should be able to
21035 			 * call ip_wput_ire directly.
21036 			 *
21037 			 * XXX Also, this can happen for ICMP and other packets
21038 			 * with multicast source addresses.  Perhaps we should
21039 			 * fix things so that we drop the packet in question,
21040 			 * but for now, just run with it.
21041 			 */
21042 			ill_t *ill = (ill_t *)q->q_ptr;
21043 
21044 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21045 			if (ipif == NULL) {
21046 				if (need_decref)
21047 					CONN_DEC_REF(connp);
21048 				freemsg(first_mp);
21049 				return;
21050 			}
21051 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21052 			    ntohl(dst), ill->ill_name));
21053 		} else {
21054 			/*
21055 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
21056 			 * and IP_MULTICAST_IF.  The block comment above this
21057 			 * function explains the locking mechanism used here.
21058 			 */
21059 			if (xmit_ill == NULL) {
21060 				xmit_ill = conn_get_held_ill(connp,
21061 				    &connp->conn_outgoing_ill, &err);
21062 				if (err == ILL_LOOKUP_FAILED) {
21063 					ip1dbg(("ip_wput: No ill for "
21064 					    "IP_BOUND_IF\n"));
21065 					BUMP_MIB(&ipst->ips_ip_mib,
21066 					    ipIfStatsOutNoRoutes);
21067 					goto drop_pkt;
21068 				}
21069 			}
21070 
21071 			if (xmit_ill == NULL) {
21072 				ipif = conn_get_held_ipif(connp,
21073 				    &connp->conn_multicast_ipif, &err);
21074 				if (err == IPIF_LOOKUP_FAILED) {
21075 					ip1dbg(("ip_wput: No ipif for "
21076 					    "multicast\n"));
21077 					BUMP_MIB(&ipst->ips_ip_mib,
21078 					    ipIfStatsOutNoRoutes);
21079 					goto drop_pkt;
21080 				}
21081 			}
21082 			if (xmit_ill != NULL) {
21083 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21084 				if (ipif == NULL) {
21085 					ip1dbg(("ip_wput: No ipif for "
21086 					    "xmit_ill\n"));
21087 					BUMP_MIB(&ipst->ips_ip_mib,
21088 					    ipIfStatsOutNoRoutes);
21089 					goto drop_pkt;
21090 				}
21091 			} else if (ipif == NULL || ipif->ipif_isv6) {
21092 				/*
21093 				 * We must do this ipif determination here
21094 				 * else we could pass through ip_newroute
21095 				 * and come back here without the conn context.
21096 				 *
21097 				 * Note: we do late binding i.e. we bind to
21098 				 * the interface when the first packet is sent.
21099 				 * For performance reasons we do not rebind on
21100 				 * each packet but keep the binding until the
21101 				 * next IP_MULTICAST_IF option.
21102 				 *
21103 				 * conn_multicast_{ipif,ill} are shared between
21104 				 * IPv4 and IPv6 and AF_INET6 sockets can
21105 				 * send both IPv4 and IPv6 packets. Hence
21106 				 * we have to check that "isv6" matches above.
21107 				 */
21108 				if (ipif != NULL)
21109 					ipif_refrele(ipif);
21110 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21111 				if (ipif == NULL) {
21112 					ip1dbg(("ip_wput: No ipif for "
21113 					    "multicast\n"));
21114 					BUMP_MIB(&ipst->ips_ip_mib,
21115 					    ipIfStatsOutNoRoutes);
21116 					goto drop_pkt;
21117 				}
21118 				err = conn_set_held_ipif(connp,
21119 				    &connp->conn_multicast_ipif, ipif);
21120 				if (err == IPIF_LOOKUP_FAILED) {
21121 					ipif_refrele(ipif);
21122 					ip1dbg(("ip_wput: No ipif for "
21123 					    "multicast\n"));
21124 					BUMP_MIB(&ipst->ips_ip_mib,
21125 					    ipIfStatsOutNoRoutes);
21126 					goto drop_pkt;
21127 				}
21128 			}
21129 		}
21130 		ASSERT(!ipif->ipif_isv6);
21131 		/*
21132 		 * As we may lose the conn by the time we reach ip_wput_ire,
21133 		 * we copy conn_multicast_loop and conn_dontroute on to an
21134 		 * ipsec_out. In case if this datagram goes out secure,
21135 		 * we need the ill_index also. Copy that also into the
21136 		 * ipsec_out.
21137 		 */
21138 		if (mctl_present) {
21139 			io = (ipsec_out_t *)first_mp->b_rptr;
21140 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21141 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21142 		} else {
21143 			ASSERT(mp == first_mp);
21144 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21145 			    BPRI_HI)) == NULL) {
21146 				ipif_refrele(ipif);
21147 				first_mp = mp;
21148 				goto discard_pkt;
21149 			}
21150 			first_mp->b_datap->db_type = M_CTL;
21151 			first_mp->b_wptr += sizeof (ipsec_info_t);
21152 			/* ipsec_out_secure is B_FALSE now */
21153 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21154 			io = (ipsec_out_t *)first_mp->b_rptr;
21155 			io->ipsec_out_type = IPSEC_OUT;
21156 			io->ipsec_out_len = sizeof (ipsec_out_t);
21157 			io->ipsec_out_use_global_policy = B_TRUE;
21158 			io->ipsec_out_ns = ipst->ips_netstack;
21159 			first_mp->b_cont = mp;
21160 			mctl_present = B_TRUE;
21161 		}
21162 
21163 		match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21164 		io->ipsec_out_ill_index =
21165 		    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21166 
21167 		if (connp != NULL) {
21168 			io->ipsec_out_multicast_loop =
21169 			    connp->conn_multicast_loop;
21170 			io->ipsec_out_dontroute = connp->conn_dontroute;
21171 			io->ipsec_out_zoneid = connp->conn_zoneid;
21172 		}
21173 		/*
21174 		 * If the application uses IP_MULTICAST_IF with
21175 		 * different logical addresses of the same ILL, we
21176 		 * need to make sure that the soruce address of
21177 		 * the packet matches the logical IP address used
21178 		 * in the option. We do it by initializing ipha_src
21179 		 * here. This should keep IPsec also happy as
21180 		 * when we return from IPsec processing, we don't
21181 		 * have to worry about getting the right address on
21182 		 * the packet. Thus it is sufficient to look for
21183 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21184 		 * MATCH_IRE_IPIF.
21185 		 *
21186 		 * NOTE : We need to do it for non-secure case also as
21187 		 * this might go out secure if there is a global policy
21188 		 * match in ip_wput_ire.
21189 		 *
21190 		 * As we do not have the ire yet, it is possible that
21191 		 * we set the source address here and then later discover
21192 		 * that the ire implies the source address to be assigned
21193 		 * through the RTF_SETSRC flag.
21194 		 * In that case, the setsrc variable will remind us
21195 		 * that overwritting the source address by the one
21196 		 * of the RTF_SETSRC-flagged ire is allowed.
21197 		 */
21198 		if (ipha->ipha_src == INADDR_ANY &&
21199 		    (connp == NULL || !connp->conn_unspec_src)) {
21200 			ipha->ipha_src = ipif->ipif_src_addr;
21201 			setsrc = RTF_SETSRC;
21202 		}
21203 		/*
21204 		 * Find an IRE which matches the destination and the outgoing
21205 		 * queue (i.e. the outgoing interface.)
21206 		 * For loopback use a unicast IP address for
21207 		 * the ire lookup.
21208 		 */
21209 		if (IS_LOOPBACK(ipif->ipif_ill))
21210 			dst = ipif->ipif_lcl_addr;
21211 
21212 		/*
21213 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21214 		 * We don't need to lookup ire in ctable as the packet
21215 		 * needs to be sent to the destination through the specified
21216 		 * ill irrespective of ires in the cache table.
21217 		 */
21218 		ire = NULL;
21219 		if (xmit_ill == NULL) {
21220 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21221 			    zoneid, msg_getlabel(mp), match_flags, ipst);
21222 		}
21223 
21224 		if (ire == NULL) {
21225 			/*
21226 			 * Multicast loopback and multicast forwarding is
21227 			 * done in ip_wput_ire.
21228 			 *
21229 			 * Mark this packet to make it be delivered to
21230 			 * ip_wput_ire after the new ire has been
21231 			 * created.
21232 			 *
21233 			 * The call to ip_newroute_ipif takes into account
21234 			 * the setsrc reminder. In any case, we take care
21235 			 * of the RTF_MULTIRT flag.
21236 			 */
21237 			mp->b_prev = mp->b_next = NULL;
21238 			if (xmit_ill == NULL ||
21239 			    xmit_ill->ill_ipif_up_count > 0) {
21240 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21241 				    setsrc | RTF_MULTIRT, zoneid, infop);
21242 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21243 				    "ip_wput_end: q %p (%S)", q, "noire");
21244 			} else {
21245 				freemsg(first_mp);
21246 			}
21247 			ipif_refrele(ipif);
21248 			if (xmit_ill != NULL)
21249 				ill_refrele(xmit_ill);
21250 			if (need_decref)
21251 				CONN_DEC_REF(connp);
21252 			return;
21253 		}
21254 
21255 		ipif_refrele(ipif);
21256 		ipif = NULL;
21257 		ASSERT(xmit_ill == NULL);
21258 
21259 		/*
21260 		 * Honor the RTF_SETSRC flag for multicast packets,
21261 		 * if allowed by the setsrc reminder.
21262 		 */
21263 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21264 			ipha->ipha_src = ire->ire_src_addr;
21265 		}
21266 
21267 		/*
21268 		 * Unconditionally force the TTL to 1 for
21269 		 * multirouted multicast packets:
21270 		 * multirouted multicast should not cross
21271 		 * multicast routers.
21272 		 */
21273 		if (ire->ire_flags & RTF_MULTIRT) {
21274 			if (ipha->ipha_ttl > 1) {
21275 				ip2dbg(("ip_wput: forcing multicast "
21276 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21277 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21278 				ipha->ipha_ttl = 1;
21279 			}
21280 		}
21281 	} else {
21282 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
21283 		if ((ire != NULL) && (ire->ire_type &
21284 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21285 			ignore_dontroute = B_TRUE;
21286 			ignore_nexthop = B_TRUE;
21287 		}
21288 		if (ire != NULL) {
21289 			ire_refrele(ire);
21290 			ire = NULL;
21291 		}
21292 		/*
21293 		 * Guard against coming in from arp in which case conn is NULL.
21294 		 * Also guard against non M_DATA with dontroute set but
21295 		 * destined to local, loopback or broadcast addresses.
21296 		 */
21297 		if (connp != NULL && connp->conn_dontroute &&
21298 		    !ignore_dontroute) {
21299 dontroute:
21300 			/*
21301 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21302 			 * routing protocols from seeing false direct
21303 			 * connectivity.
21304 			 */
21305 			ipha->ipha_ttl = 1;
21306 			/* If suitable ipif not found, drop packet */
21307 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21308 			if (dst_ipif == NULL) {
21309 noroute:
21310 				ip1dbg(("ip_wput: no route for dst using"
21311 				    " SO_DONTROUTE\n"));
21312 				BUMP_MIB(&ipst->ips_ip_mib,
21313 				    ipIfStatsOutNoRoutes);
21314 				mp->b_prev = mp->b_next = NULL;
21315 				if (first_mp == NULL)
21316 					first_mp = mp;
21317 				goto drop_pkt;
21318 			} else {
21319 				/*
21320 				 * If suitable ipif has been found, set
21321 				 * xmit_ill to the corresponding
21322 				 * ipif_ill because we'll be using the
21323 				 * send_from_ill logic below.
21324 				 */
21325 				ASSERT(xmit_ill == NULL);
21326 				xmit_ill = dst_ipif->ipif_ill;
21327 				mutex_enter(&xmit_ill->ill_lock);
21328 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21329 					mutex_exit(&xmit_ill->ill_lock);
21330 					xmit_ill = NULL;
21331 					ipif_refrele(dst_ipif);
21332 					goto noroute;
21333 				}
21334 				ill_refhold_locked(xmit_ill);
21335 				mutex_exit(&xmit_ill->ill_lock);
21336 				ipif_refrele(dst_ipif);
21337 			}
21338 		}
21339 
21340 send_from_ill:
21341 		if (xmit_ill != NULL) {
21342 			ipif_t *ipif;
21343 
21344 			/*
21345 			 * Mark this packet as originated locally
21346 			 */
21347 			mp->b_prev = mp->b_next = NULL;
21348 
21349 			/*
21350 			 * Could be SO_DONTROUTE case also.
21351 			 * Verify that at least one ipif is up on the ill.
21352 			 */
21353 			if (xmit_ill->ill_ipif_up_count == 0) {
21354 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21355 				    xmit_ill->ill_name));
21356 				goto drop_pkt;
21357 			}
21358 
21359 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21360 			if (ipif == NULL) {
21361 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21362 				    xmit_ill->ill_name));
21363 				goto drop_pkt;
21364 			}
21365 
21366 			match_flags = 0;
21367 			if (IS_UNDER_IPMP(xmit_ill))
21368 				match_flags |= MATCH_IRE_MARK_TESTHIDDEN;
21369 
21370 			/*
21371 			 * Look for a ire that is part of the group,
21372 			 * if found use it else call ip_newroute_ipif.
21373 			 * IPCL_ZONEID is not used for matching because
21374 			 * IP_ALLZONES option is valid only when the
21375 			 * ill is accessible from all zones i.e has a
21376 			 * valid ipif in all zones.
21377 			 */
21378 			match_flags |= MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21379 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21380 			    msg_getlabel(mp), match_flags, ipst);
21381 			/*
21382 			 * If an ire exists use it or else create
21383 			 * an ire but don't add it to the cache.
21384 			 * Adding an ire may cause issues with
21385 			 * asymmetric routing.
21386 			 * In case of multiroute always act as if
21387 			 * ire does not exist.
21388 			 */
21389 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21390 				if (ire != NULL)
21391 					ire_refrele(ire);
21392 				ip_newroute_ipif(q, first_mp, ipif,
21393 				    dst, connp, 0, zoneid, infop);
21394 				ipif_refrele(ipif);
21395 				ip1dbg(("ip_output: xmit_ill via %s\n",
21396 				    xmit_ill->ill_name));
21397 				ill_refrele(xmit_ill);
21398 				if (need_decref)
21399 					CONN_DEC_REF(connp);
21400 				return;
21401 			}
21402 			ipif_refrele(ipif);
21403 		} else if (ip_nexthop || (connp != NULL &&
21404 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21405 			if (!ip_nexthop) {
21406 				ip_nexthop = B_TRUE;
21407 				nexthop_addr = connp->conn_nexthop_v4;
21408 			}
21409 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21410 			    MATCH_IRE_GW;
21411 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21412 			    NULL, zoneid, msg_getlabel(mp), match_flags, ipst);
21413 		} else {
21414 			ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp),
21415 			    ipst);
21416 		}
21417 		if (!ire) {
21418 			if (ip_nexthop && !ignore_nexthop) {
21419 				if (mctl_present) {
21420 					io = (ipsec_out_t *)first_mp->b_rptr;
21421 					ASSERT(first_mp->b_datap->db_type ==
21422 					    M_CTL);
21423 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21424 				} else {
21425 					ASSERT(mp == first_mp);
21426 					first_mp = allocb(
21427 					    sizeof (ipsec_info_t), BPRI_HI);
21428 					if (first_mp == NULL) {
21429 						first_mp = mp;
21430 						goto discard_pkt;
21431 					}
21432 					first_mp->b_datap->db_type = M_CTL;
21433 					first_mp->b_wptr +=
21434 					    sizeof (ipsec_info_t);
21435 					/* ipsec_out_secure is B_FALSE now */
21436 					bzero(first_mp->b_rptr,
21437 					    sizeof (ipsec_info_t));
21438 					io = (ipsec_out_t *)first_mp->b_rptr;
21439 					io->ipsec_out_type = IPSEC_OUT;
21440 					io->ipsec_out_len =
21441 					    sizeof (ipsec_out_t);
21442 					io->ipsec_out_use_global_policy =
21443 					    B_TRUE;
21444 					io->ipsec_out_ns = ipst->ips_netstack;
21445 					first_mp->b_cont = mp;
21446 					mctl_present = B_TRUE;
21447 				}
21448 				io->ipsec_out_ip_nexthop = ip_nexthop;
21449 				io->ipsec_out_nexthop_addr = nexthop_addr;
21450 			}
21451 noirefound:
21452 			/*
21453 			 * Mark this packet as having originated on
21454 			 * this machine.  This will be noted in
21455 			 * ire_add_then_send, which needs to know
21456 			 * whether to run it back through ip_wput or
21457 			 * ip_rput following successful resolution.
21458 			 */
21459 			mp->b_prev = NULL;
21460 			mp->b_next = NULL;
21461 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21462 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21463 			    "ip_wput_end: q %p (%S)", q, "newroute");
21464 			if (xmit_ill != NULL)
21465 				ill_refrele(xmit_ill);
21466 			if (need_decref)
21467 				CONN_DEC_REF(connp);
21468 			return;
21469 		}
21470 	}
21471 
21472 	/* We now know where we are going with it. */
21473 
21474 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21475 	    "ip_wput_end: q %p (%S)", q, "end");
21476 
21477 	/*
21478 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21479 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21480 	 */
21481 	if (ire->ire_flags & RTF_MULTIRT) {
21482 		/*
21483 		 * Force the TTL of multirouted packets if required.
21484 		 * The TTL of such packets is bounded by the
21485 		 * ip_multirt_ttl ndd variable.
21486 		 */
21487 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21488 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21489 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21490 			    "(was %d), dst 0x%08x\n",
21491 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21492 			    ntohl(ire->ire_addr)));
21493 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21494 		}
21495 		/*
21496 		 * At this point, we check to see if there are any pending
21497 		 * unresolved routes. ire_multirt_resolvable()
21498 		 * checks in O(n) that all IRE_OFFSUBNET ire
21499 		 * entries for the packet's destination and
21500 		 * flagged RTF_MULTIRT are currently resolved.
21501 		 * If some remain unresolved, we make a copy
21502 		 * of the current message. It will be used
21503 		 * to initiate additional route resolutions.
21504 		 */
21505 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21506 		    msg_getlabel(first_mp), ipst);
21507 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21508 		    "multirt_need_resolve %d, first_mp %p\n",
21509 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21510 		if (multirt_need_resolve) {
21511 			copy_mp = copymsg(first_mp);
21512 			if (copy_mp != NULL) {
21513 				MULTIRT_DEBUG_TAG(copy_mp);
21514 			}
21515 		}
21516 	}
21517 
21518 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21519 	/*
21520 	 * Try to resolve another multiroute if
21521 	 * ire_multirt_resolvable() deemed it necessary.
21522 	 * At this point, we need to distinguish
21523 	 * multicasts from other packets. For multicasts,
21524 	 * we call ip_newroute_ipif() and request that both
21525 	 * multirouting and setsrc flags are checked.
21526 	 */
21527 	if (copy_mp != NULL) {
21528 		if (CLASSD(dst)) {
21529 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21530 			if (ipif) {
21531 				ASSERT(infop->ip_opt_ill_index == 0);
21532 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21533 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21534 				ipif_refrele(ipif);
21535 			} else {
21536 				MULTIRT_DEBUG_UNTAG(copy_mp);
21537 				freemsg(copy_mp);
21538 				copy_mp = NULL;
21539 			}
21540 		} else {
21541 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21542 		}
21543 	}
21544 	if (xmit_ill != NULL)
21545 		ill_refrele(xmit_ill);
21546 	if (need_decref)
21547 		CONN_DEC_REF(connp);
21548 	return;
21549 
21550 icmp_parameter_problem:
21551 	/* could not have originated externally */
21552 	ASSERT(mp->b_prev == NULL);
21553 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21554 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21555 		/* it's the IP header length that's in trouble */
21556 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21557 		first_mp = NULL;
21558 	}
21559 
21560 discard_pkt:
21561 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21562 drop_pkt:
21563 	ip1dbg(("ip_wput: dropped packet\n"));
21564 	if (ire != NULL)
21565 		ire_refrele(ire);
21566 	if (need_decref)
21567 		CONN_DEC_REF(connp);
21568 	freemsg(first_mp);
21569 	if (xmit_ill != NULL)
21570 		ill_refrele(xmit_ill);
21571 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21572 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21573 }
21574 
21575 /*
21576  * If this is a conn_t queue, then we pass in the conn. This includes the
21577  * zoneid.
21578  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21579  * in which case we use the global zoneid since those are all part of
21580  * the global zone.
21581  */
21582 void
21583 ip_wput(queue_t *q, mblk_t *mp)
21584 {
21585 	if (CONN_Q(q))
21586 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21587 	else
21588 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21589 }
21590 
21591 /*
21592  *
21593  * The following rules must be observed when accessing any ipif or ill
21594  * that has been cached in the conn. Typically conn_outgoing_ill,
21595  * conn_multicast_ipif and conn_multicast_ill.
21596  *
21597  * Access: The ipif or ill pointed to from the conn can be accessed under
21598  * the protection of the conn_lock or after it has been refheld under the
21599  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21600  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21601  * The reason for this is that a concurrent unplumb could actually be
21602  * cleaning up these cached pointers by walking the conns and might have
21603  * finished cleaning up the conn in question. The macros check that an
21604  * unplumb has not yet started on the ipif or ill.
21605  *
21606  * Caching: An ipif or ill pointer may be cached in the conn only after
21607  * making sure that an unplumb has not started. So the caching is done
21608  * while holding both the conn_lock and the ill_lock and after using the
21609  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21610  * flag before starting the cleanup of conns.
21611  *
21612  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21613  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21614  * or a reference to the ipif or a reference to an ire that references the
21615  * ipif. An ipif only changes its ill when migrating from an underlying ill
21616  * to an IPMP ill in ipif_up().
21617  */
21618 ipif_t *
21619 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21620 {
21621 	ipif_t	*ipif;
21622 	ill_t	*ill;
21623 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21624 
21625 	*err = 0;
21626 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21627 	mutex_enter(&connp->conn_lock);
21628 	ipif = *ipifp;
21629 	if (ipif != NULL) {
21630 		ill = ipif->ipif_ill;
21631 		mutex_enter(&ill->ill_lock);
21632 		if (IPIF_CAN_LOOKUP(ipif)) {
21633 			ipif_refhold_locked(ipif);
21634 			mutex_exit(&ill->ill_lock);
21635 			mutex_exit(&connp->conn_lock);
21636 			rw_exit(&ipst->ips_ill_g_lock);
21637 			return (ipif);
21638 		} else {
21639 			*err = IPIF_LOOKUP_FAILED;
21640 		}
21641 		mutex_exit(&ill->ill_lock);
21642 	}
21643 	mutex_exit(&connp->conn_lock);
21644 	rw_exit(&ipst->ips_ill_g_lock);
21645 	return (NULL);
21646 }
21647 
21648 ill_t *
21649 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21650 {
21651 	ill_t	*ill;
21652 
21653 	*err = 0;
21654 	mutex_enter(&connp->conn_lock);
21655 	ill = *illp;
21656 	if (ill != NULL) {
21657 		mutex_enter(&ill->ill_lock);
21658 		if (ILL_CAN_LOOKUP(ill)) {
21659 			ill_refhold_locked(ill);
21660 			mutex_exit(&ill->ill_lock);
21661 			mutex_exit(&connp->conn_lock);
21662 			return (ill);
21663 		} else {
21664 			*err = ILL_LOOKUP_FAILED;
21665 		}
21666 		mutex_exit(&ill->ill_lock);
21667 	}
21668 	mutex_exit(&connp->conn_lock);
21669 	return (NULL);
21670 }
21671 
21672 static int
21673 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21674 {
21675 	ill_t	*ill;
21676 
21677 	ill = ipif->ipif_ill;
21678 	mutex_enter(&connp->conn_lock);
21679 	mutex_enter(&ill->ill_lock);
21680 	if (IPIF_CAN_LOOKUP(ipif)) {
21681 		*ipifp = ipif;
21682 		mutex_exit(&ill->ill_lock);
21683 		mutex_exit(&connp->conn_lock);
21684 		return (0);
21685 	}
21686 	mutex_exit(&ill->ill_lock);
21687 	mutex_exit(&connp->conn_lock);
21688 	return (IPIF_LOOKUP_FAILED);
21689 }
21690 
21691 /*
21692  * This is called if the outbound datagram needs fragmentation.
21693  *
21694  * NOTE : This function does not ire_refrele the ire argument passed in.
21695  */
21696 static void
21697 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21698     ip_stack_t *ipst, conn_t *connp)
21699 {
21700 	ipha_t		*ipha;
21701 	mblk_t		*mp;
21702 	uint32_t	v_hlen_tos_len;
21703 	uint32_t	max_frag;
21704 	uint32_t	frag_flag;
21705 	boolean_t	dont_use;
21706 
21707 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21708 		mp = ipsec_mp->b_cont;
21709 	} else {
21710 		mp = ipsec_mp;
21711 	}
21712 
21713 	ipha = (ipha_t *)mp->b_rptr;
21714 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21715 
21716 #ifdef	_BIG_ENDIAN
21717 #define	V_HLEN	(v_hlen_tos_len >> 24)
21718 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21719 #else
21720 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21721 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21722 #endif
21723 
21724 #ifndef SPEED_BEFORE_SAFETY
21725 	/*
21726 	 * Check that ipha_length is consistent with
21727 	 * the mblk length
21728 	 */
21729 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21730 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21731 		    LENGTH, msgdsize(mp)));
21732 		freemsg(ipsec_mp);
21733 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21734 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21735 		    "packet length mismatch");
21736 		return;
21737 	}
21738 #endif
21739 	/*
21740 	 * Don't use frag_flag if pre-built packet or source
21741 	 * routed or if multicast (since multicast packets do not solicit
21742 	 * ICMP "packet too big" messages). Get the values of
21743 	 * max_frag and frag_flag atomically by acquiring the
21744 	 * ire_lock.
21745 	 */
21746 	mutex_enter(&ire->ire_lock);
21747 	max_frag = ire->ire_max_frag;
21748 	frag_flag = ire->ire_frag_flag;
21749 	mutex_exit(&ire->ire_lock);
21750 
21751 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21752 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21753 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21754 
21755 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21756 	    (dont_use ? 0 : frag_flag), zoneid, ipst, connp);
21757 }
21758 
21759 /*
21760  * Used for deciding the MSS size for the upper layer. Thus
21761  * we need to check the outbound policy values in the conn.
21762  */
21763 int
21764 conn_ipsec_length(conn_t *connp)
21765 {
21766 	ipsec_latch_t *ipl;
21767 
21768 	ipl = connp->conn_latch;
21769 	if (ipl == NULL)
21770 		return (0);
21771 
21772 	if (ipl->ipl_out_policy == NULL)
21773 		return (0);
21774 
21775 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21776 }
21777 
21778 /*
21779  * Returns an estimate of the IPsec headers size. This is used if
21780  * we don't want to call into IPsec to get the exact size.
21781  */
21782 int
21783 ipsec_out_extra_length(mblk_t *ipsec_mp)
21784 {
21785 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21786 	ipsec_action_t *a;
21787 
21788 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21789 	if (!io->ipsec_out_secure)
21790 		return (0);
21791 
21792 	a = io->ipsec_out_act;
21793 
21794 	if (a == NULL) {
21795 		ASSERT(io->ipsec_out_policy != NULL);
21796 		a = io->ipsec_out_policy->ipsp_act;
21797 	}
21798 	ASSERT(a != NULL);
21799 
21800 	return (a->ipa_ovhd);
21801 }
21802 
21803 /*
21804  * Returns an estimate of the IPsec headers size. This is used if
21805  * we don't want to call into IPsec to get the exact size.
21806  */
21807 int
21808 ipsec_in_extra_length(mblk_t *ipsec_mp)
21809 {
21810 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21811 	ipsec_action_t *a;
21812 
21813 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21814 
21815 	a = ii->ipsec_in_action;
21816 	return (a == NULL ? 0 : a->ipa_ovhd);
21817 }
21818 
21819 /*
21820  * If there are any source route options, return the true final
21821  * destination. Otherwise, return the destination.
21822  */
21823 ipaddr_t
21824 ip_get_dst(ipha_t *ipha)
21825 {
21826 	ipoptp_t	opts;
21827 	uchar_t		*opt;
21828 	uint8_t		optval;
21829 	uint8_t		optlen;
21830 	ipaddr_t	dst;
21831 	uint32_t off;
21832 
21833 	dst = ipha->ipha_dst;
21834 
21835 	if (IS_SIMPLE_IPH(ipha))
21836 		return (dst);
21837 
21838 	for (optval = ipoptp_first(&opts, ipha);
21839 	    optval != IPOPT_EOL;
21840 	    optval = ipoptp_next(&opts)) {
21841 		opt = opts.ipoptp_cur;
21842 		optlen = opts.ipoptp_len;
21843 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21844 		switch (optval) {
21845 		case IPOPT_SSRR:
21846 		case IPOPT_LSRR:
21847 			off = opt[IPOPT_OFFSET];
21848 			/*
21849 			 * If one of the conditions is true, it means
21850 			 * end of options and dst already has the right
21851 			 * value.
21852 			 */
21853 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21854 				off = optlen - IP_ADDR_LEN;
21855 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21856 			}
21857 			return (dst);
21858 		default:
21859 			break;
21860 		}
21861 	}
21862 
21863 	return (dst);
21864 }
21865 
21866 mblk_t *
21867 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21868     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21869 {
21870 	ipsec_out_t	*io;
21871 	mblk_t		*first_mp;
21872 	boolean_t policy_present;
21873 	ip_stack_t	*ipst;
21874 	ipsec_stack_t	*ipss;
21875 
21876 	ASSERT(ire != NULL);
21877 	ipst = ire->ire_ipst;
21878 	ipss = ipst->ips_netstack->netstack_ipsec;
21879 
21880 	first_mp = mp;
21881 	if (mp->b_datap->db_type == M_CTL) {
21882 		io = (ipsec_out_t *)first_mp->b_rptr;
21883 		/*
21884 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21885 		 *
21886 		 * 1) There is per-socket policy (including cached global
21887 		 *    policy) or a policy on the IP-in-IP tunnel.
21888 		 * 2) There is no per-socket policy, but it is
21889 		 *    a multicast packet that needs to go out
21890 		 *    on a specific interface. This is the case
21891 		 *    where (ip_wput and ip_wput_multicast) attaches
21892 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21893 		 *
21894 		 * In case (2) we check with global policy to
21895 		 * see if there is a match and set the ill_index
21896 		 * appropriately so that we can lookup the ire
21897 		 * properly in ip_wput_ipsec_out.
21898 		 */
21899 
21900 		/*
21901 		 * ipsec_out_use_global_policy is set to B_FALSE
21902 		 * in ipsec_in_to_out(). Refer to that function for
21903 		 * details.
21904 		 */
21905 		if ((io->ipsec_out_latch == NULL) &&
21906 		    (io->ipsec_out_use_global_policy)) {
21907 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21908 			    ire, connp, unspec_src, zoneid));
21909 		}
21910 		if (!io->ipsec_out_secure) {
21911 			/*
21912 			 * If this is not a secure packet, drop
21913 			 * the IPSEC_OUT mp and treat it as a clear
21914 			 * packet. This happens when we are sending
21915 			 * a ICMP reply back to a clear packet. See
21916 			 * ipsec_in_to_out() for details.
21917 			 */
21918 			mp = first_mp->b_cont;
21919 			freeb(first_mp);
21920 		}
21921 		return (mp);
21922 	}
21923 	/*
21924 	 * See whether we need to attach a global policy here. We
21925 	 * don't depend on the conn (as it could be null) for deciding
21926 	 * what policy this datagram should go through because it
21927 	 * should have happened in ip_wput if there was some
21928 	 * policy. This normally happens for connections which are not
21929 	 * fully bound preventing us from caching policies in
21930 	 * ip_bind. Packets coming from the TCP listener/global queue
21931 	 * - which are non-hard_bound - could also be affected by
21932 	 * applying policy here.
21933 	 *
21934 	 * If this packet is coming from tcp global queue or listener,
21935 	 * we will be applying policy here.  This may not be *right*
21936 	 * if these packets are coming from the detached connection as
21937 	 * it could have gone in clear before. This happens only if a
21938 	 * TCP connection started when there is no policy and somebody
21939 	 * added policy before it became detached. Thus packets of the
21940 	 * detached connection could go out secure and the other end
21941 	 * would drop it because it will be expecting in clear. The
21942 	 * converse is not true i.e if somebody starts a TCP
21943 	 * connection and deletes the policy, all the packets will
21944 	 * still go out with the policy that existed before deleting
21945 	 * because ip_unbind sends up policy information which is used
21946 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21947 	 * TCP to attach a dummy IPSEC_OUT and set
21948 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21949 	 * affect performance for normal cases, we are not doing it.
21950 	 * Thus, set policy before starting any TCP connections.
21951 	 *
21952 	 * NOTE - We might apply policy even for a hard bound connection
21953 	 * - for which we cached policy in ip_bind - if somebody added
21954 	 * global policy after we inherited the policy in ip_bind.
21955 	 * This means that the packets that were going out in clear
21956 	 * previously would start going secure and hence get dropped
21957 	 * on the other side. To fix this, TCP attaches a dummy
21958 	 * ipsec_out and make sure that we don't apply global policy.
21959 	 */
21960 	if (ipha != NULL)
21961 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21962 	else
21963 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21964 	if (!policy_present)
21965 		return (mp);
21966 
21967 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21968 	    zoneid));
21969 }
21970 
21971 /*
21972  * This function does the ire_refrele of the ire passed in as the
21973  * argument. As this function looks up more ires i.e broadcast ires,
21974  * it needs to REFRELE them. Currently, for simplicity we don't
21975  * differentiate the one passed in and looked up here. We always
21976  * REFRELE.
21977  * IPQoS Notes:
21978  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21979  * IPsec packets are done in ipsec_out_process.
21980  */
21981 void
21982 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21983     zoneid_t zoneid)
21984 {
21985 	ipha_t		*ipha;
21986 #define	rptr	((uchar_t *)ipha)
21987 	queue_t		*stq;
21988 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21989 	uint32_t	v_hlen_tos_len;
21990 	uint32_t	ttl_protocol;
21991 	ipaddr_t	src;
21992 	ipaddr_t	dst;
21993 	uint32_t	cksum;
21994 	ipaddr_t	orig_src;
21995 	ire_t		*ire1;
21996 	mblk_t		*next_mp;
21997 	uint_t		hlen;
21998 	uint16_t	*up;
21999 	uint32_t	max_frag = ire->ire_max_frag;
22000 	ill_t		*ill = ire_to_ill(ire);
22001 	int		clusterwide;
22002 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22003 	int		ipsec_len;
22004 	mblk_t		*first_mp;
22005 	ipsec_out_t	*io;
22006 	boolean_t	conn_dontroute;		/* conn value for multicast */
22007 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22008 	boolean_t	multicast_forward;	/* Should we forward ? */
22009 	boolean_t	unspec_src;
22010 	ill_t		*conn_outgoing_ill = NULL;
22011 	ill_t		*ire_ill;
22012 	ill_t		*ire1_ill;
22013 	ill_t		*out_ill;
22014 	uint32_t 	ill_index = 0;
22015 	boolean_t	multirt_send = B_FALSE;
22016 	int		err;
22017 	ipxmit_state_t	pktxmit_state;
22018 	ip_stack_t	*ipst = ire->ire_ipst;
22019 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22020 
22021 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22022 	    "ip_wput_ire_start: q %p", q);
22023 
22024 	multicast_forward = B_FALSE;
22025 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22026 
22027 	if (ire->ire_flags & RTF_MULTIRT) {
22028 		/*
22029 		 * Multirouting case. The bucket where ire is stored
22030 		 * probably holds other RTF_MULTIRT flagged ire
22031 		 * to the destination. In this call to ip_wput_ire,
22032 		 * we attempt to send the packet through all
22033 		 * those ires. Thus, we first ensure that ire is the
22034 		 * first RTF_MULTIRT ire in the bucket,
22035 		 * before walking the ire list.
22036 		 */
22037 		ire_t *first_ire;
22038 		irb_t *irb = ire->ire_bucket;
22039 		ASSERT(irb != NULL);
22040 
22041 		/* Make sure we do not omit any multiroute ire. */
22042 		IRB_REFHOLD(irb);
22043 		for (first_ire = irb->irb_ire;
22044 		    first_ire != NULL;
22045 		    first_ire = first_ire->ire_next) {
22046 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22047 			    (first_ire->ire_addr == ire->ire_addr) &&
22048 			    !(first_ire->ire_marks &
22049 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
22050 				break;
22051 		}
22052 
22053 		if ((first_ire != NULL) && (first_ire != ire)) {
22054 			IRE_REFHOLD(first_ire);
22055 			ire_refrele(ire);
22056 			ire = first_ire;
22057 			ill = ire_to_ill(ire);
22058 		}
22059 		IRB_REFRELE(irb);
22060 	}
22061 
22062 	/*
22063 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22064 	 * for performance we don't grab the mutexs in the fastpath
22065 	 */
22066 	if (ire->ire_type == IRE_BROADCAST && connp != NULL &&
22067 	    connp->conn_outgoing_ill != NULL) {
22068 		conn_outgoing_ill = conn_get_held_ill(connp,
22069 		    &connp->conn_outgoing_ill, &err);
22070 		if (err == ILL_LOOKUP_FAILED) {
22071 			ire_refrele(ire);
22072 			freemsg(mp);
22073 			return;
22074 		}
22075 	}
22076 
22077 	if (mp->b_datap->db_type != M_CTL) {
22078 		ipha = (ipha_t *)mp->b_rptr;
22079 	} else {
22080 		io = (ipsec_out_t *)mp->b_rptr;
22081 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22082 		ASSERT(zoneid == io->ipsec_out_zoneid);
22083 		ASSERT(zoneid != ALL_ZONES);
22084 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22085 		dst = ipha->ipha_dst;
22086 		/*
22087 		 * For the multicast case, ipsec_out carries conn_dontroute and
22088 		 * conn_multicast_loop as conn may not be available here. We
22089 		 * need this for multicast loopback and forwarding which is done
22090 		 * later in the code.
22091 		 */
22092 		if (CLASSD(dst)) {
22093 			conn_dontroute = io->ipsec_out_dontroute;
22094 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22095 			/*
22096 			 * If conn_dontroute is not set or conn_multicast_loop
22097 			 * is set, we need to do forwarding/loopback. For
22098 			 * datagrams from ip_wput_multicast, conn_dontroute is
22099 			 * set to B_TRUE and conn_multicast_loop is set to
22100 			 * B_FALSE so that we neither do forwarding nor
22101 			 * loopback.
22102 			 */
22103 			if (!conn_dontroute || conn_multicast_loop)
22104 				multicast_forward = B_TRUE;
22105 		}
22106 	}
22107 
22108 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22109 	    ire->ire_zoneid != ALL_ZONES) {
22110 		/*
22111 		 * When a zone sends a packet to another zone, we try to deliver
22112 		 * the packet under the same conditions as if the destination
22113 		 * was a real node on the network. To do so, we look for a
22114 		 * matching route in the forwarding table.
22115 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22116 		 * ip_newroute() does.
22117 		 * Note that IRE_LOCAL are special, since they are used
22118 		 * when the zoneid doesn't match in some cases. This means that
22119 		 * we need to handle ipha_src differently since ire_src_addr
22120 		 * belongs to the receiving zone instead of the sending zone.
22121 		 * When ip_restrict_interzone_loopback is set, then
22122 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22123 		 * for loopback between zones when the logical "Ethernet" would
22124 		 * have looped them back.
22125 		 */
22126 		ire_t *src_ire;
22127 
22128 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22129 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22130 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22131 		if (src_ire != NULL &&
22132 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22133 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22134 		    ire_local_same_lan(ire, src_ire))) {
22135 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22136 				ipha->ipha_src = src_ire->ire_src_addr;
22137 			ire_refrele(src_ire);
22138 		} else {
22139 			ire_refrele(ire);
22140 			if (conn_outgoing_ill != NULL)
22141 				ill_refrele(conn_outgoing_ill);
22142 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22143 			if (src_ire != NULL) {
22144 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22145 					ire_refrele(src_ire);
22146 					freemsg(mp);
22147 					return;
22148 				}
22149 				ire_refrele(src_ire);
22150 			}
22151 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22152 				/* Failed */
22153 				freemsg(mp);
22154 				return;
22155 			}
22156 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22157 			    ipst);
22158 			return;
22159 		}
22160 	}
22161 
22162 	if (mp->b_datap->db_type == M_CTL ||
22163 	    ipss->ipsec_outbound_v4_policy_present) {
22164 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22165 		    unspec_src, zoneid);
22166 		if (mp == NULL) {
22167 			ire_refrele(ire);
22168 			if (conn_outgoing_ill != NULL)
22169 				ill_refrele(conn_outgoing_ill);
22170 			return;
22171 		}
22172 		/*
22173 		 * Trusted Extensions supports all-zones interfaces, so
22174 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22175 		 * the global zone.
22176 		 */
22177 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22178 			io = (ipsec_out_t *)mp->b_rptr;
22179 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22180 			zoneid = io->ipsec_out_zoneid;
22181 		}
22182 	}
22183 
22184 	first_mp = mp;
22185 	ipsec_len = 0;
22186 
22187 	if (first_mp->b_datap->db_type == M_CTL) {
22188 		io = (ipsec_out_t *)first_mp->b_rptr;
22189 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22190 		mp = first_mp->b_cont;
22191 		ipsec_len = ipsec_out_extra_length(first_mp);
22192 		ASSERT(ipsec_len >= 0);
22193 		/* We already picked up the zoneid from the M_CTL above */
22194 		ASSERT(zoneid == io->ipsec_out_zoneid);
22195 		ASSERT(zoneid != ALL_ZONES);
22196 
22197 		/*
22198 		 * Drop M_CTL here if IPsec processing is not needed.
22199 		 * (Non-IPsec use of M_CTL extracted any information it
22200 		 * needed above).
22201 		 */
22202 		if (ipsec_len == 0) {
22203 			freeb(first_mp);
22204 			first_mp = mp;
22205 		}
22206 	}
22207 
22208 	/*
22209 	 * Fast path for ip_wput_ire
22210 	 */
22211 
22212 	ipha = (ipha_t *)mp->b_rptr;
22213 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22214 	dst = ipha->ipha_dst;
22215 
22216 	/*
22217 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22218 	 * if the socket is a SOCK_RAW type. The transport checksum should
22219 	 * be provided in the pre-built packet, so we don't need to compute it.
22220 	 * Also, other application set flags, like DF, should not be altered.
22221 	 * Other transport MUST pass down zero.
22222 	 */
22223 	ip_hdr_included = ipha->ipha_ident;
22224 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22225 
22226 	if (CLASSD(dst)) {
22227 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22228 		    ntohl(dst),
22229 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22230 		    ntohl(ire->ire_addr)));
22231 	}
22232 
22233 /* Macros to extract header fields from data already in registers */
22234 #ifdef	_BIG_ENDIAN
22235 #define	V_HLEN	(v_hlen_tos_len >> 24)
22236 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22237 #define	PROTO	(ttl_protocol & 0xFF)
22238 #else
22239 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22240 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22241 #define	PROTO	(ttl_protocol >> 8)
22242 #endif
22243 
22244 	orig_src = src = ipha->ipha_src;
22245 	/* (The loop back to "another" is explained down below.) */
22246 another:;
22247 	/*
22248 	 * Assign an ident value for this packet.  We assign idents on
22249 	 * a per destination basis out of the IRE.  There could be
22250 	 * other threads targeting the same destination, so we have to
22251 	 * arrange for a atomic increment.  Note that we use a 32-bit
22252 	 * atomic add because it has better performance than its
22253 	 * 16-bit sibling.
22254 	 *
22255 	 * If running in cluster mode and if the source address
22256 	 * belongs to a replicated service then vector through
22257 	 * cl_inet_ipident vector to allocate ip identifier
22258 	 * NOTE: This is a contract private interface with the
22259 	 * clustering group.
22260 	 */
22261 	clusterwide = 0;
22262 	if (cl_inet_ipident) {
22263 		ASSERT(cl_inet_isclusterwide);
22264 		netstackid_t stack_id = ipst->ips_netstack->netstack_stackid;
22265 
22266 		if ((*cl_inet_isclusterwide)(stack_id, IPPROTO_IP,
22267 		    AF_INET, (uint8_t *)(uintptr_t)src, NULL)) {
22268 			ipha->ipha_ident = (*cl_inet_ipident)(stack_id,
22269 			    IPPROTO_IP, AF_INET, (uint8_t *)(uintptr_t)src,
22270 			    (uint8_t *)(uintptr_t)dst, NULL);
22271 			clusterwide = 1;
22272 		}
22273 	}
22274 	if (!clusterwide) {
22275 		ipha->ipha_ident =
22276 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22277 	}
22278 
22279 #ifndef _BIG_ENDIAN
22280 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22281 #endif
22282 
22283 	/*
22284 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22285 	 * This is needed to obey conn_unspec_src when packets go through
22286 	 * ip_newroute + arp.
22287 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22288 	 */
22289 	if (src == INADDR_ANY && !unspec_src) {
22290 		/*
22291 		 * Assign the appropriate source address from the IRE if none
22292 		 * was specified.
22293 		 */
22294 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22295 
22296 		src = ire->ire_src_addr;
22297 		if (connp == NULL) {
22298 			ip1dbg(("ip_wput_ire: no connp and no src "
22299 			    "address for dst 0x%x, using src 0x%x\n",
22300 			    ntohl(dst),
22301 			    ntohl(src)));
22302 		}
22303 		ipha->ipha_src = src;
22304 	}
22305 	stq = ire->ire_stq;
22306 
22307 	/*
22308 	 * We only allow ire chains for broadcasts since there will
22309 	 * be multiple IRE_CACHE entries for the same multicast
22310 	 * address (one per ipif).
22311 	 */
22312 	next_mp = NULL;
22313 
22314 	/* broadcast packet */
22315 	if (ire->ire_type == IRE_BROADCAST)
22316 		goto broadcast;
22317 
22318 	/* loopback ? */
22319 	if (stq == NULL)
22320 		goto nullstq;
22321 
22322 	/* The ill_index for outbound ILL */
22323 	ill_index = Q_TO_INDEX(stq);
22324 
22325 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22326 	ttl_protocol = ((uint16_t *)ipha)[4];
22327 
22328 	/* pseudo checksum (do it in parts for IP header checksum) */
22329 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22330 
22331 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22332 		queue_t *dev_q = stq->q_next;
22333 
22334 		/* flow controlled */
22335 		if (DEV_Q_FLOW_BLOCKED(dev_q))
22336 			goto blocked;
22337 
22338 		if ((PROTO == IPPROTO_UDP) &&
22339 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22340 			hlen = (V_HLEN & 0xF) << 2;
22341 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22342 			if (*up != 0) {
22343 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22344 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22345 				/* Software checksum? */
22346 				if (DB_CKSUMFLAGS(mp) == 0) {
22347 					IP_STAT(ipst, ip_out_sw_cksum);
22348 					IP_STAT_UPDATE(ipst,
22349 					    ip_udp_out_sw_cksum_bytes,
22350 					    LENGTH - hlen);
22351 				}
22352 			}
22353 		}
22354 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22355 		hlen = (V_HLEN & 0xF) << 2;
22356 		if (PROTO == IPPROTO_TCP) {
22357 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22358 			/*
22359 			 * The packet header is processed once and for all, even
22360 			 * in the multirouting case. We disable hardware
22361 			 * checksum if the packet is multirouted, as it will be
22362 			 * replicated via several interfaces, and not all of
22363 			 * them may have this capability.
22364 			 */
22365 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22366 			    LENGTH, max_frag, ipsec_len, cksum);
22367 			/* Software checksum? */
22368 			if (DB_CKSUMFLAGS(mp) == 0) {
22369 				IP_STAT(ipst, ip_out_sw_cksum);
22370 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22371 				    LENGTH - hlen);
22372 			}
22373 		} else {
22374 			sctp_hdr_t	*sctph;
22375 
22376 			ASSERT(PROTO == IPPROTO_SCTP);
22377 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22378 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22379 			/*
22380 			 * Zero out the checksum field to ensure proper
22381 			 * checksum calculation.
22382 			 */
22383 			sctph->sh_chksum = 0;
22384 #ifdef	DEBUG
22385 			if (!skip_sctp_cksum)
22386 #endif
22387 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22388 		}
22389 	}
22390 
22391 	/*
22392 	 * If this is a multicast packet and originated from ip_wput
22393 	 * we need to do loopback and forwarding checks. If it comes
22394 	 * from ip_wput_multicast, we SHOULD not do this.
22395 	 */
22396 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22397 
22398 	/* checksum */
22399 	cksum += ttl_protocol;
22400 
22401 	/* fragment the packet */
22402 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22403 		goto fragmentit;
22404 	/*
22405 	 * Don't use frag_flag if packet is pre-built or source
22406 	 * routed or if multicast (since multicast packets do
22407 	 * not solicit ICMP "packet too big" messages).
22408 	 */
22409 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22410 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22411 	    !ip_source_route_included(ipha)) &&
22412 	    !CLASSD(ipha->ipha_dst))
22413 		ipha->ipha_fragment_offset_and_flags |=
22414 		    htons(ire->ire_frag_flag);
22415 
22416 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22417 		/* calculate IP header checksum */
22418 		cksum += ipha->ipha_ident;
22419 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22420 		cksum += ipha->ipha_fragment_offset_and_flags;
22421 
22422 		/* IP options present */
22423 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22424 		if (hlen)
22425 			goto checksumoptions;
22426 
22427 		/* calculate hdr checksum */
22428 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22429 		cksum = ~(cksum + (cksum >> 16));
22430 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22431 	}
22432 	if (ipsec_len != 0) {
22433 		/*
22434 		 * We will do the rest of the processing after
22435 		 * we come back from IPsec in ip_wput_ipsec_out().
22436 		 */
22437 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22438 
22439 		io = (ipsec_out_t *)first_mp->b_rptr;
22440 		io->ipsec_out_ill_index =
22441 		    ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
22442 		ipsec_out_process(q, first_mp, ire, 0);
22443 		ire_refrele(ire);
22444 		if (conn_outgoing_ill != NULL)
22445 			ill_refrele(conn_outgoing_ill);
22446 		return;
22447 	}
22448 
22449 	/*
22450 	 * In most cases, the emission loop below is entered only
22451 	 * once. Only in the case where the ire holds the
22452 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22453 	 * flagged ires in the bucket, and send the packet
22454 	 * through all crossed RTF_MULTIRT routes.
22455 	 */
22456 	if (ire->ire_flags & RTF_MULTIRT) {
22457 		multirt_send = B_TRUE;
22458 	}
22459 	do {
22460 		if (multirt_send) {
22461 			irb_t *irb;
22462 			/*
22463 			 * We are in a multiple send case, need to get
22464 			 * the next ire and make a duplicate of the packet.
22465 			 * ire1 holds here the next ire to process in the
22466 			 * bucket. If multirouting is expected,
22467 			 * any non-RTF_MULTIRT ire that has the
22468 			 * right destination address is ignored.
22469 			 */
22470 			irb = ire->ire_bucket;
22471 			ASSERT(irb != NULL);
22472 
22473 			IRB_REFHOLD(irb);
22474 			for (ire1 = ire->ire_next;
22475 			    ire1 != NULL;
22476 			    ire1 = ire1->ire_next) {
22477 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22478 					continue;
22479 				if (ire1->ire_addr != ire->ire_addr)
22480 					continue;
22481 				if (ire1->ire_marks &
22482 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
22483 					continue;
22484 
22485 				/* Got one */
22486 				IRE_REFHOLD(ire1);
22487 				break;
22488 			}
22489 			IRB_REFRELE(irb);
22490 
22491 			if (ire1 != NULL) {
22492 				next_mp = copyb(mp);
22493 				if ((next_mp == NULL) ||
22494 				    ((mp->b_cont != NULL) &&
22495 				    ((next_mp->b_cont =
22496 				    dupmsg(mp->b_cont)) == NULL))) {
22497 					freemsg(next_mp);
22498 					next_mp = NULL;
22499 					ire_refrele(ire1);
22500 					ire1 = NULL;
22501 				}
22502 			}
22503 
22504 			/* Last multiroute ire; don't loop anymore. */
22505 			if (ire1 == NULL) {
22506 				multirt_send = B_FALSE;
22507 			}
22508 		}
22509 
22510 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22511 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22512 		    mblk_t *, mp);
22513 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22514 		    ipst->ips_ipv4firewall_physical_out,
22515 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22516 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22517 
22518 		if (mp == NULL)
22519 			goto release_ire_and_ill;
22520 
22521 		if (ipst->ips_ipobs_enabled) {
22522 			zoneid_t szone;
22523 
22524 			/*
22525 			 * On the outbound path the destination zone will be
22526 			 * unknown as we're sending this packet out on the
22527 			 * wire.
22528 			 */
22529 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
22530 			    ALL_ZONES);
22531 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
22532 			    ire->ire_ipif->ipif_ill, IPV4_VERSION, 0, ipst);
22533 		}
22534 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22535 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22536 
22537 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE, connp);
22538 
22539 		if ((pktxmit_state == SEND_FAILED) ||
22540 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22541 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22542 			    "- packet dropped\n"));
22543 release_ire_and_ill:
22544 			ire_refrele(ire);
22545 			if (next_mp != NULL) {
22546 				freemsg(next_mp);
22547 				ire_refrele(ire1);
22548 			}
22549 			if (conn_outgoing_ill != NULL)
22550 				ill_refrele(conn_outgoing_ill);
22551 			return;
22552 		}
22553 
22554 		if (CLASSD(dst)) {
22555 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22556 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22557 			    LENGTH);
22558 		}
22559 
22560 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22561 		    "ip_wput_ire_end: q %p (%S)",
22562 		    q, "last copy out");
22563 		IRE_REFRELE(ire);
22564 
22565 		if (multirt_send) {
22566 			ASSERT(ire1);
22567 			/*
22568 			 * Proceed with the next RTF_MULTIRT ire,
22569 			 * Also set up the send-to queue accordingly.
22570 			 */
22571 			ire = ire1;
22572 			ire1 = NULL;
22573 			stq = ire->ire_stq;
22574 			mp = next_mp;
22575 			next_mp = NULL;
22576 			ipha = (ipha_t *)mp->b_rptr;
22577 			ill_index = Q_TO_INDEX(stq);
22578 			ill = (ill_t *)stq->q_ptr;
22579 		}
22580 	} while (multirt_send);
22581 	if (conn_outgoing_ill != NULL)
22582 		ill_refrele(conn_outgoing_ill);
22583 	return;
22584 
22585 	/*
22586 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22587 	 */
22588 broadcast:
22589 	{
22590 		/*
22591 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22592 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22593 		 * can be overridden stack-wide through the ip_broadcast_ttl
22594 		 * ndd tunable, or on a per-connection basis through the
22595 		 * IP_BROADCAST_TTL socket option.
22596 		 *
22597 		 * In the event that we are replying to incoming ICMP packets,
22598 		 * connp could be NULL.
22599 		 */
22600 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22601 		if (connp != NULL) {
22602 			if (connp->conn_dontroute)
22603 				ipha->ipha_ttl = 1;
22604 			else if (connp->conn_broadcast_ttl != 0)
22605 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22606 		}
22607 
22608 		/*
22609 		 * Note that we are not doing a IRB_REFHOLD here.
22610 		 * Actually we don't care if the list changes i.e
22611 		 * if somebody deletes an IRE from the list while
22612 		 * we drop the lock, the next time we come around
22613 		 * ire_next will be NULL and hence we won't send
22614 		 * out multiple copies which is fine.
22615 		 */
22616 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22617 		ire1 = ire->ire_next;
22618 		if (conn_outgoing_ill != NULL) {
22619 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22620 				ASSERT(ire1 == ire->ire_next);
22621 				if (ire1 != NULL && ire1->ire_addr == dst) {
22622 					ire_refrele(ire);
22623 					ire = ire1;
22624 					IRE_REFHOLD(ire);
22625 					ire1 = ire->ire_next;
22626 					continue;
22627 				}
22628 				rw_exit(&ire->ire_bucket->irb_lock);
22629 				/* Did not find a matching ill */
22630 				ip1dbg(("ip_wput_ire: broadcast with no "
22631 				    "matching IP_BOUND_IF ill %s dst %x\n",
22632 				    conn_outgoing_ill->ill_name, dst));
22633 				freemsg(first_mp);
22634 				if (ire != NULL)
22635 					ire_refrele(ire);
22636 				ill_refrele(conn_outgoing_ill);
22637 				return;
22638 			}
22639 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22640 			/*
22641 			 * If the next IRE has the same address and is not one
22642 			 * of the two copies that we need to send, try to see
22643 			 * whether this copy should be sent at all. This
22644 			 * assumes that we insert loopbacks first and then
22645 			 * non-loopbacks. This is acheived by inserting the
22646 			 * loopback always before non-loopback.
22647 			 * This is used to send a single copy of a broadcast
22648 			 * packet out all physical interfaces that have an
22649 			 * matching IRE_BROADCAST while also looping
22650 			 * back one copy (to ip_wput_local) for each
22651 			 * matching physical interface. However, we avoid
22652 			 * sending packets out different logical that match by
22653 			 * having ipif_up/ipif_down supress duplicate
22654 			 * IRE_BROADCASTS.
22655 			 *
22656 			 * This feature is currently used to get broadcasts
22657 			 * sent to multiple interfaces, when the broadcast
22658 			 * address being used applies to multiple interfaces.
22659 			 * For example, a whole net broadcast will be
22660 			 * replicated on every connected subnet of
22661 			 * the target net.
22662 			 *
22663 			 * Each zone has its own set of IRE_BROADCASTs, so that
22664 			 * we're able to distribute inbound packets to multiple
22665 			 * zones who share a broadcast address. We avoid looping
22666 			 * back outbound packets in different zones but on the
22667 			 * same ill, as the application would see duplicates.
22668 			 *
22669 			 * This logic assumes that ire_add_v4() groups the
22670 			 * IRE_BROADCAST entries so that those with the same
22671 			 * ire_addr are kept together.
22672 			 */
22673 			ire_ill = ire->ire_ipif->ipif_ill;
22674 			if (ire->ire_stq != NULL || ire1->ire_stq == NULL) {
22675 				while (ire1 != NULL && ire1->ire_addr == dst) {
22676 					ire1_ill = ire1->ire_ipif->ipif_ill;
22677 					if (ire1_ill != ire_ill)
22678 						break;
22679 					ire1 = ire1->ire_next;
22680 				}
22681 			}
22682 		}
22683 		ASSERT(multirt_send == B_FALSE);
22684 		if (ire1 != NULL && ire1->ire_addr == dst) {
22685 			if ((ire->ire_flags & RTF_MULTIRT) &&
22686 			    (ire1->ire_flags & RTF_MULTIRT)) {
22687 				/*
22688 				 * We are in the multirouting case.
22689 				 * The message must be sent at least
22690 				 * on both ires. These ires have been
22691 				 * inserted AFTER the standard ones
22692 				 * in ip_rt_add(). There are thus no
22693 				 * other ire entries for the destination
22694 				 * address in the rest of the bucket
22695 				 * that do not have the RTF_MULTIRT
22696 				 * flag. We don't process a copy
22697 				 * of the message here. This will be
22698 				 * done in the final sending loop.
22699 				 */
22700 				multirt_send = B_TRUE;
22701 			} else {
22702 				next_mp = ip_copymsg(first_mp);
22703 				if (next_mp != NULL)
22704 					IRE_REFHOLD(ire1);
22705 			}
22706 		}
22707 		rw_exit(&ire->ire_bucket->irb_lock);
22708 	}
22709 
22710 	if (stq) {
22711 		/*
22712 		 * A non-NULL send-to queue means this packet is going
22713 		 * out of this machine.
22714 		 */
22715 		out_ill = (ill_t *)stq->q_ptr;
22716 
22717 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22718 		ttl_protocol = ((uint16_t *)ipha)[4];
22719 		/*
22720 		 * We accumulate the pseudo header checksum in cksum.
22721 		 * This is pretty hairy code, so watch close.  One
22722 		 * thing to keep in mind is that UDP and TCP have
22723 		 * stored their respective datagram lengths in their
22724 		 * checksum fields.  This lines things up real nice.
22725 		 */
22726 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22727 		    (src >> 16) + (src & 0xFFFF);
22728 		/*
22729 		 * We assume the udp checksum field contains the
22730 		 * length, so to compute the pseudo header checksum,
22731 		 * all we need is the protocol number and src/dst.
22732 		 */
22733 		/* Provide the checksums for UDP and TCP. */
22734 		if ((PROTO == IPPROTO_TCP) &&
22735 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22736 			/* hlen gets the number of uchar_ts in the IP header */
22737 			hlen = (V_HLEN & 0xF) << 2;
22738 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22739 			IP_STAT(ipst, ip_out_sw_cksum);
22740 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22741 			    LENGTH - hlen);
22742 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22743 		} else if (PROTO == IPPROTO_SCTP &&
22744 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22745 			sctp_hdr_t	*sctph;
22746 
22747 			hlen = (V_HLEN & 0xF) << 2;
22748 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22749 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22750 			sctph->sh_chksum = 0;
22751 #ifdef	DEBUG
22752 			if (!skip_sctp_cksum)
22753 #endif
22754 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22755 		} else {
22756 			queue_t	*dev_q = stq->q_next;
22757 
22758 			if (DEV_Q_FLOW_BLOCKED(dev_q)) {
22759 blocked:
22760 				ipha->ipha_ident = ip_hdr_included;
22761 				/*
22762 				 * If we don't have a conn to apply
22763 				 * backpressure, free the message.
22764 				 * In the ire_send path, we don't know
22765 				 * the position to requeue the packet. Rather
22766 				 * than reorder packets, we just drop this
22767 				 * packet.
22768 				 */
22769 				if (ipst->ips_ip_output_queue &&
22770 				    connp != NULL &&
22771 				    caller != IRE_SEND) {
22772 					if (caller == IP_WSRV) {
22773 						connp->conn_did_putbq = 1;
22774 						(void) putbq(connp->conn_wq,
22775 						    first_mp);
22776 						conn_drain_insert(connp);
22777 						/*
22778 						 * This is the service thread,
22779 						 * and the queue is already
22780 						 * noenabled. The check for
22781 						 * canput and the putbq is not
22782 						 * atomic. So we need to check
22783 						 * again.
22784 						 */
22785 						if (canput(stq->q_next))
22786 							connp->conn_did_putbq
22787 							    = 0;
22788 						IP_STAT(ipst, ip_conn_flputbq);
22789 					} else {
22790 						/*
22791 						 * We are not the service proc.
22792 						 * ip_wsrv will be scheduled or
22793 						 * is already running.
22794 						 */
22795 
22796 						(void) putq(connp->conn_wq,
22797 						    first_mp);
22798 					}
22799 				} else {
22800 					out_ill = (ill_t *)stq->q_ptr;
22801 					BUMP_MIB(out_ill->ill_ip_mib,
22802 					    ipIfStatsOutDiscards);
22803 					freemsg(first_mp);
22804 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22805 					    "ip_wput_ire_end: q %p (%S)",
22806 					    q, "discard");
22807 				}
22808 				ire_refrele(ire);
22809 				if (next_mp) {
22810 					ire_refrele(ire1);
22811 					freemsg(next_mp);
22812 				}
22813 				if (conn_outgoing_ill != NULL)
22814 					ill_refrele(conn_outgoing_ill);
22815 				return;
22816 			}
22817 			if ((PROTO == IPPROTO_UDP) &&
22818 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22819 				/*
22820 				 * hlen gets the number of uchar_ts in the
22821 				 * IP header
22822 				 */
22823 				hlen = (V_HLEN & 0xF) << 2;
22824 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22825 				max_frag = ire->ire_max_frag;
22826 				if (*up != 0) {
22827 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22828 					    up, PROTO, hlen, LENGTH, max_frag,
22829 					    ipsec_len, cksum);
22830 					/* Software checksum? */
22831 					if (DB_CKSUMFLAGS(mp) == 0) {
22832 						IP_STAT(ipst, ip_out_sw_cksum);
22833 						IP_STAT_UPDATE(ipst,
22834 						    ip_udp_out_sw_cksum_bytes,
22835 						    LENGTH - hlen);
22836 					}
22837 				}
22838 			}
22839 		}
22840 		/*
22841 		 * Need to do this even when fragmenting. The local
22842 		 * loopback can be done without computing checksums
22843 		 * but forwarding out other interface must be done
22844 		 * after the IP checksum (and ULP checksums) have been
22845 		 * computed.
22846 		 *
22847 		 * NOTE : multicast_forward is set only if this packet
22848 		 * originated from ip_wput. For packets originating from
22849 		 * ip_wput_multicast, it is not set.
22850 		 */
22851 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22852 multi_loopback:
22853 			ip2dbg(("ip_wput: multicast, loop %d\n",
22854 			    conn_multicast_loop));
22855 
22856 			/*  Forget header checksum offload */
22857 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22858 
22859 			/*
22860 			 * Local loopback of multicasts?  Check the
22861 			 * ill.
22862 			 *
22863 			 * Note that the loopback function will not come
22864 			 * in through ip_rput - it will only do the
22865 			 * client fanout thus we need to do an mforward
22866 			 * as well.  The is different from the BSD
22867 			 * logic.
22868 			 */
22869 			if (ill != NULL) {
22870 				if (ilm_lookup_ill(ill, ipha->ipha_dst,
22871 				    ALL_ZONES) != NULL) {
22872 					/*
22873 					 * Pass along the virtual output q.
22874 					 * ip_wput_local() will distribute the
22875 					 * packet to all the matching zones,
22876 					 * except the sending zone when
22877 					 * IP_MULTICAST_LOOP is false.
22878 					 */
22879 					ip_multicast_loopback(q, ill, first_mp,
22880 					    conn_multicast_loop ? 0 :
22881 					    IP_FF_NO_MCAST_LOOP, zoneid);
22882 				}
22883 			}
22884 			if (ipha->ipha_ttl == 0) {
22885 				/*
22886 				 * 0 => only to this host i.e. we are
22887 				 * done. We are also done if this was the
22888 				 * loopback interface since it is sufficient
22889 				 * to loopback one copy of a multicast packet.
22890 				 */
22891 				freemsg(first_mp);
22892 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22893 				    "ip_wput_ire_end: q %p (%S)",
22894 				    q, "loopback");
22895 				ire_refrele(ire);
22896 				if (conn_outgoing_ill != NULL)
22897 					ill_refrele(conn_outgoing_ill);
22898 				return;
22899 			}
22900 			/*
22901 			 * ILLF_MULTICAST is checked in ip_newroute
22902 			 * i.e. we don't need to check it here since
22903 			 * all IRE_CACHEs come from ip_newroute.
22904 			 * For multicast traffic, SO_DONTROUTE is interpreted
22905 			 * to mean only send the packet out the interface
22906 			 * (optionally specified with IP_MULTICAST_IF)
22907 			 * and do not forward it out additional interfaces.
22908 			 * RSVP and the rsvp daemon is an example of a
22909 			 * protocol and user level process that
22910 			 * handles it's own routing. Hence, it uses the
22911 			 * SO_DONTROUTE option to accomplish this.
22912 			 */
22913 
22914 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
22915 			    ill != NULL) {
22916 				/* Unconditionally redo the checksum */
22917 				ipha->ipha_hdr_checksum = 0;
22918 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22919 
22920 				/*
22921 				 * If this needs to go out secure, we need
22922 				 * to wait till we finish the IPsec
22923 				 * processing.
22924 				 */
22925 				if (ipsec_len == 0 &&
22926 				    ip_mforward(ill, ipha, mp)) {
22927 					freemsg(first_mp);
22928 					ip1dbg(("ip_wput: mforward failed\n"));
22929 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22930 					    "ip_wput_ire_end: q %p (%S)",
22931 					    q, "mforward failed");
22932 					ire_refrele(ire);
22933 					if (conn_outgoing_ill != NULL)
22934 						ill_refrele(conn_outgoing_ill);
22935 					return;
22936 				}
22937 			}
22938 		}
22939 		max_frag = ire->ire_max_frag;
22940 		cksum += ttl_protocol;
22941 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
22942 			/* No fragmentation required for this one. */
22943 			/*
22944 			 * Don't use frag_flag if packet is pre-built or source
22945 			 * routed or if multicast (since multicast packets do
22946 			 * not solicit ICMP "packet too big" messages).
22947 			 */
22948 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22949 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22950 			    !ip_source_route_included(ipha)) &&
22951 			    !CLASSD(ipha->ipha_dst))
22952 				ipha->ipha_fragment_offset_and_flags |=
22953 				    htons(ire->ire_frag_flag);
22954 
22955 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22956 				/* Complete the IP header checksum. */
22957 				cksum += ipha->ipha_ident;
22958 				cksum += (v_hlen_tos_len >> 16)+
22959 				    (v_hlen_tos_len & 0xFFFF);
22960 				cksum += ipha->ipha_fragment_offset_and_flags;
22961 				hlen = (V_HLEN & 0xF) -
22962 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22963 				if (hlen) {
22964 checksumoptions:
22965 					/*
22966 					 * Account for the IP Options in the IP
22967 					 * header checksum.
22968 					 */
22969 					up = (uint16_t *)(rptr+
22970 					    IP_SIMPLE_HDR_LENGTH);
22971 					do {
22972 						cksum += up[0];
22973 						cksum += up[1];
22974 						up += 2;
22975 					} while (--hlen);
22976 				}
22977 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22978 				cksum = ~(cksum + (cksum >> 16));
22979 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
22980 			}
22981 			if (ipsec_len != 0) {
22982 				ipsec_out_process(q, first_mp, ire, ill_index);
22983 				if (!next_mp) {
22984 					ire_refrele(ire);
22985 					if (conn_outgoing_ill != NULL)
22986 						ill_refrele(conn_outgoing_ill);
22987 					return;
22988 				}
22989 				goto next;
22990 			}
22991 
22992 			/*
22993 			 * multirt_send has already been handled
22994 			 * for broadcast, but not yet for multicast
22995 			 * or IP options.
22996 			 */
22997 			if (next_mp == NULL) {
22998 				if (ire->ire_flags & RTF_MULTIRT) {
22999 					multirt_send = B_TRUE;
23000 				}
23001 			}
23002 
23003 			/*
23004 			 * In most cases, the emission loop below is
23005 			 * entered only once. Only in the case where
23006 			 * the ire holds the RTF_MULTIRT flag, do we loop
23007 			 * to process all RTF_MULTIRT ires in the bucket,
23008 			 * and send the packet through all crossed
23009 			 * RTF_MULTIRT routes.
23010 			 */
23011 			do {
23012 				if (multirt_send) {
23013 					irb_t *irb;
23014 
23015 					irb = ire->ire_bucket;
23016 					ASSERT(irb != NULL);
23017 					/*
23018 					 * We are in a multiple send case,
23019 					 * need to get the next IRE and make
23020 					 * a duplicate of the packet.
23021 					 */
23022 					IRB_REFHOLD(irb);
23023 					for (ire1 = ire->ire_next;
23024 					    ire1 != NULL;
23025 					    ire1 = ire1->ire_next) {
23026 						if (!(ire1->ire_flags &
23027 						    RTF_MULTIRT))
23028 							continue;
23029 
23030 						if (ire1->ire_addr !=
23031 						    ire->ire_addr)
23032 							continue;
23033 
23034 						if (ire1->ire_marks &
23035 						    (IRE_MARK_CONDEMNED |
23036 						    IRE_MARK_TESTHIDDEN))
23037 							continue;
23038 
23039 						/* Got one */
23040 						IRE_REFHOLD(ire1);
23041 						break;
23042 					}
23043 					IRB_REFRELE(irb);
23044 
23045 					if (ire1 != NULL) {
23046 						next_mp = copyb(mp);
23047 						if ((next_mp == NULL) ||
23048 						    ((mp->b_cont != NULL) &&
23049 						    ((next_mp->b_cont =
23050 						    dupmsg(mp->b_cont))
23051 						    == NULL))) {
23052 							freemsg(next_mp);
23053 							next_mp = NULL;
23054 							ire_refrele(ire1);
23055 							ire1 = NULL;
23056 						}
23057 					}
23058 
23059 					/*
23060 					 * Last multiroute ire; don't loop
23061 					 * anymore. The emission is over
23062 					 * and next_mp is NULL.
23063 					 */
23064 					if (ire1 == NULL) {
23065 						multirt_send = B_FALSE;
23066 					}
23067 				}
23068 
23069 				out_ill = ire_to_ill(ire);
23070 				DTRACE_PROBE4(ip4__physical__out__start,
23071 				    ill_t *, NULL,
23072 				    ill_t *, out_ill,
23073 				    ipha_t *, ipha, mblk_t *, mp);
23074 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23075 				    ipst->ips_ipv4firewall_physical_out,
23076 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23077 				DTRACE_PROBE1(ip4__physical__out__end,
23078 				    mblk_t *, mp);
23079 				if (mp == NULL)
23080 					goto release_ire_and_ill_2;
23081 
23082 				ASSERT(ipsec_len == 0);
23083 				mp->b_prev =
23084 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23085 				DTRACE_PROBE2(ip__xmit__2,
23086 				    mblk_t *, mp, ire_t *, ire);
23087 				pktxmit_state = ip_xmit_v4(mp, ire,
23088 				    NULL, B_TRUE, connp);
23089 				if ((pktxmit_state == SEND_FAILED) ||
23090 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23091 release_ire_and_ill_2:
23092 					if (next_mp) {
23093 						freemsg(next_mp);
23094 						ire_refrele(ire1);
23095 					}
23096 					ire_refrele(ire);
23097 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23098 					    "ip_wput_ire_end: q %p (%S)",
23099 					    q, "discard MDATA");
23100 					if (conn_outgoing_ill != NULL)
23101 						ill_refrele(conn_outgoing_ill);
23102 					return;
23103 				}
23104 
23105 				if (CLASSD(dst)) {
23106 					BUMP_MIB(out_ill->ill_ip_mib,
23107 					    ipIfStatsHCOutMcastPkts);
23108 					UPDATE_MIB(out_ill->ill_ip_mib,
23109 					    ipIfStatsHCOutMcastOctets,
23110 					    LENGTH);
23111 				} else if (ire->ire_type == IRE_BROADCAST) {
23112 					BUMP_MIB(out_ill->ill_ip_mib,
23113 					    ipIfStatsHCOutBcastPkts);
23114 				}
23115 
23116 				if (multirt_send) {
23117 					/*
23118 					 * We are in a multiple send case,
23119 					 * need to re-enter the sending loop
23120 					 * using the next ire.
23121 					 */
23122 					ire_refrele(ire);
23123 					ire = ire1;
23124 					stq = ire->ire_stq;
23125 					mp = next_mp;
23126 					next_mp = NULL;
23127 					ipha = (ipha_t *)mp->b_rptr;
23128 					ill_index = Q_TO_INDEX(stq);
23129 				}
23130 			} while (multirt_send);
23131 
23132 			if (!next_mp) {
23133 				/*
23134 				 * Last copy going out (the ultra-common
23135 				 * case).  Note that we intentionally replicate
23136 				 * the putnext rather than calling it before
23137 				 * the next_mp check in hopes of a little
23138 				 * tail-call action out of the compiler.
23139 				 */
23140 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23141 				    "ip_wput_ire_end: q %p (%S)",
23142 				    q, "last copy out(1)");
23143 				ire_refrele(ire);
23144 				if (conn_outgoing_ill != NULL)
23145 					ill_refrele(conn_outgoing_ill);
23146 				return;
23147 			}
23148 			/* More copies going out below. */
23149 		} else {
23150 			int offset;
23151 fragmentit:
23152 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23153 			/*
23154 			 * If this would generate a icmp_frag_needed message,
23155 			 * we need to handle it before we do the IPsec
23156 			 * processing. Otherwise, we need to strip the IPsec
23157 			 * headers before we send up the message to the ULPs
23158 			 * which becomes messy and difficult.
23159 			 */
23160 			if (ipsec_len != 0) {
23161 				if ((max_frag < (unsigned int)(LENGTH +
23162 				    ipsec_len)) && (offset & IPH_DF)) {
23163 					out_ill = (ill_t *)stq->q_ptr;
23164 					BUMP_MIB(out_ill->ill_ip_mib,
23165 					    ipIfStatsOutFragFails);
23166 					BUMP_MIB(out_ill->ill_ip_mib,
23167 					    ipIfStatsOutFragReqds);
23168 					ipha->ipha_hdr_checksum = 0;
23169 					ipha->ipha_hdr_checksum =
23170 					    (uint16_t)ip_csum_hdr(ipha);
23171 					icmp_frag_needed(ire->ire_stq, first_mp,
23172 					    max_frag, zoneid, ipst);
23173 					if (!next_mp) {
23174 						ire_refrele(ire);
23175 						if (conn_outgoing_ill != NULL) {
23176 							ill_refrele(
23177 							    conn_outgoing_ill);
23178 						}
23179 						return;
23180 					}
23181 				} else {
23182 					/*
23183 					 * This won't cause a icmp_frag_needed
23184 					 * message. to be generated. Send it on
23185 					 * the wire. Note that this could still
23186 					 * cause fragmentation and all we
23187 					 * do is the generation of the message
23188 					 * to the ULP if needed before IPsec.
23189 					 */
23190 					if (!next_mp) {
23191 						ipsec_out_process(q, first_mp,
23192 						    ire, ill_index);
23193 						TRACE_2(TR_FAC_IP,
23194 						    TR_IP_WPUT_IRE_END,
23195 						    "ip_wput_ire_end: q %p "
23196 						    "(%S)", q,
23197 						    "last ipsec_out_process");
23198 						ire_refrele(ire);
23199 						if (conn_outgoing_ill != NULL) {
23200 							ill_refrele(
23201 							    conn_outgoing_ill);
23202 						}
23203 						return;
23204 					}
23205 					ipsec_out_process(q, first_mp,
23206 					    ire, ill_index);
23207 				}
23208 			} else {
23209 				/*
23210 				 * Initiate IPPF processing. For
23211 				 * fragmentable packets we finish
23212 				 * all QOS packet processing before
23213 				 * calling:
23214 				 * ip_wput_ire_fragmentit->ip_wput_frag
23215 				 */
23216 
23217 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23218 					ip_process(IPP_LOCAL_OUT, &mp,
23219 					    ill_index);
23220 					if (mp == NULL) {
23221 						out_ill = (ill_t *)stq->q_ptr;
23222 						BUMP_MIB(out_ill->ill_ip_mib,
23223 						    ipIfStatsOutDiscards);
23224 						if (next_mp != NULL) {
23225 							freemsg(next_mp);
23226 							ire_refrele(ire1);
23227 						}
23228 						ire_refrele(ire);
23229 						TRACE_2(TR_FAC_IP,
23230 						    TR_IP_WPUT_IRE_END,
23231 						    "ip_wput_ire: q %p (%S)",
23232 						    q, "discard MDATA");
23233 						if (conn_outgoing_ill != NULL) {
23234 							ill_refrele(
23235 							    conn_outgoing_ill);
23236 						}
23237 						return;
23238 					}
23239 				}
23240 				if (!next_mp) {
23241 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23242 					    "ip_wput_ire_end: q %p (%S)",
23243 					    q, "last fragmentation");
23244 					ip_wput_ire_fragmentit(mp, ire,
23245 					    zoneid, ipst, connp);
23246 					ire_refrele(ire);
23247 					if (conn_outgoing_ill != NULL)
23248 						ill_refrele(conn_outgoing_ill);
23249 					return;
23250 				}
23251 				ip_wput_ire_fragmentit(mp, ire,
23252 				    zoneid, ipst, connp);
23253 			}
23254 		}
23255 	} else {
23256 nullstq:
23257 		/* A NULL stq means the destination address is local. */
23258 		UPDATE_OB_PKT_COUNT(ire);
23259 		ire->ire_last_used_time = lbolt;
23260 		ASSERT(ire->ire_ipif != NULL);
23261 		if (!next_mp) {
23262 			/*
23263 			 * Is there an "in" and "out" for traffic local
23264 			 * to a host (loopback)?  The code in Solaris doesn't
23265 			 * explicitly draw a line in its code for in vs out,
23266 			 * so we've had to draw a line in the sand: ip_wput_ire
23267 			 * is considered to be the "output" side and
23268 			 * ip_wput_local to be the "input" side.
23269 			 */
23270 			out_ill = ire_to_ill(ire);
23271 
23272 			/*
23273 			 * DTrace this as ip:::send.  A blocked packet will
23274 			 * fire the send probe, but not the receive probe.
23275 			 */
23276 			DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23277 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23278 			    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23279 
23280 			DTRACE_PROBE4(ip4__loopback__out__start,
23281 			    ill_t *, NULL, ill_t *, out_ill,
23282 			    ipha_t *, ipha, mblk_t *, first_mp);
23283 
23284 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23285 			    ipst->ips_ipv4firewall_loopback_out,
23286 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23287 
23288 			DTRACE_PROBE1(ip4__loopback__out_end,
23289 			    mblk_t *, first_mp);
23290 
23291 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23292 			    "ip_wput_ire_end: q %p (%S)",
23293 			    q, "local address");
23294 
23295 			if (first_mp != NULL)
23296 				ip_wput_local(q, out_ill, ipha,
23297 				    first_mp, ire, 0, ire->ire_zoneid);
23298 			ire_refrele(ire);
23299 			if (conn_outgoing_ill != NULL)
23300 				ill_refrele(conn_outgoing_ill);
23301 			return;
23302 		}
23303 
23304 		out_ill = ire_to_ill(ire);
23305 
23306 		/*
23307 		 * DTrace this as ip:::send.  A blocked packet will fire the
23308 		 * send probe, but not the receive probe.
23309 		 */
23310 		DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23311 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23312 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23313 
23314 		DTRACE_PROBE4(ip4__loopback__out__start,
23315 		    ill_t *, NULL, ill_t *, out_ill,
23316 		    ipha_t *, ipha, mblk_t *, first_mp);
23317 
23318 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23319 		    ipst->ips_ipv4firewall_loopback_out,
23320 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23321 
23322 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23323 
23324 		if (first_mp != NULL)
23325 			ip_wput_local(q, out_ill, ipha,
23326 			    first_mp, ire, 0, ire->ire_zoneid);
23327 	}
23328 next:
23329 	/*
23330 	 * More copies going out to additional interfaces.
23331 	 * ire1 has already been held. We don't need the
23332 	 * "ire" anymore.
23333 	 */
23334 	ire_refrele(ire);
23335 	ire = ire1;
23336 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23337 	mp = next_mp;
23338 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23339 	ill = ire_to_ill(ire);
23340 	first_mp = mp;
23341 	if (ipsec_len != 0) {
23342 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23343 		mp = mp->b_cont;
23344 	}
23345 	dst = ire->ire_addr;
23346 	ipha = (ipha_t *)mp->b_rptr;
23347 	/*
23348 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23349 	 * Restore ipha_ident "no checksum" flag.
23350 	 */
23351 	src = orig_src;
23352 	ipha->ipha_ident = ip_hdr_included;
23353 	goto another;
23354 
23355 #undef	rptr
23356 #undef	Q_TO_INDEX
23357 }
23358 
23359 /*
23360  * Routine to allocate a message that is used to notify the ULP about MDT.
23361  * The caller may provide a pointer to the link-layer MDT capabilities,
23362  * or NULL if MDT is to be disabled on the stream.
23363  */
23364 mblk_t *
23365 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23366 {
23367 	mblk_t *mp;
23368 	ip_mdt_info_t *mdti;
23369 	ill_mdt_capab_t *idst;
23370 
23371 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23372 		DB_TYPE(mp) = M_CTL;
23373 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23374 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23375 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23376 		idst = &(mdti->mdt_capab);
23377 
23378 		/*
23379 		 * If the caller provides us with the capability, copy
23380 		 * it over into our notification message; otherwise
23381 		 * we zero out the capability portion.
23382 		 */
23383 		if (isrc != NULL)
23384 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23385 		else
23386 			bzero((caddr_t)idst, sizeof (*idst));
23387 	}
23388 	return (mp);
23389 }
23390 
23391 /*
23392  * Routine which determines whether MDT can be enabled on the destination
23393  * IRE and IPC combination, and if so, allocates and returns the MDT
23394  * notification mblk that may be used by ULP.  We also check if we need to
23395  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23396  * MDT usage in the past have been lifted.  This gets called during IP
23397  * and ULP binding.
23398  */
23399 mblk_t *
23400 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23401     ill_mdt_capab_t *mdt_cap)
23402 {
23403 	mblk_t *mp;
23404 	boolean_t rc = B_FALSE;
23405 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23406 
23407 	ASSERT(dst_ire != NULL);
23408 	ASSERT(connp != NULL);
23409 	ASSERT(mdt_cap != NULL);
23410 
23411 	/*
23412 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23413 	 * Multidata, which is handled in tcp_multisend().  This
23414 	 * is the reason why we do all these checks here, to ensure
23415 	 * that we don't enable Multidata for the cases which we
23416 	 * can't handle at the moment.
23417 	 */
23418 	do {
23419 		/* Only do TCP at the moment */
23420 		if (connp->conn_ulp != IPPROTO_TCP)
23421 			break;
23422 
23423 		/*
23424 		 * IPsec outbound policy present?  Note that we get here
23425 		 * after calling ipsec_conn_cache_policy() where the global
23426 		 * policy checking is performed.  conn_latch will be
23427 		 * non-NULL as long as there's a policy defined,
23428 		 * i.e. conn_out_enforce_policy may be NULL in such case
23429 		 * when the connection is non-secure, and hence we check
23430 		 * further if the latch refers to an outbound policy.
23431 		 */
23432 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23433 			break;
23434 
23435 		/* CGTP (multiroute) is enabled? */
23436 		if (dst_ire->ire_flags & RTF_MULTIRT)
23437 			break;
23438 
23439 		/* Outbound IPQoS enabled? */
23440 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23441 			/*
23442 			 * In this case, we disable MDT for this and all
23443 			 * future connections going over the interface.
23444 			 */
23445 			mdt_cap->ill_mdt_on = 0;
23446 			break;
23447 		}
23448 
23449 		/* socket option(s) present? */
23450 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23451 			break;
23452 
23453 		rc = B_TRUE;
23454 	/* CONSTCOND */
23455 	} while (0);
23456 
23457 	/* Remember the result */
23458 	connp->conn_mdt_ok = rc;
23459 
23460 	if (!rc)
23461 		return (NULL);
23462 	else if (!mdt_cap->ill_mdt_on) {
23463 		/*
23464 		 * If MDT has been previously turned off in the past, and we
23465 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23466 		 * then enable it for this interface.
23467 		 */
23468 		mdt_cap->ill_mdt_on = 1;
23469 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23470 		    "interface %s\n", ill_name));
23471 	}
23472 
23473 	/* Allocate the MDT info mblk */
23474 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23475 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23476 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23477 		return (NULL);
23478 	}
23479 	return (mp);
23480 }
23481 
23482 /*
23483  * Routine to allocate a message that is used to notify the ULP about LSO.
23484  * The caller may provide a pointer to the link-layer LSO capabilities,
23485  * or NULL if LSO is to be disabled on the stream.
23486  */
23487 mblk_t *
23488 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23489 {
23490 	mblk_t *mp;
23491 	ip_lso_info_t *lsoi;
23492 	ill_lso_capab_t *idst;
23493 
23494 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23495 		DB_TYPE(mp) = M_CTL;
23496 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23497 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23498 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23499 		idst = &(lsoi->lso_capab);
23500 
23501 		/*
23502 		 * If the caller provides us with the capability, copy
23503 		 * it over into our notification message; otherwise
23504 		 * we zero out the capability portion.
23505 		 */
23506 		if (isrc != NULL)
23507 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23508 		else
23509 			bzero((caddr_t)idst, sizeof (*idst));
23510 	}
23511 	return (mp);
23512 }
23513 
23514 /*
23515  * Routine which determines whether LSO can be enabled on the destination
23516  * IRE and IPC combination, and if so, allocates and returns the LSO
23517  * notification mblk that may be used by ULP.  We also check if we need to
23518  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23519  * LSO usage in the past have been lifted.  This gets called during IP
23520  * and ULP binding.
23521  */
23522 mblk_t *
23523 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23524     ill_lso_capab_t *lso_cap)
23525 {
23526 	mblk_t *mp;
23527 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23528 
23529 	ASSERT(dst_ire != NULL);
23530 	ASSERT(connp != NULL);
23531 	ASSERT(lso_cap != NULL);
23532 
23533 	connp->conn_lso_ok = B_TRUE;
23534 
23535 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23536 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23537 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23538 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23539 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23540 		connp->conn_lso_ok = B_FALSE;
23541 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23542 			/*
23543 			 * Disable LSO for this and all future connections going
23544 			 * over the interface.
23545 			 */
23546 			lso_cap->ill_lso_on = 0;
23547 		}
23548 	}
23549 
23550 	if (!connp->conn_lso_ok)
23551 		return (NULL);
23552 	else if (!lso_cap->ill_lso_on) {
23553 		/*
23554 		 * If LSO has been previously turned off in the past, and we
23555 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23556 		 * then enable it for this interface.
23557 		 */
23558 		lso_cap->ill_lso_on = 1;
23559 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23560 		    ill_name));
23561 	}
23562 
23563 	/* Allocate the LSO info mblk */
23564 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23565 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23566 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23567 
23568 	return (mp);
23569 }
23570 
23571 /*
23572  * Create destination address attribute, and fill it with the physical
23573  * destination address and SAP taken from the template DL_UNITDATA_REQ
23574  * message block.
23575  */
23576 boolean_t
23577 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23578 {
23579 	dl_unitdata_req_t *dlurp;
23580 	pattr_t *pa;
23581 	pattrinfo_t pa_info;
23582 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23583 	uint_t das_len, das_off;
23584 
23585 	ASSERT(dlmp != NULL);
23586 
23587 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23588 	das_len = dlurp->dl_dest_addr_length;
23589 	das_off = dlurp->dl_dest_addr_offset;
23590 
23591 	pa_info.type = PATTR_DSTADDRSAP;
23592 	pa_info.len = sizeof (**das) + das_len - 1;
23593 
23594 	/* create and associate the attribute */
23595 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23596 	if (pa != NULL) {
23597 		ASSERT(*das != NULL);
23598 		(*das)->addr_is_group = 0;
23599 		(*das)->addr_len = (uint8_t)das_len;
23600 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23601 	}
23602 
23603 	return (pa != NULL);
23604 }
23605 
23606 /*
23607  * Create hardware checksum attribute and fill it with the values passed.
23608  */
23609 boolean_t
23610 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23611     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23612 {
23613 	pattr_t *pa;
23614 	pattrinfo_t pa_info;
23615 
23616 	ASSERT(mmd != NULL);
23617 
23618 	pa_info.type = PATTR_HCKSUM;
23619 	pa_info.len = sizeof (pattr_hcksum_t);
23620 
23621 	/* create and associate the attribute */
23622 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23623 	if (pa != NULL) {
23624 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23625 
23626 		hck->hcksum_start_offset = start_offset;
23627 		hck->hcksum_stuff_offset = stuff_offset;
23628 		hck->hcksum_end_offset = end_offset;
23629 		hck->hcksum_flags = flags;
23630 	}
23631 	return (pa != NULL);
23632 }
23633 
23634 /*
23635  * Create zerocopy attribute and fill it with the specified flags
23636  */
23637 boolean_t
23638 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23639 {
23640 	pattr_t *pa;
23641 	pattrinfo_t pa_info;
23642 
23643 	ASSERT(mmd != NULL);
23644 	pa_info.type = PATTR_ZCOPY;
23645 	pa_info.len = sizeof (pattr_zcopy_t);
23646 
23647 	/* create and associate the attribute */
23648 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23649 	if (pa != NULL) {
23650 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23651 
23652 		zcopy->zcopy_flags = flags;
23653 	}
23654 	return (pa != NULL);
23655 }
23656 
23657 /*
23658  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23659  * block chain. We could rewrite to handle arbitrary message block chains but
23660  * that would make the code complicated and slow. Right now there three
23661  * restrictions:
23662  *
23663  *   1. The first message block must contain the complete IP header and
23664  *	at least 1 byte of payload data.
23665  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23666  *	so that we can use a single Multidata message.
23667  *   3. No frag must be distributed over two or more message blocks so
23668  *	that we don't need more than two packet descriptors per frag.
23669  *
23670  * The above restrictions allow us to support userland applications (which
23671  * will send down a single message block) and NFS over UDP (which will
23672  * send down a chain of at most three message blocks).
23673  *
23674  * We also don't use MDT for payloads with less than or equal to
23675  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23676  */
23677 boolean_t
23678 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23679 {
23680 	int	blocks;
23681 	ssize_t	total, missing, size;
23682 
23683 	ASSERT(mp != NULL);
23684 	ASSERT(hdr_len > 0);
23685 
23686 	size = MBLKL(mp) - hdr_len;
23687 	if (size <= 0)
23688 		return (B_FALSE);
23689 
23690 	/* The first mblk contains the header and some payload. */
23691 	blocks = 1;
23692 	total = size;
23693 	size %= len;
23694 	missing = (size == 0) ? 0 : (len - size);
23695 	mp = mp->b_cont;
23696 
23697 	while (mp != NULL) {
23698 		/*
23699 		 * Give up if we encounter a zero length message block.
23700 		 * In practice, this should rarely happen and therefore
23701 		 * not worth the trouble of freeing and re-linking the
23702 		 * mblk from the chain to handle such case.
23703 		 */
23704 		if ((size = MBLKL(mp)) == 0)
23705 			return (B_FALSE);
23706 
23707 		/* Too many payload buffers for a single Multidata message? */
23708 		if (++blocks > MULTIDATA_MAX_PBUFS)
23709 			return (B_FALSE);
23710 
23711 		total += size;
23712 		/* Is a frag distributed over two or more message blocks? */
23713 		if (missing > size)
23714 			return (B_FALSE);
23715 		size -= missing;
23716 
23717 		size %= len;
23718 		missing = (size == 0) ? 0 : (len - size);
23719 
23720 		mp = mp->b_cont;
23721 	}
23722 
23723 	return (total > ip_wput_frag_mdt_min);
23724 }
23725 
23726 /*
23727  * Outbound IPv4 fragmentation routine using MDT.
23728  */
23729 static void
23730 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23731     uint32_t frag_flag, int offset)
23732 {
23733 	ipha_t		*ipha_orig;
23734 	int		i1, ip_data_end;
23735 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23736 	mblk_t		*hdr_mp, *md_mp = NULL;
23737 	unsigned char	*hdr_ptr, *pld_ptr;
23738 	multidata_t	*mmd;
23739 	ip_pdescinfo_t	pdi;
23740 	ill_t		*ill;
23741 	ip_stack_t	*ipst = ire->ire_ipst;
23742 
23743 	ASSERT(DB_TYPE(mp) == M_DATA);
23744 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23745 
23746 	ill = ire_to_ill(ire);
23747 	ASSERT(ill != NULL);
23748 
23749 	ipha_orig = (ipha_t *)mp->b_rptr;
23750 	mp->b_rptr += sizeof (ipha_t);
23751 
23752 	/* Calculate how many packets we will send out */
23753 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23754 	pkts = (i1 + len - 1) / len;
23755 	ASSERT(pkts > 1);
23756 
23757 	/* Allocate a message block which will hold all the IP Headers. */
23758 	wroff = ipst->ips_ip_wroff_extra;
23759 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23760 
23761 	i1 = pkts * hdr_chunk_len;
23762 	/*
23763 	 * Create the header buffer, Multidata and destination address
23764 	 * and SAP attribute that should be associated with it.
23765 	 */
23766 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23767 	    ((hdr_mp->b_wptr += i1),
23768 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23769 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23770 		freemsg(mp);
23771 		if (md_mp == NULL) {
23772 			freemsg(hdr_mp);
23773 		} else {
23774 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23775 			freemsg(md_mp);
23776 		}
23777 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23778 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23779 		return;
23780 	}
23781 	IP_STAT(ipst, ip_frag_mdt_allocd);
23782 
23783 	/*
23784 	 * Add a payload buffer to the Multidata; this operation must not
23785 	 * fail, or otherwise our logic in this routine is broken.  There
23786 	 * is no memory allocation done by the routine, so any returned
23787 	 * failure simply tells us that we've done something wrong.
23788 	 *
23789 	 * A failure tells us that either we're adding the same payload
23790 	 * buffer more than once, or we're trying to add more buffers than
23791 	 * allowed.  None of the above cases should happen, and we panic
23792 	 * because either there's horrible heap corruption, and/or
23793 	 * programming mistake.
23794 	 */
23795 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23796 		goto pbuf_panic;
23797 
23798 	hdr_ptr = hdr_mp->b_rptr;
23799 	pld_ptr = mp->b_rptr;
23800 
23801 	/* Establish the ending byte offset, based on the starting offset. */
23802 	offset <<= 3;
23803 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23804 	    IP_SIMPLE_HDR_LENGTH;
23805 
23806 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23807 
23808 	while (pld_ptr < mp->b_wptr) {
23809 		ipha_t		*ipha;
23810 		uint16_t	offset_and_flags;
23811 		uint16_t	ip_len;
23812 		int		error;
23813 
23814 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23815 		ipha = (ipha_t *)(hdr_ptr + wroff);
23816 		ASSERT(OK_32PTR(ipha));
23817 		*ipha = *ipha_orig;
23818 
23819 		if (ip_data_end - offset > len) {
23820 			offset_and_flags = IPH_MF;
23821 		} else {
23822 			/*
23823 			 * Last frag. Set len to the length of this last piece.
23824 			 */
23825 			len = ip_data_end - offset;
23826 			/* A frag of a frag might have IPH_MF non-zero */
23827 			offset_and_flags =
23828 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23829 			    IPH_MF;
23830 		}
23831 		offset_and_flags |= (uint16_t)(offset >> 3);
23832 		offset_and_flags |= (uint16_t)frag_flag;
23833 		/* Store the offset and flags in the IP header. */
23834 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23835 
23836 		/* Store the length in the IP header. */
23837 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23838 		ipha->ipha_length = htons(ip_len);
23839 
23840 		/*
23841 		 * Set the IP header checksum.  Note that mp is just
23842 		 * the header, so this is easy to pass to ip_csum.
23843 		 */
23844 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23845 
23846 		DTRACE_IP7(send, mblk_t *, md_mp, conn_t *, NULL, void_ip_t *,
23847 		    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *,
23848 		    NULL, int, 0);
23849 
23850 		/*
23851 		 * Record offset and size of header and data of the next packet
23852 		 * in the multidata message.
23853 		 */
23854 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23855 		PDESC_PLD_INIT(&pdi);
23856 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23857 		ASSERT(i1 > 0);
23858 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23859 		if (i1 == len) {
23860 			pld_ptr += len;
23861 		} else {
23862 			i1 = len - i1;
23863 			mp = mp->b_cont;
23864 			ASSERT(mp != NULL);
23865 			ASSERT(MBLKL(mp) >= i1);
23866 			/*
23867 			 * Attach the next payload message block to the
23868 			 * multidata message.
23869 			 */
23870 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23871 				goto pbuf_panic;
23872 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23873 			pld_ptr = mp->b_rptr + i1;
23874 		}
23875 
23876 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23877 		    KM_NOSLEEP)) == NULL) {
23878 			/*
23879 			 * Any failure other than ENOMEM indicates that we
23880 			 * have passed in invalid pdesc info or parameters
23881 			 * to mmd_addpdesc, which must not happen.
23882 			 *
23883 			 * EINVAL is a result of failure on boundary checks
23884 			 * against the pdesc info contents.  It should not
23885 			 * happen, and we panic because either there's
23886 			 * horrible heap corruption, and/or programming
23887 			 * mistake.
23888 			 */
23889 			if (error != ENOMEM) {
23890 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23891 				    "pdesc logic error detected for "
23892 				    "mmd %p pinfo %p (%d)\n",
23893 				    (void *)mmd, (void *)&pdi, error);
23894 				/* NOTREACHED */
23895 			}
23896 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
23897 			/* Free unattached payload message blocks as well */
23898 			md_mp->b_cont = mp->b_cont;
23899 			goto free_mmd;
23900 		}
23901 
23902 		/* Advance fragment offset. */
23903 		offset += len;
23904 
23905 		/* Advance to location for next header in the buffer. */
23906 		hdr_ptr += hdr_chunk_len;
23907 
23908 		/* Did we reach the next payload message block? */
23909 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23910 			mp = mp->b_cont;
23911 			/*
23912 			 * Attach the next message block with payload
23913 			 * data to the multidata message.
23914 			 */
23915 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23916 				goto pbuf_panic;
23917 			pld_ptr = mp->b_rptr;
23918 		}
23919 	}
23920 
23921 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23922 	ASSERT(mp->b_wptr == pld_ptr);
23923 
23924 	/* Update IP statistics */
23925 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
23926 
23927 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
23928 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
23929 
23930 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
23931 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
23932 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
23933 
23934 	if (pkt_type == OB_PKT) {
23935 		ire->ire_ob_pkt_count += pkts;
23936 		if (ire->ire_ipif != NULL)
23937 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23938 	} else {
23939 		/* The type is IB_PKT in the forwarding path. */
23940 		ire->ire_ib_pkt_count += pkts;
23941 		ASSERT(!IRE_IS_LOCAL(ire));
23942 		if (ire->ire_type & IRE_BROADCAST) {
23943 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23944 		} else {
23945 			UPDATE_MIB(ill->ill_ip_mib,
23946 			    ipIfStatsHCOutForwDatagrams, pkts);
23947 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
23948 		}
23949 	}
23950 	ire->ire_last_used_time = lbolt;
23951 	/* Send it down */
23952 	putnext(ire->ire_stq, md_mp);
23953 	return;
23954 
23955 pbuf_panic:
23956 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
23957 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
23958 	    pbuf_idx);
23959 	/* NOTREACHED */
23960 }
23961 
23962 /*
23963  * Outbound IP fragmentation routine.
23964  *
23965  * NOTE : This routine does not ire_refrele the ire that is passed in
23966  * as the argument.
23967  */
23968 static void
23969 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
23970     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst, conn_t *connp)
23971 {
23972 	int		i1;
23973 	mblk_t		*ll_hdr_mp;
23974 	int 		ll_hdr_len;
23975 	int		hdr_len;
23976 	mblk_t		*hdr_mp;
23977 	ipha_t		*ipha;
23978 	int		ip_data_end;
23979 	int		len;
23980 	mblk_t		*mp = mp_orig, *mp1;
23981 	int		offset;
23982 	queue_t		*q;
23983 	uint32_t	v_hlen_tos_len;
23984 	mblk_t		*first_mp;
23985 	boolean_t	mctl_present;
23986 	ill_t		*ill;
23987 	ill_t		*out_ill;
23988 	mblk_t		*xmit_mp;
23989 	mblk_t		*carve_mp;
23990 	ire_t		*ire1 = NULL;
23991 	ire_t		*save_ire = NULL;
23992 	mblk_t  	*next_mp = NULL;
23993 	boolean_t	last_frag = B_FALSE;
23994 	boolean_t	multirt_send = B_FALSE;
23995 	ire_t		*first_ire = NULL;
23996 	irb_t		*irb = NULL;
23997 	mib2_ipIfStatsEntry_t *mibptr = NULL;
23998 
23999 	ill = ire_to_ill(ire);
24000 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24001 
24002 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24003 
24004 	if (max_frag == 0) {
24005 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24006 		    " -  dropping packet\n"));
24007 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24008 		freemsg(mp);
24009 		return;
24010 	}
24011 
24012 	/*
24013 	 * IPsec does not allow hw accelerated packets to be fragmented
24014 	 * This check is made in ip_wput_ipsec_out prior to coming here
24015 	 * via ip_wput_ire_fragmentit.
24016 	 *
24017 	 * If at this point we have an ire whose ARP request has not
24018 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24019 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24020 	 * This packet and all fragmentable packets for this ire will
24021 	 * continue to get dropped while ire_nce->nce_state remains in
24022 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24023 	 * ND_REACHABLE, all subsquent large packets for this ire will
24024 	 * get fragemented and sent out by this function.
24025 	 */
24026 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24027 		/* If nce_state is ND_INITIAL, trigger ARP query */
24028 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
24029 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24030 		    " -  dropping packet\n"));
24031 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24032 		freemsg(mp);
24033 		return;
24034 	}
24035 
24036 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24037 	    "ip_wput_frag_start:");
24038 
24039 	if (mp->b_datap->db_type == M_CTL) {
24040 		first_mp = mp;
24041 		mp_orig = mp = mp->b_cont;
24042 		mctl_present = B_TRUE;
24043 	} else {
24044 		first_mp = mp;
24045 		mctl_present = B_FALSE;
24046 	}
24047 
24048 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24049 	ipha = (ipha_t *)mp->b_rptr;
24050 
24051 	/*
24052 	 * If the Don't Fragment flag is on, generate an ICMP destination
24053 	 * unreachable, fragmentation needed.
24054 	 */
24055 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24056 	if (offset & IPH_DF) {
24057 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24058 		if (is_system_labeled()) {
24059 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24060 			    ire->ire_max_frag - max_frag, AF_INET);
24061 		}
24062 		/*
24063 		 * Need to compute hdr checksum if called from ip_wput_ire.
24064 		 * Note that ip_rput_forward verifies the checksum before
24065 		 * calling this routine so in that case this is a noop.
24066 		 */
24067 		ipha->ipha_hdr_checksum = 0;
24068 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24069 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24070 		    ipst);
24071 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24072 		    "ip_wput_frag_end:(%S)",
24073 		    "don't fragment");
24074 		return;
24075 	}
24076 	/*
24077 	 * Labeled systems adjust max_frag if they add a label
24078 	 * to send the correct path mtu.  We need the real mtu since we
24079 	 * are fragmenting the packet after label adjustment.
24080 	 */
24081 	if (is_system_labeled())
24082 		max_frag = ire->ire_max_frag;
24083 	if (mctl_present)
24084 		freeb(first_mp);
24085 	/*
24086 	 * Establish the starting offset.  May not be zero if we are fragging
24087 	 * a fragment that is being forwarded.
24088 	 */
24089 	offset = offset & IPH_OFFSET;
24090 
24091 	/* TODO why is this test needed? */
24092 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24093 	if (((max_frag - LENGTH) & ~7) < 8) {
24094 		/* TODO: notify ulp somehow */
24095 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24096 		freemsg(mp);
24097 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24098 		    "ip_wput_frag_end:(%S)",
24099 		    "len < 8");
24100 		return;
24101 	}
24102 
24103 	hdr_len = (V_HLEN & 0xF) << 2;
24104 
24105 	ipha->ipha_hdr_checksum = 0;
24106 
24107 	/*
24108 	 * Establish the number of bytes maximum per frag, after putting
24109 	 * in the header.
24110 	 */
24111 	len = (max_frag - hdr_len) & ~7;
24112 
24113 	/* Check if we can use MDT to send out the frags. */
24114 	ASSERT(!IRE_IS_LOCAL(ire));
24115 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24116 	    ipst->ips_ip_multidata_outbound &&
24117 	    !(ire->ire_flags & RTF_MULTIRT) &&
24118 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24119 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24120 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24121 		ASSERT(ill->ill_mdt_capab != NULL);
24122 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24123 			/*
24124 			 * If MDT has been previously turned off in the past,
24125 			 * and we currently can do MDT (due to IPQoS policy
24126 			 * removal, etc.) then enable it for this interface.
24127 			 */
24128 			ill->ill_mdt_capab->ill_mdt_on = 1;
24129 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24130 			    ill->ill_name));
24131 		}
24132 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24133 		    offset);
24134 		return;
24135 	}
24136 
24137 	/* Get a copy of the header for the trailing frags */
24138 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
24139 	    mp);
24140 	if (!hdr_mp) {
24141 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24142 		freemsg(mp);
24143 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24144 		    "ip_wput_frag_end:(%S)",
24145 		    "couldn't copy hdr");
24146 		return;
24147 	}
24148 
24149 	/* Store the starting offset, with the MoreFrags flag. */
24150 	i1 = offset | IPH_MF | frag_flag;
24151 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24152 
24153 	/* Establish the ending byte offset, based on the starting offset. */
24154 	offset <<= 3;
24155 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24156 
24157 	/* Store the length of the first fragment in the IP header. */
24158 	i1 = len + hdr_len;
24159 	ASSERT(i1 <= IP_MAXPACKET);
24160 	ipha->ipha_length = htons((uint16_t)i1);
24161 
24162 	/*
24163 	 * Compute the IP header checksum for the first frag.  We have to
24164 	 * watch out that we stop at the end of the header.
24165 	 */
24166 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24167 
24168 	/*
24169 	 * Now carve off the first frag.  Note that this will include the
24170 	 * original IP header.
24171 	 */
24172 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24173 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24174 		freeb(hdr_mp);
24175 		freemsg(mp_orig);
24176 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24177 		    "ip_wput_frag_end:(%S)",
24178 		    "couldn't carve first");
24179 		return;
24180 	}
24181 
24182 	/*
24183 	 * Multirouting case. Each fragment is replicated
24184 	 * via all non-condemned RTF_MULTIRT routes
24185 	 * currently resolved.
24186 	 * We ensure that first_ire is the first RTF_MULTIRT
24187 	 * ire in the bucket.
24188 	 */
24189 	if (ire->ire_flags & RTF_MULTIRT) {
24190 		irb = ire->ire_bucket;
24191 		ASSERT(irb != NULL);
24192 
24193 		multirt_send = B_TRUE;
24194 
24195 		/* Make sure we do not omit any multiroute ire. */
24196 		IRB_REFHOLD(irb);
24197 		for (first_ire = irb->irb_ire;
24198 		    first_ire != NULL;
24199 		    first_ire = first_ire->ire_next) {
24200 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24201 			    (first_ire->ire_addr == ire->ire_addr) &&
24202 			    !(first_ire->ire_marks &
24203 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
24204 				break;
24205 		}
24206 
24207 		if (first_ire != NULL) {
24208 			if (first_ire != ire) {
24209 				IRE_REFHOLD(first_ire);
24210 				/*
24211 				 * Do not release the ire passed in
24212 				 * as the argument.
24213 				 */
24214 				ire = first_ire;
24215 			} else {
24216 				first_ire = NULL;
24217 			}
24218 		}
24219 		IRB_REFRELE(irb);
24220 
24221 		/*
24222 		 * Save the first ire; we will need to restore it
24223 		 * for the trailing frags.
24224 		 * We REFHOLD save_ire, as each iterated ire will be
24225 		 * REFRELEd.
24226 		 */
24227 		save_ire = ire;
24228 		IRE_REFHOLD(save_ire);
24229 	}
24230 
24231 	/*
24232 	 * First fragment emission loop.
24233 	 * In most cases, the emission loop below is entered only
24234 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24235 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24236 	 * bucket, and send the fragment through all crossed
24237 	 * RTF_MULTIRT routes.
24238 	 */
24239 	do {
24240 		if (ire->ire_flags & RTF_MULTIRT) {
24241 			/*
24242 			 * We are in a multiple send case, need to get
24243 			 * the next ire and make a copy of the packet.
24244 			 * ire1 holds here the next ire to process in the
24245 			 * bucket. If multirouting is expected,
24246 			 * any non-RTF_MULTIRT ire that has the
24247 			 * right destination address is ignored.
24248 			 *
24249 			 * We have to take into account the MTU of
24250 			 * each walked ire. max_frag is set by the
24251 			 * the caller and generally refers to
24252 			 * the primary ire entry. Here we ensure that
24253 			 * no route with a lower MTU will be used, as
24254 			 * fragments are carved once for all ires,
24255 			 * then replicated.
24256 			 */
24257 			ASSERT(irb != NULL);
24258 			IRB_REFHOLD(irb);
24259 			for (ire1 = ire->ire_next;
24260 			    ire1 != NULL;
24261 			    ire1 = ire1->ire_next) {
24262 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24263 					continue;
24264 				if (ire1->ire_addr != ire->ire_addr)
24265 					continue;
24266 				if (ire1->ire_marks &
24267 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
24268 					continue;
24269 				/*
24270 				 * Ensure we do not exceed the MTU
24271 				 * of the next route.
24272 				 */
24273 				if (ire1->ire_max_frag < max_frag) {
24274 					ip_multirt_bad_mtu(ire1, max_frag);
24275 					continue;
24276 				}
24277 
24278 				/* Got one. */
24279 				IRE_REFHOLD(ire1);
24280 				break;
24281 			}
24282 			IRB_REFRELE(irb);
24283 
24284 			if (ire1 != NULL) {
24285 				next_mp = copyb(mp);
24286 				if ((next_mp == NULL) ||
24287 				    ((mp->b_cont != NULL) &&
24288 				    ((next_mp->b_cont =
24289 				    dupmsg(mp->b_cont)) == NULL))) {
24290 					freemsg(next_mp);
24291 					next_mp = NULL;
24292 					ire_refrele(ire1);
24293 					ire1 = NULL;
24294 				}
24295 			}
24296 
24297 			/* Last multiroute ire; don't loop anymore. */
24298 			if (ire1 == NULL) {
24299 				multirt_send = B_FALSE;
24300 			}
24301 		}
24302 
24303 		ll_hdr_len = 0;
24304 		LOCK_IRE_FP_MP(ire);
24305 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24306 		if (ll_hdr_mp != NULL) {
24307 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24308 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24309 		} else {
24310 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24311 		}
24312 
24313 		/* If there is a transmit header, get a copy for this frag. */
24314 		/*
24315 		 * TODO: should check db_ref before calling ip_carve_mp since
24316 		 * it might give us a dup.
24317 		 */
24318 		if (!ll_hdr_mp) {
24319 			/* No xmit header. */
24320 			xmit_mp = mp;
24321 
24322 		/* We have a link-layer header that can fit in our mblk. */
24323 		} else if (mp->b_datap->db_ref == 1 &&
24324 		    ll_hdr_len != 0 &&
24325 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24326 			/* M_DATA fastpath */
24327 			mp->b_rptr -= ll_hdr_len;
24328 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24329 			xmit_mp = mp;
24330 
24331 		/* Corner case if copyb has failed */
24332 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24333 			UNLOCK_IRE_FP_MP(ire);
24334 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24335 			freeb(hdr_mp);
24336 			freemsg(mp);
24337 			freemsg(mp_orig);
24338 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24339 			    "ip_wput_frag_end:(%S)",
24340 			    "discard");
24341 
24342 			if (multirt_send) {
24343 				ASSERT(ire1);
24344 				ASSERT(next_mp);
24345 
24346 				freemsg(next_mp);
24347 				ire_refrele(ire1);
24348 			}
24349 			if (save_ire != NULL)
24350 				IRE_REFRELE(save_ire);
24351 
24352 			if (first_ire != NULL)
24353 				ire_refrele(first_ire);
24354 			return;
24355 
24356 		/*
24357 		 * Case of res_mp OR the fastpath mp can't fit
24358 		 * in the mblk
24359 		 */
24360 		} else {
24361 			xmit_mp->b_cont = mp;
24362 
24363 			/*
24364 			 * Get priority marking, if any.
24365 			 * We propagate the CoS marking from the
24366 			 * original packet that went to QoS processing
24367 			 * in ip_wput_ire to the newly carved mp.
24368 			 */
24369 			if (DB_TYPE(xmit_mp) == M_DATA)
24370 				xmit_mp->b_band = mp->b_band;
24371 		}
24372 		UNLOCK_IRE_FP_MP(ire);
24373 
24374 		q = ire->ire_stq;
24375 		out_ill = (ill_t *)q->q_ptr;
24376 
24377 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24378 
24379 		DTRACE_PROBE4(ip4__physical__out__start,
24380 		    ill_t *, NULL, ill_t *, out_ill,
24381 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24382 
24383 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24384 		    ipst->ips_ipv4firewall_physical_out,
24385 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24386 
24387 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24388 
24389 		if (xmit_mp != NULL) {
24390 			DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *, NULL,
24391 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
24392 			    ipha_t *, ipha, ip6_t *, NULL, int, 0);
24393 
24394 			ILL_SEND_TX(out_ill, ire, connp, xmit_mp, 0);
24395 
24396 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24397 			UPDATE_MIB(out_ill->ill_ip_mib,
24398 			    ipIfStatsHCOutOctets, i1);
24399 
24400 			if (pkt_type != OB_PKT) {
24401 				/*
24402 				 * Update the packet count and MIB stats
24403 				 * of trailing RTF_MULTIRT ires.
24404 				 */
24405 				UPDATE_OB_PKT_COUNT(ire);
24406 				BUMP_MIB(out_ill->ill_ip_mib,
24407 				    ipIfStatsOutFragReqds);
24408 			}
24409 		}
24410 
24411 		if (multirt_send) {
24412 			/*
24413 			 * We are in a multiple send case; look for
24414 			 * the next ire and re-enter the loop.
24415 			 */
24416 			ASSERT(ire1);
24417 			ASSERT(next_mp);
24418 			/* REFRELE the current ire before looping */
24419 			ire_refrele(ire);
24420 			ire = ire1;
24421 			ire1 = NULL;
24422 			mp = next_mp;
24423 			next_mp = NULL;
24424 		}
24425 	} while (multirt_send);
24426 
24427 	ASSERT(ire1 == NULL);
24428 
24429 	/* Restore the original ire; we need it for the trailing frags */
24430 	if (save_ire != NULL) {
24431 		/* REFRELE the last iterated ire */
24432 		ire_refrele(ire);
24433 		/* save_ire has been REFHOLDed */
24434 		ire = save_ire;
24435 		save_ire = NULL;
24436 		q = ire->ire_stq;
24437 	}
24438 
24439 	if (pkt_type == OB_PKT) {
24440 		UPDATE_OB_PKT_COUNT(ire);
24441 	} else {
24442 		out_ill = (ill_t *)q->q_ptr;
24443 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24444 		UPDATE_IB_PKT_COUNT(ire);
24445 	}
24446 
24447 	/* Advance the offset to the second frag starting point. */
24448 	offset += len;
24449 	/*
24450 	 * Update hdr_len from the copied header - there might be less options
24451 	 * in the later fragments.
24452 	 */
24453 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24454 	/* Loop until done. */
24455 	for (;;) {
24456 		uint16_t	offset_and_flags;
24457 		uint16_t	ip_len;
24458 
24459 		if (ip_data_end - offset > len) {
24460 			/*
24461 			 * Carve off the appropriate amount from the original
24462 			 * datagram.
24463 			 */
24464 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24465 				mp = NULL;
24466 				break;
24467 			}
24468 			/*
24469 			 * More frags after this one.  Get another copy
24470 			 * of the header.
24471 			 */
24472 			if (carve_mp->b_datap->db_ref == 1 &&
24473 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24474 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24475 				/* Inline IP header */
24476 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24477 				    hdr_mp->b_rptr;
24478 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24479 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24480 				mp = carve_mp;
24481 			} else {
24482 				if (!(mp = copyb(hdr_mp))) {
24483 					freemsg(carve_mp);
24484 					break;
24485 				}
24486 				/* Get priority marking, if any. */
24487 				mp->b_band = carve_mp->b_band;
24488 				mp->b_cont = carve_mp;
24489 			}
24490 			ipha = (ipha_t *)mp->b_rptr;
24491 			offset_and_flags = IPH_MF;
24492 		} else {
24493 			/*
24494 			 * Last frag.  Consume the header. Set len to
24495 			 * the length of this last piece.
24496 			 */
24497 			len = ip_data_end - offset;
24498 
24499 			/*
24500 			 * Carve off the appropriate amount from the original
24501 			 * datagram.
24502 			 */
24503 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24504 				mp = NULL;
24505 				break;
24506 			}
24507 			if (carve_mp->b_datap->db_ref == 1 &&
24508 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24509 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24510 				/* Inline IP header */
24511 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24512 				    hdr_mp->b_rptr;
24513 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24514 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24515 				mp = carve_mp;
24516 				freeb(hdr_mp);
24517 				hdr_mp = mp;
24518 			} else {
24519 				mp = hdr_mp;
24520 				/* Get priority marking, if any. */
24521 				mp->b_band = carve_mp->b_band;
24522 				mp->b_cont = carve_mp;
24523 			}
24524 			ipha = (ipha_t *)mp->b_rptr;
24525 			/* A frag of a frag might have IPH_MF non-zero */
24526 			offset_and_flags =
24527 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24528 			    IPH_MF;
24529 		}
24530 		offset_and_flags |= (uint16_t)(offset >> 3);
24531 		offset_and_flags |= (uint16_t)frag_flag;
24532 		/* Store the offset and flags in the IP header. */
24533 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24534 
24535 		/* Store the length in the IP header. */
24536 		ip_len = (uint16_t)(len + hdr_len);
24537 		ipha->ipha_length = htons(ip_len);
24538 
24539 		/*
24540 		 * Set the IP header checksum.	Note that mp is just
24541 		 * the header, so this is easy to pass to ip_csum.
24542 		 */
24543 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24544 
24545 		/* Attach a transmit header, if any, and ship it. */
24546 		if (pkt_type == OB_PKT) {
24547 			UPDATE_OB_PKT_COUNT(ire);
24548 		} else {
24549 			out_ill = (ill_t *)q->q_ptr;
24550 			BUMP_MIB(out_ill->ill_ip_mib,
24551 			    ipIfStatsHCOutForwDatagrams);
24552 			UPDATE_IB_PKT_COUNT(ire);
24553 		}
24554 
24555 		if (ire->ire_flags & RTF_MULTIRT) {
24556 			irb = ire->ire_bucket;
24557 			ASSERT(irb != NULL);
24558 
24559 			multirt_send = B_TRUE;
24560 
24561 			/*
24562 			 * Save the original ire; we will need to restore it
24563 			 * for the tailing frags.
24564 			 */
24565 			save_ire = ire;
24566 			IRE_REFHOLD(save_ire);
24567 		}
24568 		/*
24569 		 * Emission loop for this fragment, similar
24570 		 * to what is done for the first fragment.
24571 		 */
24572 		do {
24573 			if (multirt_send) {
24574 				/*
24575 				 * We are in a multiple send case, need to get
24576 				 * the next ire and make a copy of the packet.
24577 				 */
24578 				ASSERT(irb != NULL);
24579 				IRB_REFHOLD(irb);
24580 				for (ire1 = ire->ire_next;
24581 				    ire1 != NULL;
24582 				    ire1 = ire1->ire_next) {
24583 					if (!(ire1->ire_flags & RTF_MULTIRT))
24584 						continue;
24585 					if (ire1->ire_addr != ire->ire_addr)
24586 						continue;
24587 					if (ire1->ire_marks &
24588 					    (IRE_MARK_CONDEMNED |
24589 					    IRE_MARK_TESTHIDDEN))
24590 						continue;
24591 					/*
24592 					 * Ensure we do not exceed the MTU
24593 					 * of the next route.
24594 					 */
24595 					if (ire1->ire_max_frag < max_frag) {
24596 						ip_multirt_bad_mtu(ire1,
24597 						    max_frag);
24598 						continue;
24599 					}
24600 
24601 					/* Got one. */
24602 					IRE_REFHOLD(ire1);
24603 					break;
24604 				}
24605 				IRB_REFRELE(irb);
24606 
24607 				if (ire1 != NULL) {
24608 					next_mp = copyb(mp);
24609 					if ((next_mp == NULL) ||
24610 					    ((mp->b_cont != NULL) &&
24611 					    ((next_mp->b_cont =
24612 					    dupmsg(mp->b_cont)) == NULL))) {
24613 						freemsg(next_mp);
24614 						next_mp = NULL;
24615 						ire_refrele(ire1);
24616 						ire1 = NULL;
24617 					}
24618 				}
24619 
24620 				/* Last multiroute ire; don't loop anymore. */
24621 				if (ire1 == NULL) {
24622 					multirt_send = B_FALSE;
24623 				}
24624 			}
24625 
24626 			/* Update transmit header */
24627 			ll_hdr_len = 0;
24628 			LOCK_IRE_FP_MP(ire);
24629 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24630 			if (ll_hdr_mp != NULL) {
24631 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24632 				ll_hdr_len = MBLKL(ll_hdr_mp);
24633 			} else {
24634 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24635 			}
24636 
24637 			if (!ll_hdr_mp) {
24638 				xmit_mp = mp;
24639 
24640 			/*
24641 			 * We have link-layer header that can fit in
24642 			 * our mblk.
24643 			 */
24644 			} else if (mp->b_datap->db_ref == 1 &&
24645 			    ll_hdr_len != 0 &&
24646 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24647 				/* M_DATA fastpath */
24648 				mp->b_rptr -= ll_hdr_len;
24649 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24650 				    ll_hdr_len);
24651 				xmit_mp = mp;
24652 
24653 			/*
24654 			 * Case of res_mp OR the fastpath mp can't fit
24655 			 * in the mblk
24656 			 */
24657 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24658 				xmit_mp->b_cont = mp;
24659 				/* Get priority marking, if any. */
24660 				if (DB_TYPE(xmit_mp) == M_DATA)
24661 					xmit_mp->b_band = mp->b_band;
24662 
24663 			/* Corner case if copyb failed */
24664 			} else {
24665 				/*
24666 				 * Exit both the replication and
24667 				 * fragmentation loops.
24668 				 */
24669 				UNLOCK_IRE_FP_MP(ire);
24670 				goto drop_pkt;
24671 			}
24672 			UNLOCK_IRE_FP_MP(ire);
24673 
24674 			mp1 = mp;
24675 			out_ill = (ill_t *)q->q_ptr;
24676 
24677 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24678 
24679 			DTRACE_PROBE4(ip4__physical__out__start,
24680 			    ill_t *, NULL, ill_t *, out_ill,
24681 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24682 
24683 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24684 			    ipst->ips_ipv4firewall_physical_out,
24685 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24686 
24687 			DTRACE_PROBE1(ip4__physical__out__end,
24688 			    mblk_t *, xmit_mp);
24689 
24690 			if (mp != mp1 && hdr_mp == mp1)
24691 				hdr_mp = mp;
24692 			if (mp != mp1 && mp_orig == mp1)
24693 				mp_orig = mp;
24694 
24695 			if (xmit_mp != NULL) {
24696 				DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *,
24697 				    NULL, void_ip_t *, ipha,
24698 				    __dtrace_ipsr_ill_t *, out_ill, ipha_t *,
24699 				    ipha, ip6_t *, NULL, int, 0);
24700 
24701 				ILL_SEND_TX(out_ill, ire, connp, xmit_mp, 0);
24702 
24703 				BUMP_MIB(out_ill->ill_ip_mib,
24704 				    ipIfStatsHCOutTransmits);
24705 				UPDATE_MIB(out_ill->ill_ip_mib,
24706 				    ipIfStatsHCOutOctets, ip_len);
24707 
24708 				if (pkt_type != OB_PKT) {
24709 					/*
24710 					 * Update the packet count of trailing
24711 					 * RTF_MULTIRT ires.
24712 					 */
24713 					UPDATE_OB_PKT_COUNT(ire);
24714 				}
24715 			}
24716 
24717 			/* All done if we just consumed the hdr_mp. */
24718 			if (mp == hdr_mp) {
24719 				last_frag = B_TRUE;
24720 				BUMP_MIB(out_ill->ill_ip_mib,
24721 				    ipIfStatsOutFragOKs);
24722 			}
24723 
24724 			if (multirt_send) {
24725 				/*
24726 				 * We are in a multiple send case; look for
24727 				 * the next ire and re-enter the loop.
24728 				 */
24729 				ASSERT(ire1);
24730 				ASSERT(next_mp);
24731 				/* REFRELE the current ire before looping */
24732 				ire_refrele(ire);
24733 				ire = ire1;
24734 				ire1 = NULL;
24735 				q = ire->ire_stq;
24736 				mp = next_mp;
24737 				next_mp = NULL;
24738 			}
24739 		} while (multirt_send);
24740 		/*
24741 		 * Restore the original ire; we need it for the
24742 		 * trailing frags
24743 		 */
24744 		if (save_ire != NULL) {
24745 			ASSERT(ire1 == NULL);
24746 			/* REFRELE the last iterated ire */
24747 			ire_refrele(ire);
24748 			/* save_ire has been REFHOLDed */
24749 			ire = save_ire;
24750 			q = ire->ire_stq;
24751 			save_ire = NULL;
24752 		}
24753 
24754 		if (last_frag) {
24755 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24756 			    "ip_wput_frag_end:(%S)",
24757 			    "consumed hdr_mp");
24758 
24759 			if (first_ire != NULL)
24760 				ire_refrele(first_ire);
24761 			return;
24762 		}
24763 		/* Otherwise, advance and loop. */
24764 		offset += len;
24765 	}
24766 
24767 drop_pkt:
24768 	/* Clean up following allocation failure. */
24769 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24770 	freemsg(mp);
24771 	if (mp != hdr_mp)
24772 		freeb(hdr_mp);
24773 	if (mp != mp_orig)
24774 		freemsg(mp_orig);
24775 
24776 	if (save_ire != NULL)
24777 		IRE_REFRELE(save_ire);
24778 	if (first_ire != NULL)
24779 		ire_refrele(first_ire);
24780 
24781 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24782 	    "ip_wput_frag_end:(%S)",
24783 	    "end--alloc failure");
24784 }
24785 
24786 /*
24787  * Copy the header plus those options which have the copy bit set
24788  * src is the template to make sure we preserve the cred for TX purposes.
24789  */
24790 static mblk_t *
24791 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
24792     mblk_t *src)
24793 {
24794 	mblk_t	*mp;
24795 	uchar_t	*up;
24796 
24797 	/*
24798 	 * Quick check if we need to look for options without the copy bit
24799 	 * set
24800 	 */
24801 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
24802 	if (!mp)
24803 		return (mp);
24804 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24805 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24806 		bcopy(rptr, mp->b_rptr, hdr_len);
24807 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24808 		return (mp);
24809 	}
24810 	up  = mp->b_rptr;
24811 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24812 	up += IP_SIMPLE_HDR_LENGTH;
24813 	rptr += IP_SIMPLE_HDR_LENGTH;
24814 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24815 	while (hdr_len > 0) {
24816 		uint32_t optval;
24817 		uint32_t optlen;
24818 
24819 		optval = *rptr;
24820 		if (optval == IPOPT_EOL)
24821 			break;
24822 		if (optval == IPOPT_NOP)
24823 			optlen = 1;
24824 		else
24825 			optlen = rptr[1];
24826 		if (optval & IPOPT_COPY) {
24827 			bcopy(rptr, up, optlen);
24828 			up += optlen;
24829 		}
24830 		rptr += optlen;
24831 		hdr_len -= optlen;
24832 	}
24833 	/*
24834 	 * Make sure that we drop an even number of words by filling
24835 	 * with EOL to the next word boundary.
24836 	 */
24837 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24838 	    hdr_len & 0x3; hdr_len++)
24839 		*up++ = IPOPT_EOL;
24840 	mp->b_wptr = up;
24841 	/* Update header length */
24842 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24843 	return (mp);
24844 }
24845 
24846 /*
24847  * Delivery to local recipients including fanout to multiple recipients.
24848  * Does not do checksumming of UDP/TCP.
24849  * Note: q should be the read side queue for either the ill or conn.
24850  * Note: rq should be the read side q for the lower (ill) stream.
24851  * We don't send packets to IPPF processing, thus the last argument
24852  * to all the fanout calls are B_FALSE.
24853  */
24854 void
24855 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24856     int fanout_flags, zoneid_t zoneid)
24857 {
24858 	uint32_t	protocol;
24859 	mblk_t		*first_mp;
24860 	boolean_t	mctl_present;
24861 	int		ire_type;
24862 #define	rptr	((uchar_t *)ipha)
24863 	ip_stack_t	*ipst = ill->ill_ipst;
24864 
24865 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24866 	    "ip_wput_local_start: q %p", q);
24867 
24868 	if (ire != NULL) {
24869 		ire_type = ire->ire_type;
24870 	} else {
24871 		/*
24872 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24873 		 * packet is not multicast, we can't tell the ire type.
24874 		 */
24875 		ASSERT(CLASSD(ipha->ipha_dst));
24876 		ire_type = IRE_BROADCAST;
24877 	}
24878 
24879 	first_mp = mp;
24880 	if (first_mp->b_datap->db_type == M_CTL) {
24881 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24882 		if (!io->ipsec_out_secure) {
24883 			/*
24884 			 * This ipsec_out_t was allocated in ip_wput
24885 			 * for multicast packets to store the ill_index.
24886 			 * As this is being delivered locally, we don't
24887 			 * need this anymore.
24888 			 */
24889 			mp = first_mp->b_cont;
24890 			freeb(first_mp);
24891 			first_mp = mp;
24892 			mctl_present = B_FALSE;
24893 		} else {
24894 			/*
24895 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24896 			 * security properties for the looped-back packet.
24897 			 */
24898 			mctl_present = B_TRUE;
24899 			mp = first_mp->b_cont;
24900 			ASSERT(mp != NULL);
24901 			ipsec_out_to_in(first_mp);
24902 		}
24903 	} else {
24904 		mctl_present = B_FALSE;
24905 	}
24906 
24907 	DTRACE_PROBE4(ip4__loopback__in__start,
24908 	    ill_t *, ill, ill_t *, NULL,
24909 	    ipha_t *, ipha, mblk_t *, first_mp);
24910 
24911 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
24912 	    ipst->ips_ipv4firewall_loopback_in,
24913 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
24914 
24915 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24916 
24917 	if (first_mp == NULL)
24918 		return;
24919 
24920 	if (ipst->ips_ipobs_enabled) {
24921 		zoneid_t szone, dzone, lookup_zoneid = ALL_ZONES;
24922 		zoneid_t stackzoneid = netstackid_to_zoneid(
24923 		    ipst->ips_netstack->netstack_stackid);
24924 
24925 		dzone = (stackzoneid == GLOBAL_ZONEID) ? zoneid : stackzoneid;
24926 		/*
24927 		 * 127.0.0.1 is special, as we cannot lookup its zoneid by
24928 		 * address.  Restrict the lookup below to the destination zone.
24929 		 */
24930 		if (ipha->ipha_src == ntohl(INADDR_LOOPBACK))
24931 			lookup_zoneid = zoneid;
24932 		szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
24933 		    lookup_zoneid);
24934 		ipobs_hook(mp, IPOBS_HOOK_LOCAL, szone, dzone, ill,
24935 		    IPV4_VERSION, 0, ipst);
24936 	}
24937 
24938 	DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL, void_ip_t *,
24939 	    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *, NULL,
24940 	    int, 1);
24941 
24942 	ipst->ips_loopback_packets++;
24943 
24944 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
24945 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
24946 	if (!IS_SIMPLE_IPH(ipha)) {
24947 		ip_wput_local_options(ipha, ipst);
24948 	}
24949 
24950 	protocol = ipha->ipha_protocol;
24951 	switch (protocol) {
24952 	case IPPROTO_ICMP: {
24953 		ire_t		*ire_zone;
24954 		ilm_t		*ilm;
24955 		mblk_t		*mp1;
24956 		zoneid_t	last_zoneid;
24957 		ilm_walker_t	ilw;
24958 
24959 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
24960 			ASSERT(ire_type == IRE_BROADCAST);
24961 			/*
24962 			 * In the multicast case, applications may have joined
24963 			 * the group from different zones, so we need to deliver
24964 			 * the packet to each of them. Loop through the
24965 			 * multicast memberships structures (ilm) on the receive
24966 			 * ill and send a copy of the packet up each matching
24967 			 * one. However, we don't do this for multicasts sent on
24968 			 * the loopback interface (PHYI_LOOPBACK flag set) as
24969 			 * they must stay in the sender's zone.
24970 			 *
24971 			 * ilm_add_v6() ensures that ilms in the same zone are
24972 			 * contiguous in the ill_ilm list. We use this property
24973 			 * to avoid sending duplicates needed when two
24974 			 * applications in the same zone join the same group on
24975 			 * different logical interfaces: we ignore the ilm if
24976 			 * it's zoneid is the same as the last matching one.
24977 			 * In addition, the sending of the packet for
24978 			 * ire_zoneid is delayed until all of the other ilms
24979 			 * have been exhausted.
24980 			 */
24981 			last_zoneid = -1;
24982 			ilm = ilm_walker_start(&ilw, ill);
24983 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
24984 				if (ipha->ipha_dst != ilm->ilm_addr ||
24985 				    ilm->ilm_zoneid == last_zoneid ||
24986 				    ilm->ilm_zoneid == zoneid ||
24987 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
24988 					continue;
24989 				mp1 = ip_copymsg(first_mp);
24990 				if (mp1 == NULL)
24991 					continue;
24992 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
24993 				    0, 0, mctl_present, B_FALSE, ill,
24994 				    ilm->ilm_zoneid);
24995 				last_zoneid = ilm->ilm_zoneid;
24996 			}
24997 			ilm_walker_finish(&ilw);
24998 			/*
24999 			 * Loopback case: the sending endpoint has
25000 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25001 			 * dispatch the multicast packet to the sending zone.
25002 			 */
25003 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25004 				freemsg(first_mp);
25005 				return;
25006 			}
25007 		} else if (ire_type == IRE_BROADCAST) {
25008 			/*
25009 			 * In the broadcast case, there may be many zones
25010 			 * which need a copy of the packet delivered to them.
25011 			 * There is one IRE_BROADCAST per broadcast address
25012 			 * and per zone; we walk those using a helper function.
25013 			 * In addition, the sending of the packet for zoneid is
25014 			 * delayed until all of the other ires have been
25015 			 * processed.
25016 			 */
25017 			IRB_REFHOLD(ire->ire_bucket);
25018 			ire_zone = NULL;
25019 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25020 			    ire)) != NULL) {
25021 				mp1 = ip_copymsg(first_mp);
25022 				if (mp1 == NULL)
25023 					continue;
25024 
25025 				UPDATE_IB_PKT_COUNT(ire_zone);
25026 				ire_zone->ire_last_used_time = lbolt;
25027 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25028 				    mctl_present, B_FALSE, ill,
25029 				    ire_zone->ire_zoneid);
25030 			}
25031 			IRB_REFRELE(ire->ire_bucket);
25032 		}
25033 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25034 		    0, mctl_present, B_FALSE, ill, zoneid);
25035 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25036 		    "ip_wput_local_end: q %p (%S)",
25037 		    q, "icmp");
25038 		return;
25039 	}
25040 	case IPPROTO_IGMP:
25041 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25042 			/* Bad packet - discarded by igmp_input */
25043 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25044 			    "ip_wput_local_end: q %p (%S)",
25045 			    q, "igmp_input--bad packet");
25046 			if (mctl_present)
25047 				freeb(first_mp);
25048 			return;
25049 		}
25050 		/*
25051 		 * igmp_input() may have returned the pulled up message.
25052 		 * So first_mp and ipha need to be reinitialized.
25053 		 */
25054 		ipha = (ipha_t *)mp->b_rptr;
25055 		if (mctl_present)
25056 			first_mp->b_cont = mp;
25057 		else
25058 			first_mp = mp;
25059 		/* deliver to local raw users */
25060 		break;
25061 	case IPPROTO_ENCAP:
25062 		/*
25063 		 * This case is covered by either ip_fanout_proto, or by
25064 		 * the above security processing for self-tunneled packets.
25065 		 */
25066 		break;
25067 	case IPPROTO_UDP: {
25068 		uint16_t	*up;
25069 		uint32_t	ports;
25070 
25071 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25072 		    UDP_PORTS_OFFSET);
25073 		/* Force a 'valid' checksum. */
25074 		up[3] = 0;
25075 
25076 		ports = *(uint32_t *)up;
25077 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25078 		    (ire_type == IRE_BROADCAST),
25079 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25080 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25081 		    ill, zoneid);
25082 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25083 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25084 		return;
25085 	}
25086 	case IPPROTO_TCP: {
25087 
25088 		/*
25089 		 * For TCP, discard broadcast packets.
25090 		 */
25091 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25092 			freemsg(first_mp);
25093 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25094 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25095 			return;
25096 		}
25097 
25098 		if (mp->b_datap->db_type == M_DATA) {
25099 			/*
25100 			 * M_DATA mblk, so init mblk (chain) for no struio().
25101 			 */
25102 			mblk_t	*mp1 = mp;
25103 
25104 			do {
25105 				mp1->b_datap->db_struioflag = 0;
25106 			} while ((mp1 = mp1->b_cont) != NULL);
25107 		}
25108 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25109 		    <= mp->b_wptr);
25110 		ip_fanout_tcp(q, first_mp, ill, ipha,
25111 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25112 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25113 		    mctl_present, B_FALSE, zoneid);
25114 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25115 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25116 		return;
25117 	}
25118 	case IPPROTO_SCTP:
25119 	{
25120 		uint32_t	ports;
25121 
25122 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25123 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25124 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25125 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25126 		return;
25127 	}
25128 
25129 	default:
25130 		break;
25131 	}
25132 	/*
25133 	 * Find a client for some other protocol.  We give
25134 	 * copies to multiple clients, if more than one is
25135 	 * bound.
25136 	 */
25137 	ip_fanout_proto(q, first_mp, ill, ipha,
25138 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25139 	    mctl_present, B_FALSE, ill, zoneid);
25140 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25141 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25142 #undef	rptr
25143 }
25144 
25145 /*
25146  * Update any source route, record route, or timestamp options.
25147  * Check that we are at end of strict source route.
25148  * The options have been sanity checked by ip_wput_options().
25149  */
25150 static void
25151 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25152 {
25153 	ipoptp_t	opts;
25154 	uchar_t		*opt;
25155 	uint8_t		optval;
25156 	uint8_t		optlen;
25157 	ipaddr_t	dst;
25158 	uint32_t	ts;
25159 	ire_t		*ire;
25160 	timestruc_t	now;
25161 
25162 	ip2dbg(("ip_wput_local_options\n"));
25163 	for (optval = ipoptp_first(&opts, ipha);
25164 	    optval != IPOPT_EOL;
25165 	    optval = ipoptp_next(&opts)) {
25166 		opt = opts.ipoptp_cur;
25167 		optlen = opts.ipoptp_len;
25168 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25169 		switch (optval) {
25170 			uint32_t off;
25171 		case IPOPT_SSRR:
25172 		case IPOPT_LSRR:
25173 			off = opt[IPOPT_OFFSET];
25174 			off--;
25175 			if (optlen < IP_ADDR_LEN ||
25176 			    off > optlen - IP_ADDR_LEN) {
25177 				/* End of source route */
25178 				break;
25179 			}
25180 			/*
25181 			 * This will only happen if two consecutive entries
25182 			 * in the source route contains our address or if
25183 			 * it is a packet with a loose source route which
25184 			 * reaches us before consuming the whole source route
25185 			 */
25186 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25187 			if (optval == IPOPT_SSRR) {
25188 				return;
25189 			}
25190 			/*
25191 			 * Hack: instead of dropping the packet truncate the
25192 			 * source route to what has been used by filling the
25193 			 * rest with IPOPT_NOP.
25194 			 */
25195 			opt[IPOPT_OLEN] = (uint8_t)off;
25196 			while (off < optlen) {
25197 				opt[off++] = IPOPT_NOP;
25198 			}
25199 			break;
25200 		case IPOPT_RR:
25201 			off = opt[IPOPT_OFFSET];
25202 			off--;
25203 			if (optlen < IP_ADDR_LEN ||
25204 			    off > optlen - IP_ADDR_LEN) {
25205 				/* No more room - ignore */
25206 				ip1dbg((
25207 				    "ip_wput_forward_options: end of RR\n"));
25208 				break;
25209 			}
25210 			dst = htonl(INADDR_LOOPBACK);
25211 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25212 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25213 			break;
25214 		case IPOPT_TS:
25215 			/* Insert timestamp if there is romm */
25216 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25217 			case IPOPT_TS_TSONLY:
25218 				off = IPOPT_TS_TIMELEN;
25219 				break;
25220 			case IPOPT_TS_PRESPEC:
25221 			case IPOPT_TS_PRESPEC_RFC791:
25222 				/* Verify that the address matched */
25223 				off = opt[IPOPT_OFFSET] - 1;
25224 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25225 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25226 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25227 				    ipst);
25228 				if (ire == NULL) {
25229 					/* Not for us */
25230 					break;
25231 				}
25232 				ire_refrele(ire);
25233 				/* FALLTHRU */
25234 			case IPOPT_TS_TSANDADDR:
25235 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25236 				break;
25237 			default:
25238 				/*
25239 				 * ip_*put_options should have already
25240 				 * dropped this packet.
25241 				 */
25242 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25243 				    "unknown IT - bug in ip_wput_options?\n");
25244 				return;	/* Keep "lint" happy */
25245 			}
25246 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25247 				/* Increase overflow counter */
25248 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25249 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25250 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25251 				    (off << 4);
25252 				break;
25253 			}
25254 			off = opt[IPOPT_OFFSET] - 1;
25255 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25256 			case IPOPT_TS_PRESPEC:
25257 			case IPOPT_TS_PRESPEC_RFC791:
25258 			case IPOPT_TS_TSANDADDR:
25259 				dst = htonl(INADDR_LOOPBACK);
25260 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25261 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25262 				/* FALLTHRU */
25263 			case IPOPT_TS_TSONLY:
25264 				off = opt[IPOPT_OFFSET] - 1;
25265 				/* Compute # of milliseconds since midnight */
25266 				gethrestime(&now);
25267 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25268 				    now.tv_nsec / (NANOSEC / MILLISEC);
25269 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25270 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25271 				break;
25272 			}
25273 			break;
25274 		}
25275 	}
25276 }
25277 
25278 /*
25279  * Send out a multicast packet on interface ipif.
25280  * The sender does not have an conn.
25281  * Caller verifies that this isn't a PHYI_LOOPBACK.
25282  */
25283 void
25284 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25285 {
25286 	ipha_t	*ipha;
25287 	ire_t	*ire;
25288 	ipaddr_t	dst;
25289 	mblk_t		*first_mp;
25290 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25291 
25292 	/* igmp_sendpkt always allocates a ipsec_out_t */
25293 	ASSERT(mp->b_datap->db_type == M_CTL);
25294 	ASSERT(!ipif->ipif_isv6);
25295 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25296 
25297 	first_mp = mp;
25298 	mp = first_mp->b_cont;
25299 	ASSERT(mp->b_datap->db_type == M_DATA);
25300 	ipha = (ipha_t *)mp->b_rptr;
25301 
25302 	/*
25303 	 * Find an IRE which matches the destination and the outgoing
25304 	 * queue (i.e. the outgoing interface.)
25305 	 */
25306 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25307 		dst = ipif->ipif_pp_dst_addr;
25308 	else
25309 		dst = ipha->ipha_dst;
25310 	/*
25311 	 * The source address has already been initialized by the
25312 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25313 	 * be sufficient rather than MATCH_IRE_IPIF.
25314 	 *
25315 	 * This function is used for sending IGMP packets.  For IPMP,
25316 	 * we sidestep IGMP snooping issues by sending all multicast
25317 	 * traffic on a single interface in the IPMP group.
25318 	 */
25319 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25320 	    MATCH_IRE_ILL, ipst);
25321 	if (!ire) {
25322 		/*
25323 		 * Mark this packet to make it be delivered to
25324 		 * ip_wput_ire after the new ire has been
25325 		 * created.
25326 		 */
25327 		mp->b_prev = NULL;
25328 		mp->b_next = NULL;
25329 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25330 		    zoneid, &zero_info);
25331 		return;
25332 	}
25333 
25334 	/*
25335 	 * Honor the RTF_SETSRC flag; this is the only case
25336 	 * where we force this addr whatever the current src addr is,
25337 	 * because this address is set by igmp_sendpkt(), and
25338 	 * cannot be specified by any user.
25339 	 */
25340 	if (ire->ire_flags & RTF_SETSRC) {
25341 		ipha->ipha_src = ire->ire_src_addr;
25342 	}
25343 
25344 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25345 }
25346 
25347 /*
25348  * NOTE : This function does not ire_refrele the ire argument passed in.
25349  *
25350  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25351  * failure. The nce_fp_mp can vanish any time in the case of
25352  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25353  * the ire_lock to access the nce_fp_mp in this case.
25354  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25355  * prepending a fastpath message IPQoS processing must precede it, we also set
25356  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25357  * (IPQoS might have set the b_band for CoS marking).
25358  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25359  * must follow it so that IPQoS can mark the dl_priority field for CoS
25360  * marking, if needed.
25361  */
25362 static mblk_t *
25363 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc,
25364     uint32_t ill_index, ipha_t **iphap)
25365 {
25366 	uint_t	hlen;
25367 	ipha_t *ipha;
25368 	mblk_t *mp1;
25369 	boolean_t qos_done = B_FALSE;
25370 	uchar_t	*ll_hdr;
25371 	ip_stack_t	*ipst = ire->ire_ipst;
25372 
25373 #define	rptr	((uchar_t *)ipha)
25374 
25375 	ipha = (ipha_t *)mp->b_rptr;
25376 	hlen = 0;
25377 	LOCK_IRE_FP_MP(ire);
25378 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25379 		ASSERT(DB_TYPE(mp1) == M_DATA);
25380 		/* Initiate IPPF processing */
25381 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25382 			UNLOCK_IRE_FP_MP(ire);
25383 			ip_process(proc, &mp, ill_index);
25384 			if (mp == NULL)
25385 				return (NULL);
25386 
25387 			ipha = (ipha_t *)mp->b_rptr;
25388 			LOCK_IRE_FP_MP(ire);
25389 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25390 				qos_done = B_TRUE;
25391 				goto no_fp_mp;
25392 			}
25393 			ASSERT(DB_TYPE(mp1) == M_DATA);
25394 		}
25395 		hlen = MBLKL(mp1);
25396 		/*
25397 		 * Check if we have enough room to prepend fastpath
25398 		 * header
25399 		 */
25400 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25401 			ll_hdr = rptr - hlen;
25402 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25403 			/*
25404 			 * Set the b_rptr to the start of the link layer
25405 			 * header
25406 			 */
25407 			mp->b_rptr = ll_hdr;
25408 			mp1 = mp;
25409 		} else {
25410 			mp1 = copyb(mp1);
25411 			if (mp1 == NULL)
25412 				goto unlock_err;
25413 			mp1->b_band = mp->b_band;
25414 			mp1->b_cont = mp;
25415 			/*
25416 			 * XXX disable ICK_VALID and compute checksum
25417 			 * here; can happen if nce_fp_mp changes and
25418 			 * it can't be copied now due to insufficient
25419 			 * space. (unlikely, fp mp can change, but it
25420 			 * does not increase in length)
25421 			 */
25422 		}
25423 		UNLOCK_IRE_FP_MP(ire);
25424 	} else {
25425 no_fp_mp:
25426 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25427 		if (mp1 == NULL) {
25428 unlock_err:
25429 			UNLOCK_IRE_FP_MP(ire);
25430 			freemsg(mp);
25431 			return (NULL);
25432 		}
25433 		UNLOCK_IRE_FP_MP(ire);
25434 		mp1->b_cont = mp;
25435 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25436 			ip_process(proc, &mp1, ill_index);
25437 			if (mp1 == NULL)
25438 				return (NULL);
25439 
25440 			if (mp1->b_cont == NULL)
25441 				ipha = NULL;
25442 			else
25443 				ipha = (ipha_t *)mp1->b_cont->b_rptr;
25444 		}
25445 	}
25446 
25447 	*iphap = ipha;
25448 	return (mp1);
25449 #undef rptr
25450 }
25451 
25452 /*
25453  * Finish the outbound IPsec processing for an IPv6 packet. This function
25454  * is called from ipsec_out_process() if the IPsec packet was processed
25455  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25456  * asynchronously.
25457  */
25458 void
25459 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25460     ire_t *ire_arg)
25461 {
25462 	in6_addr_t *v6dstp;
25463 	ire_t *ire;
25464 	mblk_t *mp;
25465 	ip6_t *ip6h1;
25466 	uint_t	ill_index;
25467 	ipsec_out_t *io;
25468 	boolean_t hwaccel;
25469 	uint32_t flags = IP6_NO_IPPOLICY;
25470 	int match_flags;
25471 	zoneid_t zoneid;
25472 	boolean_t ill_need_rele = B_FALSE;
25473 	boolean_t ire_need_rele = B_FALSE;
25474 	ip_stack_t	*ipst;
25475 
25476 	mp = ipsec_mp->b_cont;
25477 	ip6h1 = (ip6_t *)mp->b_rptr;
25478 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25479 	ASSERT(io->ipsec_out_ns != NULL);
25480 	ipst = io->ipsec_out_ns->netstack_ip;
25481 	ill_index = io->ipsec_out_ill_index;
25482 	if (io->ipsec_out_reachable) {
25483 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25484 	}
25485 	hwaccel = io->ipsec_out_accelerated;
25486 	zoneid = io->ipsec_out_zoneid;
25487 	ASSERT(zoneid != ALL_ZONES);
25488 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25489 	/* Multicast addresses should have non-zero ill_index. */
25490 	v6dstp = &ip6h->ip6_dst;
25491 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25492 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25493 
25494 	if (ill == NULL && ill_index != 0) {
25495 		ill = ip_grab_ill(ipsec_mp, ill_index, B_TRUE, ipst);
25496 		/* Failure case frees things for us. */
25497 		if (ill == NULL)
25498 			return;
25499 
25500 		ill_need_rele = B_TRUE;
25501 	}
25502 	ASSERT(mp != NULL);
25503 
25504 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25505 		boolean_t unspec_src;
25506 		ipif_t	*ipif;
25507 
25508 		/*
25509 		 * Use the ill_index to get the right ill.
25510 		 */
25511 		unspec_src = io->ipsec_out_unspec_src;
25512 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25513 		if (ipif == NULL) {
25514 			if (ill_need_rele)
25515 				ill_refrele(ill);
25516 			freemsg(ipsec_mp);
25517 			return;
25518 		}
25519 
25520 		if (ire_arg != NULL) {
25521 			ire = ire_arg;
25522 		} else {
25523 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25524 			    zoneid, msg_getlabel(mp), match_flags, ipst);
25525 			ire_need_rele = B_TRUE;
25526 		}
25527 		if (ire != NULL) {
25528 			ipif_refrele(ipif);
25529 			/*
25530 			 * XXX Do the multicast forwarding now, as the IPsec
25531 			 * processing has been done.
25532 			 */
25533 			goto send;
25534 		}
25535 
25536 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25537 		mp->b_prev = NULL;
25538 		mp->b_next = NULL;
25539 
25540 		/*
25541 		 * If the IPsec packet was processed asynchronously,
25542 		 * drop it now.
25543 		 */
25544 		if (q == NULL) {
25545 			if (ill_need_rele)
25546 				ill_refrele(ill);
25547 			freemsg(ipsec_mp);
25548 			return;
25549 		}
25550 
25551 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, v6dstp, &ip6h->ip6_src,
25552 		    unspec_src, zoneid);
25553 		ipif_refrele(ipif);
25554 	} else {
25555 		if (ire_arg != NULL) {
25556 			ire = ire_arg;
25557 		} else {
25558 			ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL, ipst);
25559 			ire_need_rele = B_TRUE;
25560 		}
25561 		if (ire != NULL)
25562 			goto send;
25563 		/*
25564 		 * ire disappeared underneath.
25565 		 *
25566 		 * What we need to do here is the ip_newroute
25567 		 * logic to get the ire without doing the IPsec
25568 		 * processing. Follow the same old path. But this
25569 		 * time, ip_wput or ire_add_then_send will call us
25570 		 * directly as all the IPsec operations are done.
25571 		 */
25572 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25573 		mp->b_prev = NULL;
25574 		mp->b_next = NULL;
25575 
25576 		/*
25577 		 * If the IPsec packet was processed asynchronously,
25578 		 * drop it now.
25579 		 */
25580 		if (q == NULL) {
25581 			if (ill_need_rele)
25582 				ill_refrele(ill);
25583 			freemsg(ipsec_mp);
25584 			return;
25585 		}
25586 
25587 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25588 		    zoneid, ipst);
25589 	}
25590 	if (ill != NULL && ill_need_rele)
25591 		ill_refrele(ill);
25592 	return;
25593 send:
25594 	if (ill != NULL && ill_need_rele)
25595 		ill_refrele(ill);
25596 
25597 	/* Local delivery */
25598 	if (ire->ire_stq == NULL) {
25599 		ill_t	*out_ill;
25600 		ASSERT(q != NULL);
25601 
25602 		/* PFHooks: LOOPBACK_OUT */
25603 		out_ill = ire_to_ill(ire);
25604 
25605 		/*
25606 		 * DTrace this as ip:::send.  A blocked packet will fire the
25607 		 * send probe, but not the receive probe.
25608 		 */
25609 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25610 		    void_ip_t *, ip6h, __dtrace_ipsr_ill_t *, out_ill,
25611 		    ipha_t *, NULL, ip6_t *, ip6h, int, 1);
25612 
25613 		DTRACE_PROBE4(ip6__loopback__out__start,
25614 		    ill_t *, NULL, ill_t *, out_ill,
25615 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25616 
25617 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25618 		    ipst->ips_ipv6firewall_loopback_out,
25619 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25620 
25621 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25622 
25623 		if (ipsec_mp != NULL) {
25624 			ip_wput_local_v6(RD(q), out_ill,
25625 			    ip6h, ipsec_mp, ire, 0, zoneid);
25626 		}
25627 		if (ire_need_rele)
25628 			ire_refrele(ire);
25629 		return;
25630 	}
25631 	/*
25632 	 * Everything is done. Send it out on the wire.
25633 	 * We force the insertion of a fragment header using the
25634 	 * IPH_FRAG_HDR flag in two cases:
25635 	 * - after reception of an ICMPv6 "packet too big" message
25636 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25637 	 * - for multirouted IPv6 packets, so that the receiver can
25638 	 *   discard duplicates according to their fragment identifier
25639 	 */
25640 	/* XXX fix flow control problems. */
25641 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25642 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25643 		if (hwaccel) {
25644 			/*
25645 			 * hardware acceleration does not handle these
25646 			 * "slow path" cases.
25647 			 */
25648 			/* IPsec KSTATS: should bump bean counter here. */
25649 			if (ire_need_rele)
25650 				ire_refrele(ire);
25651 			freemsg(ipsec_mp);
25652 			return;
25653 		}
25654 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25655 		    (mp->b_cont ? msgdsize(mp) :
25656 		    mp->b_wptr - (uchar_t *)ip6h)) {
25657 			/* IPsec KSTATS: should bump bean counter here. */
25658 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25659 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25660 			    msgdsize(mp)));
25661 			if (ire_need_rele)
25662 				ire_refrele(ire);
25663 			freemsg(ipsec_mp);
25664 			return;
25665 		}
25666 		ASSERT(mp->b_prev == NULL);
25667 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25668 		    ntohs(ip6h->ip6_plen) +
25669 		    IPV6_HDR_LEN, ire->ire_max_frag));
25670 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25671 		    ire->ire_max_frag);
25672 	} else {
25673 		UPDATE_OB_PKT_COUNT(ire);
25674 		ire->ire_last_used_time = lbolt;
25675 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25676 	}
25677 	if (ire_need_rele)
25678 		ire_refrele(ire);
25679 	freeb(ipsec_mp);
25680 }
25681 
25682 void
25683 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25684 {
25685 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25686 	da_ipsec_t *hada;	/* data attributes */
25687 	ill_t *ill = (ill_t *)q->q_ptr;
25688 
25689 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25690 
25691 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25692 		/* IPsec KSTATS: Bump lose counter here! */
25693 		freemsg(mp);
25694 		return;
25695 	}
25696 
25697 	/*
25698 	 * It's an IPsec packet that must be
25699 	 * accelerated by the Provider, and the
25700 	 * outbound ill is IPsec acceleration capable.
25701 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25702 	 * to the ill.
25703 	 * IPsec KSTATS: should bump packet counter here.
25704 	 */
25705 
25706 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25707 	if (hada_mp == NULL) {
25708 		/* IPsec KSTATS: should bump packet counter here. */
25709 		freemsg(mp);
25710 		return;
25711 	}
25712 
25713 	hada_mp->b_datap->db_type = M_CTL;
25714 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25715 	hada_mp->b_cont = mp;
25716 
25717 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25718 	bzero(hada, sizeof (da_ipsec_t));
25719 	hada->da_type = IPHADA_M_CTL;
25720 
25721 	putnext(q, hada_mp);
25722 }
25723 
25724 /*
25725  * Finish the outbound IPsec processing. This function is called from
25726  * ipsec_out_process() if the IPsec packet was processed
25727  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25728  * asynchronously.
25729  */
25730 void
25731 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25732     ire_t *ire_arg)
25733 {
25734 	uint32_t v_hlen_tos_len;
25735 	ipaddr_t	dst;
25736 	ipif_t	*ipif = NULL;
25737 	ire_t *ire;
25738 	ire_t *ire1 = NULL;
25739 	mblk_t *next_mp = NULL;
25740 	uint32_t max_frag;
25741 	boolean_t multirt_send = B_FALSE;
25742 	mblk_t *mp;
25743 	ipha_t *ipha1;
25744 	uint_t	ill_index;
25745 	ipsec_out_t *io;
25746 	int match_flags;
25747 	irb_t *irb = NULL;
25748 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25749 	zoneid_t zoneid;
25750 	ipxmit_state_t	pktxmit_state;
25751 	ip_stack_t	*ipst;
25752 
25753 #ifdef	_BIG_ENDIAN
25754 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25755 #else
25756 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25757 #endif
25758 
25759 	mp = ipsec_mp->b_cont;
25760 	ipha1 = (ipha_t *)mp->b_rptr;
25761 	ASSERT(mp != NULL);
25762 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25763 	dst = ipha->ipha_dst;
25764 
25765 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25766 	ill_index = io->ipsec_out_ill_index;
25767 	zoneid = io->ipsec_out_zoneid;
25768 	ASSERT(zoneid != ALL_ZONES);
25769 	ipst = io->ipsec_out_ns->netstack_ip;
25770 	ASSERT(io->ipsec_out_ns != NULL);
25771 
25772 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25773 	if (ill == NULL && ill_index != 0) {
25774 		ill = ip_grab_ill(ipsec_mp, ill_index, B_FALSE, ipst);
25775 		/* Failure case frees things for us. */
25776 		if (ill == NULL)
25777 			return;
25778 
25779 		ill_need_rele = B_TRUE;
25780 	}
25781 
25782 	if (CLASSD(dst)) {
25783 		boolean_t conn_dontroute;
25784 		/*
25785 		 * Use the ill_index to get the right ipif.
25786 		 */
25787 		conn_dontroute = io->ipsec_out_dontroute;
25788 		if (ill_index == 0)
25789 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25790 		else
25791 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25792 		if (ipif == NULL) {
25793 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25794 			    " multicast\n"));
25795 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25796 			freemsg(ipsec_mp);
25797 			goto done;
25798 		}
25799 		/*
25800 		 * ipha_src has already been intialized with the
25801 		 * value of the ipif in ip_wput. All we need now is
25802 		 * an ire to send this downstream.
25803 		 */
25804 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25805 		    msg_getlabel(mp), match_flags, ipst);
25806 		if (ire != NULL) {
25807 			ill_t *ill1;
25808 			/*
25809 			 * Do the multicast forwarding now, as the IPsec
25810 			 * processing has been done.
25811 			 */
25812 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25813 			    (ill1 = ire_to_ill(ire))) {
25814 				if (ip_mforward(ill1, ipha, mp)) {
25815 					freemsg(ipsec_mp);
25816 					ip1dbg(("ip_wput_ipsec_out: mforward "
25817 					    "failed\n"));
25818 					ire_refrele(ire);
25819 					goto done;
25820 				}
25821 			}
25822 			goto send;
25823 		}
25824 
25825 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25826 		mp->b_prev = NULL;
25827 		mp->b_next = NULL;
25828 
25829 		/*
25830 		 * If the IPsec packet was processed asynchronously,
25831 		 * drop it now.
25832 		 */
25833 		if (q == NULL) {
25834 			freemsg(ipsec_mp);
25835 			goto done;
25836 		}
25837 
25838 		/*
25839 		 * We may be using a wrong ipif to create the ire.
25840 		 * But it is okay as the source address is assigned
25841 		 * for the packet already. Next outbound packet would
25842 		 * create the IRE with the right IPIF in ip_wput.
25843 		 *
25844 		 * Also handle RTF_MULTIRT routes.
25845 		 */
25846 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25847 		    zoneid, &zero_info);
25848 	} else {
25849 		if (ire_arg != NULL) {
25850 			ire = ire_arg;
25851 			ire_need_rele = B_FALSE;
25852 		} else {
25853 			ire = ire_cache_lookup(dst, zoneid,
25854 			    msg_getlabel(mp), ipst);
25855 		}
25856 		if (ire != NULL) {
25857 			goto send;
25858 		}
25859 
25860 		/*
25861 		 * ire disappeared underneath.
25862 		 *
25863 		 * What we need to do here is the ip_newroute
25864 		 * logic to get the ire without doing the IPsec
25865 		 * processing. Follow the same old path. But this
25866 		 * time, ip_wput or ire_add_then_put will call us
25867 		 * directly as all the IPsec operations are done.
25868 		 */
25869 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25870 		mp->b_prev = NULL;
25871 		mp->b_next = NULL;
25872 
25873 		/*
25874 		 * If the IPsec packet was processed asynchronously,
25875 		 * drop it now.
25876 		 */
25877 		if (q == NULL) {
25878 			freemsg(ipsec_mp);
25879 			goto done;
25880 		}
25881 
25882 		/*
25883 		 * Since we're going through ip_newroute() again, we
25884 		 * need to make sure we don't:
25885 		 *
25886 		 *	1.) Trigger the ASSERT() with the ipha_ident
25887 		 *	    overloading.
25888 		 *	2.) Redo transport-layer checksumming, since we've
25889 		 *	    already done all that to get this far.
25890 		 *
25891 		 * The easiest way not do either of the above is to set
25892 		 * the ipha_ident field to IP_HDR_INCLUDED.
25893 		 */
25894 		ipha->ipha_ident = IP_HDR_INCLUDED;
25895 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
25896 		    zoneid, ipst);
25897 	}
25898 	goto done;
25899 send:
25900 	if (ire->ire_stq == NULL) {
25901 		ill_t	*out_ill;
25902 		/*
25903 		 * Loopbacks go through ip_wput_local except for one case.
25904 		 * We come here if we generate a icmp_frag_needed message
25905 		 * after IPsec processing is over. When this function calls
25906 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
25907 		 * icmp_frag_needed. The message generated comes back here
25908 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
25909 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
25910 		 * source address as it is usually set in ip_wput_ire. As
25911 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
25912 		 * and we end up here. We can't enter ip_wput_ire once the
25913 		 * IPsec processing is over and hence we need to do it here.
25914 		 */
25915 		ASSERT(q != NULL);
25916 		UPDATE_OB_PKT_COUNT(ire);
25917 		ire->ire_last_used_time = lbolt;
25918 		if (ipha->ipha_src == 0)
25919 			ipha->ipha_src = ire->ire_src_addr;
25920 
25921 		/* PFHooks: LOOPBACK_OUT */
25922 		out_ill = ire_to_ill(ire);
25923 
25924 		/*
25925 		 * DTrace this as ip:::send.  A blocked packet will fire the
25926 		 * send probe, but not the receive probe.
25927 		 */
25928 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25929 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
25930 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
25931 
25932 		DTRACE_PROBE4(ip4__loopback__out__start,
25933 		    ill_t *, NULL, ill_t *, out_ill,
25934 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
25935 
25936 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
25937 		    ipst->ips_ipv4firewall_loopback_out,
25938 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
25939 
25940 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
25941 
25942 		if (ipsec_mp != NULL)
25943 			ip_wput_local(RD(q), out_ill,
25944 			    ipha, ipsec_mp, ire, 0, zoneid);
25945 		if (ire_need_rele)
25946 			ire_refrele(ire);
25947 		goto done;
25948 	}
25949 
25950 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
25951 		/*
25952 		 * We are through with IPsec processing.
25953 		 * Fragment this and send it on the wire.
25954 		 */
25955 		if (io->ipsec_out_accelerated) {
25956 			/*
25957 			 * The packet has been accelerated but must
25958 			 * be fragmented. This should not happen
25959 			 * since AH and ESP must not accelerate
25960 			 * packets that need fragmentation, however
25961 			 * the configuration could have changed
25962 			 * since the AH or ESP processing.
25963 			 * Drop packet.
25964 			 * IPsec KSTATS: bump bean counter here.
25965 			 */
25966 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
25967 			    "fragmented accelerated packet!\n"));
25968 			freemsg(ipsec_mp);
25969 		} else {
25970 			ip_wput_ire_fragmentit(ipsec_mp, ire,
25971 			    zoneid, ipst, NULL);
25972 		}
25973 		if (ire_need_rele)
25974 			ire_refrele(ire);
25975 		goto done;
25976 	}
25977 
25978 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
25979 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
25980 	    (void *)ire->ire_ipif, (void *)ipif));
25981 
25982 	/*
25983 	 * Multiroute the secured packet.
25984 	 */
25985 	if (ire->ire_flags & RTF_MULTIRT) {
25986 		ire_t *first_ire;
25987 		irb = ire->ire_bucket;
25988 		ASSERT(irb != NULL);
25989 		/*
25990 		 * This ire has been looked up as the one that
25991 		 * goes through the given ipif;
25992 		 * make sure we do not omit any other multiroute ire
25993 		 * that may be present in the bucket before this one.
25994 		 */
25995 		IRB_REFHOLD(irb);
25996 		for (first_ire = irb->irb_ire;
25997 		    first_ire != NULL;
25998 		    first_ire = first_ire->ire_next) {
25999 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26000 			    (first_ire->ire_addr == ire->ire_addr) &&
26001 			    !(first_ire->ire_marks &
26002 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
26003 				break;
26004 		}
26005 
26006 		if ((first_ire != NULL) && (first_ire != ire)) {
26007 			/*
26008 			 * Don't change the ire if the packet must
26009 			 * be fragmented if sent via this new one.
26010 			 */
26011 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26012 				IRE_REFHOLD(first_ire);
26013 				if (ire_need_rele)
26014 					ire_refrele(ire);
26015 				else
26016 					ire_need_rele = B_TRUE;
26017 				ire = first_ire;
26018 			}
26019 		}
26020 		IRB_REFRELE(irb);
26021 
26022 		multirt_send = B_TRUE;
26023 		max_frag = ire->ire_max_frag;
26024 	}
26025 
26026 	/*
26027 	 * In most cases, the emission loop below is entered only once.
26028 	 * Only in the case where the ire holds the RTF_MULTIRT
26029 	 * flag, we loop to process all RTF_MULTIRT ires in the
26030 	 * bucket, and send the packet through all crossed
26031 	 * RTF_MULTIRT routes.
26032 	 */
26033 	do {
26034 		if (multirt_send) {
26035 			/*
26036 			 * ire1 holds here the next ire to process in the
26037 			 * bucket. If multirouting is expected,
26038 			 * any non-RTF_MULTIRT ire that has the
26039 			 * right destination address is ignored.
26040 			 */
26041 			ASSERT(irb != NULL);
26042 			IRB_REFHOLD(irb);
26043 			for (ire1 = ire->ire_next;
26044 			    ire1 != NULL;
26045 			    ire1 = ire1->ire_next) {
26046 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26047 					continue;
26048 				if (ire1->ire_addr != ire->ire_addr)
26049 					continue;
26050 				if (ire1->ire_marks &
26051 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
26052 					continue;
26053 				/* No loopback here */
26054 				if (ire1->ire_stq == NULL)
26055 					continue;
26056 				/*
26057 				 * Ensure we do not exceed the MTU
26058 				 * of the next route.
26059 				 */
26060 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26061 					ip_multirt_bad_mtu(ire1, max_frag);
26062 					continue;
26063 				}
26064 
26065 				IRE_REFHOLD(ire1);
26066 				break;
26067 			}
26068 			IRB_REFRELE(irb);
26069 			if (ire1 != NULL) {
26070 				/*
26071 				 * We are in a multiple send case, need to
26072 				 * make a copy of the packet.
26073 				 */
26074 				next_mp = copymsg(ipsec_mp);
26075 				if (next_mp == NULL) {
26076 					ire_refrele(ire1);
26077 					ire1 = NULL;
26078 				}
26079 			}
26080 		}
26081 		/*
26082 		 * Everything is done. Send it out on the wire
26083 		 *
26084 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26085 		 * either send it on the wire or, in the case of
26086 		 * HW acceleration, call ipsec_hw_putnext.
26087 		 */
26088 		if (ire->ire_nce &&
26089 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26090 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26091 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26092 			/*
26093 			 * If ire's link-layer is unresolved (this
26094 			 * would only happen if the incomplete ire
26095 			 * was added to cachetable via forwarding path)
26096 			 * don't bother going to ip_xmit_v4. Just drop the
26097 			 * packet.
26098 			 * There is a slight risk here, in that, if we
26099 			 * have the forwarding path create an incomplete
26100 			 * IRE, then until the IRE is completed, any
26101 			 * transmitted IPsec packets will be dropped
26102 			 * instead of being queued waiting for resolution.
26103 			 *
26104 			 * But the likelihood of a forwarding packet and a wput
26105 			 * packet sending to the same dst at the same time
26106 			 * and there not yet be an ARP entry for it is small.
26107 			 * Furthermore, if this actually happens, it might
26108 			 * be likely that wput would generate multiple
26109 			 * packets (and forwarding would also have a train
26110 			 * of packets) for that destination. If this is
26111 			 * the case, some of them would have been dropped
26112 			 * anyway, since ARP only queues a few packets while
26113 			 * waiting for resolution
26114 			 *
26115 			 * NOTE: We should really call ip_xmit_v4,
26116 			 * and let it queue the packet and send the
26117 			 * ARP query and have ARP come back thus:
26118 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26119 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26120 			 * hw accel work. But it's too complex to get
26121 			 * the IPsec hw  acceleration approach to fit
26122 			 * well with ip_xmit_v4 doing ARP without
26123 			 * doing IPsec simplification. For now, we just
26124 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26125 			 * that we can continue with the send on the next
26126 			 * attempt.
26127 			 *
26128 			 * XXX THis should be revisited, when
26129 			 * the IPsec/IP interaction is cleaned up
26130 			 */
26131 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26132 			    " - dropping packet\n"));
26133 			freemsg(ipsec_mp);
26134 			/*
26135 			 * Call ip_xmit_v4() to trigger ARP query
26136 			 * in case the nce_state is ND_INITIAL
26137 			 */
26138 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
26139 			goto drop_pkt;
26140 		}
26141 
26142 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26143 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26144 		    mblk_t *, ipsec_mp);
26145 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26146 		    ipst->ips_ipv4firewall_physical_out, NULL,
26147 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26148 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26149 		if (ipsec_mp == NULL)
26150 			goto drop_pkt;
26151 
26152 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26153 		pktxmit_state = ip_xmit_v4(mp, ire,
26154 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE, NULL);
26155 
26156 		if ((pktxmit_state ==  SEND_FAILED) ||
26157 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26158 
26159 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26160 drop_pkt:
26161 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26162 			    ipIfStatsOutDiscards);
26163 			if (ire_need_rele)
26164 				ire_refrele(ire);
26165 			if (ire1 != NULL) {
26166 				ire_refrele(ire1);
26167 				freemsg(next_mp);
26168 			}
26169 			goto done;
26170 		}
26171 
26172 		freeb(ipsec_mp);
26173 		if (ire_need_rele)
26174 			ire_refrele(ire);
26175 
26176 		if (ire1 != NULL) {
26177 			ire = ire1;
26178 			ire_need_rele = B_TRUE;
26179 			ASSERT(next_mp);
26180 			ipsec_mp = next_mp;
26181 			mp = ipsec_mp->b_cont;
26182 			ire1 = NULL;
26183 			next_mp = NULL;
26184 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26185 		} else {
26186 			multirt_send = B_FALSE;
26187 		}
26188 	} while (multirt_send);
26189 done:
26190 	if (ill != NULL && ill_need_rele)
26191 		ill_refrele(ill);
26192 	if (ipif != NULL)
26193 		ipif_refrele(ipif);
26194 }
26195 
26196 /*
26197  * Get the ill corresponding to the specified ire, and compare its
26198  * capabilities with the protocol and algorithms specified by the
26199  * the SA obtained from ipsec_out. If they match, annotate the
26200  * ipsec_out structure to indicate that the packet needs acceleration.
26201  *
26202  *
26203  * A packet is eligible for outbound hardware acceleration if the
26204  * following conditions are satisfied:
26205  *
26206  * 1. the packet will not be fragmented
26207  * 2. the provider supports the algorithm
26208  * 3. there is no pending control message being exchanged
26209  * 4. snoop is not attached
26210  * 5. the destination address is not a broadcast or multicast address.
26211  *
26212  * Rationale:
26213  *	- Hardware drivers do not support fragmentation with
26214  *	  the current interface.
26215  *	- snoop, multicast, and broadcast may result in exposure of
26216  *	  a cleartext datagram.
26217  * We check all five of these conditions here.
26218  *
26219  * XXX would like to nuke "ire_t *" parameter here; problem is that
26220  * IRE is only way to figure out if a v4 address is a broadcast and
26221  * thus ineligible for acceleration...
26222  */
26223 static void
26224 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26225 {
26226 	ipsec_out_t *io;
26227 	mblk_t *data_mp;
26228 	uint_t plen, overhead;
26229 	ip_stack_t	*ipst;
26230 
26231 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26232 		return;
26233 
26234 	if (ill == NULL)
26235 		return;
26236 	ipst = ill->ill_ipst;
26237 	/*
26238 	 * Destination address is a broadcast or multicast.  Punt.
26239 	 */
26240 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26241 	    IRE_LOCAL)))
26242 		return;
26243 
26244 	data_mp = ipsec_mp->b_cont;
26245 
26246 	if (ill->ill_isv6) {
26247 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26248 
26249 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26250 			return;
26251 
26252 		plen = ip6h->ip6_plen;
26253 	} else {
26254 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26255 
26256 		if (CLASSD(ipha->ipha_dst))
26257 			return;
26258 
26259 		plen = ipha->ipha_length;
26260 	}
26261 	/*
26262 	 * Is there a pending DLPI control message being exchanged
26263 	 * between IP/IPsec and the DLS Provider? If there is, it
26264 	 * could be a SADB update, and the state of the DLS Provider
26265 	 * SADB might not be in sync with the SADB maintained by
26266 	 * IPsec. To avoid dropping packets or using the wrong keying
26267 	 * material, we do not accelerate this packet.
26268 	 */
26269 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26270 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26271 		    "ill_dlpi_pending! don't accelerate packet\n"));
26272 		return;
26273 	}
26274 
26275 	/*
26276 	 * Is the Provider in promiscous mode? If it does, we don't
26277 	 * accelerate the packet since it will bounce back up to the
26278 	 * listeners in the clear.
26279 	 */
26280 	if (ill->ill_promisc_on_phys) {
26281 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26282 		    "ill in promiscous mode, don't accelerate packet\n"));
26283 		return;
26284 	}
26285 
26286 	/*
26287 	 * Will the packet require fragmentation?
26288 	 */
26289 
26290 	/*
26291 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26292 	 * as is used elsewhere.
26293 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26294 	 *	+ 2-byte trailer
26295 	 */
26296 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26297 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26298 
26299 	if ((plen + overhead) > ill->ill_max_mtu)
26300 		return;
26301 
26302 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26303 
26304 	/*
26305 	 * Can the ill accelerate this IPsec protocol and algorithm
26306 	 * specified by the SA?
26307 	 */
26308 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26309 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26310 		return;
26311 	}
26312 
26313 	/*
26314 	 * Tell AH or ESP that the outbound ill is capable of
26315 	 * accelerating this packet.
26316 	 */
26317 	io->ipsec_out_is_capab_ill = B_TRUE;
26318 }
26319 
26320 /*
26321  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26322  *
26323  * If this function returns B_TRUE, the requested SA's have been filled
26324  * into the ipsec_out_*_sa pointers.
26325  *
26326  * If the function returns B_FALSE, the packet has been "consumed", most
26327  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26328  *
26329  * The SA references created by the protocol-specific "select"
26330  * function will be released when the ipsec_mp is freed, thanks to the
26331  * ipsec_out_free destructor -- see spd.c.
26332  */
26333 static boolean_t
26334 ipsec_out_select_sa(mblk_t *ipsec_mp)
26335 {
26336 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26337 	ipsec_out_t *io;
26338 	ipsec_policy_t *pp;
26339 	ipsec_action_t *ap;
26340 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26341 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26342 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26343 
26344 	if (!io->ipsec_out_secure) {
26345 		/*
26346 		 * We came here by mistake.
26347 		 * Don't bother with ipsec processing
26348 		 * We should "discourage" this path in the future.
26349 		 */
26350 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26351 		return (B_FALSE);
26352 	}
26353 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26354 	ASSERT((io->ipsec_out_policy != NULL) ||
26355 	    (io->ipsec_out_act != NULL));
26356 
26357 	ASSERT(io->ipsec_out_failed == B_FALSE);
26358 
26359 	/*
26360 	 * IPsec processing has started.
26361 	 */
26362 	io->ipsec_out_proc_begin = B_TRUE;
26363 	ap = io->ipsec_out_act;
26364 	if (ap == NULL) {
26365 		pp = io->ipsec_out_policy;
26366 		ASSERT(pp != NULL);
26367 		ap = pp->ipsp_act;
26368 		ASSERT(ap != NULL);
26369 	}
26370 
26371 	/*
26372 	 * We have an action.  now, let's select SA's.
26373 	 * (In the future, we can cache this in the conn_t..)
26374 	 */
26375 	if (ap->ipa_want_esp) {
26376 		if (io->ipsec_out_esp_sa == NULL) {
26377 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26378 			    IPPROTO_ESP);
26379 		}
26380 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26381 	}
26382 
26383 	if (ap->ipa_want_ah) {
26384 		if (io->ipsec_out_ah_sa == NULL) {
26385 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26386 			    IPPROTO_AH);
26387 		}
26388 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26389 		/*
26390 		 * The ESP and AH processing order needs to be preserved
26391 		 * when both protocols are required (ESP should be applied
26392 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26393 		 * when both ESP and AH are required, and an AH ACQUIRE
26394 		 * is needed.
26395 		 */
26396 		if (ap->ipa_want_esp && need_ah_acquire)
26397 			need_esp_acquire = B_TRUE;
26398 	}
26399 
26400 	/*
26401 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26402 	 * Release SAs that got referenced, but will not be used until we
26403 	 * acquire _all_ of the SAs we need.
26404 	 */
26405 	if (need_ah_acquire || need_esp_acquire) {
26406 		if (io->ipsec_out_ah_sa != NULL) {
26407 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26408 			io->ipsec_out_ah_sa = NULL;
26409 		}
26410 		if (io->ipsec_out_esp_sa != NULL) {
26411 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26412 			io->ipsec_out_esp_sa = NULL;
26413 		}
26414 
26415 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26416 		return (B_FALSE);
26417 	}
26418 
26419 	return (B_TRUE);
26420 }
26421 
26422 /*
26423  * Process an IPSEC_OUT message and see what you can
26424  * do with it.
26425  * IPQoS Notes:
26426  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26427  * IPsec.
26428  * XXX would like to nuke ire_t.
26429  * XXX ill_index better be "real"
26430  */
26431 void
26432 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26433 {
26434 	ipsec_out_t *io;
26435 	ipsec_policy_t *pp;
26436 	ipsec_action_t *ap;
26437 	ipha_t *ipha;
26438 	ip6_t *ip6h;
26439 	mblk_t *mp;
26440 	ill_t *ill;
26441 	zoneid_t zoneid;
26442 	ipsec_status_t ipsec_rc;
26443 	boolean_t ill_need_rele = B_FALSE;
26444 	ip_stack_t	*ipst;
26445 	ipsec_stack_t	*ipss;
26446 
26447 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26448 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26449 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26450 	ipst = io->ipsec_out_ns->netstack_ip;
26451 	mp = ipsec_mp->b_cont;
26452 
26453 	/*
26454 	 * Initiate IPPF processing. We do it here to account for packets
26455 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26456 	 * We can check for ipsec_out_proc_begin even for such packets, as
26457 	 * they will always be false (asserted below).
26458 	 */
26459 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26460 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26461 		    io->ipsec_out_ill_index : ill_index);
26462 		if (mp == NULL) {
26463 			ip2dbg(("ipsec_out_process: packet dropped "\
26464 			    "during IPPF processing\n"));
26465 			freeb(ipsec_mp);
26466 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26467 			return;
26468 		}
26469 	}
26470 
26471 	if (!io->ipsec_out_secure) {
26472 		/*
26473 		 * We came here by mistake.
26474 		 * Don't bother with ipsec processing
26475 		 * Should "discourage" this path in the future.
26476 		 */
26477 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26478 		goto done;
26479 	}
26480 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26481 	ASSERT((io->ipsec_out_policy != NULL) ||
26482 	    (io->ipsec_out_act != NULL));
26483 	ASSERT(io->ipsec_out_failed == B_FALSE);
26484 
26485 	ipss = ipst->ips_netstack->netstack_ipsec;
26486 	if (!ipsec_loaded(ipss)) {
26487 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26488 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26489 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26490 		} else {
26491 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26492 		}
26493 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26494 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26495 		    &ipss->ipsec_dropper);
26496 		return;
26497 	}
26498 
26499 	/*
26500 	 * IPsec processing has started.
26501 	 */
26502 	io->ipsec_out_proc_begin = B_TRUE;
26503 	ap = io->ipsec_out_act;
26504 	if (ap == NULL) {
26505 		pp = io->ipsec_out_policy;
26506 		ASSERT(pp != NULL);
26507 		ap = pp->ipsp_act;
26508 		ASSERT(ap != NULL);
26509 	}
26510 
26511 	/*
26512 	 * Save the outbound ill index. When the packet comes back
26513 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26514 	 * before sending it the accelerated packet.
26515 	 */
26516 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26517 		ill = ire_to_ill(ire);
26518 		io->ipsec_out_capab_ill_index = ill->ill_phyint->phyint_ifindex;
26519 	}
26520 
26521 	/*
26522 	 * The order of processing is first insert a IP header if needed.
26523 	 * Then insert the ESP header and then the AH header.
26524 	 */
26525 	if ((io->ipsec_out_se_done == B_FALSE) &&
26526 	    (ap->ipa_want_se)) {
26527 		/*
26528 		 * First get the outer IP header before sending
26529 		 * it to ESP.
26530 		 */
26531 		ipha_t *oipha, *iipha;
26532 		mblk_t *outer_mp, *inner_mp;
26533 
26534 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26535 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26536 			    "ipsec_out_process: "
26537 			    "Self-Encapsulation failed: Out of memory\n");
26538 			freemsg(ipsec_mp);
26539 			if (ill != NULL) {
26540 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26541 			} else {
26542 				BUMP_MIB(&ipst->ips_ip_mib,
26543 				    ipIfStatsOutDiscards);
26544 			}
26545 			return;
26546 		}
26547 		inner_mp = ipsec_mp->b_cont;
26548 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26549 		oipha = (ipha_t *)outer_mp->b_rptr;
26550 		iipha = (ipha_t *)inner_mp->b_rptr;
26551 		*oipha = *iipha;
26552 		outer_mp->b_wptr += sizeof (ipha_t);
26553 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26554 		    sizeof (ipha_t));
26555 		oipha->ipha_protocol = IPPROTO_ENCAP;
26556 		oipha->ipha_version_and_hdr_length =
26557 		    IP_SIMPLE_HDR_VERSION;
26558 		oipha->ipha_hdr_checksum = 0;
26559 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26560 		outer_mp->b_cont = inner_mp;
26561 		ipsec_mp->b_cont = outer_mp;
26562 
26563 		io->ipsec_out_se_done = B_TRUE;
26564 		io->ipsec_out_tunnel = B_TRUE;
26565 	}
26566 
26567 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26568 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26569 	    !ipsec_out_select_sa(ipsec_mp))
26570 		return;
26571 
26572 	/*
26573 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26574 	 * to do the heavy lifting.
26575 	 */
26576 	zoneid = io->ipsec_out_zoneid;
26577 	ASSERT(zoneid != ALL_ZONES);
26578 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26579 		ASSERT(io->ipsec_out_esp_sa != NULL);
26580 		io->ipsec_out_esp_done = B_TRUE;
26581 		/*
26582 		 * Note that since hw accel can only apply one transform,
26583 		 * not two, we skip hw accel for ESP if we also have AH
26584 		 * This is an design limitation of the interface
26585 		 * which should be revisited.
26586 		 */
26587 		ASSERT(ire != NULL);
26588 		if (io->ipsec_out_ah_sa == NULL) {
26589 			ill = (ill_t *)ire->ire_stq->q_ptr;
26590 			ipsec_out_is_accelerated(ipsec_mp,
26591 			    io->ipsec_out_esp_sa, ill, ire);
26592 		}
26593 
26594 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26595 		switch (ipsec_rc) {
26596 		case IPSEC_STATUS_SUCCESS:
26597 			break;
26598 		case IPSEC_STATUS_FAILED:
26599 			if (ill != NULL) {
26600 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26601 			} else {
26602 				BUMP_MIB(&ipst->ips_ip_mib,
26603 				    ipIfStatsOutDiscards);
26604 			}
26605 			/* FALLTHRU */
26606 		case IPSEC_STATUS_PENDING:
26607 			return;
26608 		}
26609 	}
26610 
26611 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26612 		ASSERT(io->ipsec_out_ah_sa != NULL);
26613 		io->ipsec_out_ah_done = B_TRUE;
26614 		if (ire == NULL) {
26615 			int idx = io->ipsec_out_capab_ill_index;
26616 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26617 			    NULL, NULL, NULL, NULL, ipst);
26618 			ill_need_rele = B_TRUE;
26619 		} else {
26620 			ill = (ill_t *)ire->ire_stq->q_ptr;
26621 		}
26622 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26623 		    ire);
26624 
26625 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26626 		switch (ipsec_rc) {
26627 		case IPSEC_STATUS_SUCCESS:
26628 			break;
26629 		case IPSEC_STATUS_FAILED:
26630 			if (ill != NULL) {
26631 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26632 			} else {
26633 				BUMP_MIB(&ipst->ips_ip_mib,
26634 				    ipIfStatsOutDiscards);
26635 			}
26636 			/* FALLTHRU */
26637 		case IPSEC_STATUS_PENDING:
26638 			if (ill != NULL && ill_need_rele)
26639 				ill_refrele(ill);
26640 			return;
26641 		}
26642 	}
26643 	/*
26644 	 * We are done with IPsec processing. Send it over the wire.
26645 	 */
26646 done:
26647 	mp = ipsec_mp->b_cont;
26648 	ipha = (ipha_t *)mp->b_rptr;
26649 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26650 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ire->ire_ipif->ipif_ill,
26651 		    ire);
26652 	} else {
26653 		ip6h = (ip6_t *)ipha;
26654 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ire->ire_ipif->ipif_ill,
26655 		    ire);
26656 	}
26657 	if (ill != NULL && ill_need_rele)
26658 		ill_refrele(ill);
26659 }
26660 
26661 /* ARGSUSED */
26662 void
26663 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26664 {
26665 	opt_restart_t	*or;
26666 	int	err;
26667 	conn_t	*connp;
26668 	cred_t	*cr;
26669 
26670 	ASSERT(CONN_Q(q));
26671 	connp = Q_TO_CONN(q);
26672 
26673 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26674 	or = (opt_restart_t *)first_mp->b_rptr;
26675 	/*
26676 	 * We checked for a db_credp the first time svr4_optcom_req
26677 	 * was called (from ip_wput_nondata). So we can just ASSERT here.
26678 	 */
26679 	cr = msg_getcred(first_mp, NULL);
26680 	ASSERT(cr != NULL);
26681 
26682 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26683 		err = svr4_optcom_req(q, first_mp, cr,
26684 		    &ip_opt_obj, B_FALSE);
26685 	} else {
26686 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26687 		err = tpi_optcom_req(q, first_mp, cr,
26688 		    &ip_opt_obj, B_FALSE);
26689 	}
26690 	if (err != EINPROGRESS) {
26691 		/* operation is done */
26692 		CONN_OPER_PENDING_DONE(connp);
26693 	}
26694 }
26695 
26696 /*
26697  * ioctls that go through a down/up sequence may need to wait for the down
26698  * to complete. This involves waiting for the ire and ipif refcnts to go down
26699  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26700  */
26701 /* ARGSUSED */
26702 void
26703 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26704 {
26705 	struct iocblk *iocp;
26706 	mblk_t *mp1;
26707 	ip_ioctl_cmd_t *ipip;
26708 	int err;
26709 	sin_t	*sin;
26710 	struct lifreq *lifr;
26711 	struct ifreq *ifr;
26712 
26713 	iocp = (struct iocblk *)mp->b_rptr;
26714 	ASSERT(ipsq != NULL);
26715 	/* Existence of mp1 verified in ip_wput_nondata */
26716 	mp1 = mp->b_cont->b_cont;
26717 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26718 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26719 		/*
26720 		 * Special case where ipx_current_ipif is not set:
26721 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26722 		 * We are here as were not able to complete the operation in
26723 		 * ipif_set_values because we could not become exclusive on
26724 		 * the new ipsq.
26725 		 */
26726 		ill_t *ill = q->q_ptr;
26727 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26728 	}
26729 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
26730 
26731 	if (ipip->ipi_cmd_type == IF_CMD) {
26732 		/* This a old style SIOC[GS]IF* command */
26733 		ifr = (struct ifreq *)mp1->b_rptr;
26734 		sin = (sin_t *)&ifr->ifr_addr;
26735 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26736 		/* This a new style SIOC[GS]LIF* command */
26737 		lifr = (struct lifreq *)mp1->b_rptr;
26738 		sin = (sin_t *)&lifr->lifr_addr;
26739 	} else {
26740 		sin = NULL;
26741 	}
26742 
26743 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
26744 	    q, mp, ipip, mp1->b_rptr);
26745 
26746 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26747 }
26748 
26749 /*
26750  * ioctl processing
26751  *
26752  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26753  * the ioctl command in the ioctl tables, determines the copyin data size
26754  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26755  *
26756  * ioctl processing then continues when the M_IOCDATA makes its way down to
26757  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26758  * associated 'conn' is refheld till the end of the ioctl and the general
26759  * ioctl processing function ip_process_ioctl() is called to extract the
26760  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26761  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26762  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26763  * is used to extract the ioctl's arguments.
26764  *
26765  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26766  * so goes thru the serialization primitive ipsq_try_enter. Then the
26767  * appropriate function to handle the ioctl is called based on the entry in
26768  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26769  * which also refreleases the 'conn' that was refheld at the start of the
26770  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26771  *
26772  * Many exclusive ioctls go thru an internal down up sequence as part of
26773  * the operation. For example an attempt to change the IP address of an
26774  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26775  * does all the cleanup such as deleting all ires that use this address.
26776  * Then we need to wait till all references to the interface go away.
26777  */
26778 void
26779 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26780 {
26781 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26782 	ip_ioctl_cmd_t *ipip = arg;
26783 	ip_extract_func_t *extract_funcp;
26784 	cmd_info_t ci;
26785 	int err;
26786 	boolean_t entered_ipsq = B_FALSE;
26787 
26788 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26789 
26790 	if (ipip == NULL)
26791 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26792 
26793 	/*
26794 	 * SIOCLIFADDIF needs to go thru a special path since the
26795 	 * ill may not exist yet. This happens in the case of lo0
26796 	 * which is created using this ioctl.
26797 	 */
26798 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26799 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26800 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26801 		return;
26802 	}
26803 
26804 	ci.ci_ipif = NULL;
26805 	if (ipip->ipi_cmd_type == MISC_CMD) {
26806 		/*
26807 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26808 		 */
26809 		if (ipip->ipi_cmd == IF_UNITSEL) {
26810 			/* ioctl comes down the ill */
26811 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26812 			ipif_refhold(ci.ci_ipif);
26813 		}
26814 		err = 0;
26815 		ci.ci_sin = NULL;
26816 		ci.ci_sin6 = NULL;
26817 		ci.ci_lifr = NULL;
26818 	} else {
26819 		switch (ipip->ipi_cmd_type) {
26820 		case IF_CMD:
26821 		case LIF_CMD:
26822 			extract_funcp = ip_extract_lifreq;
26823 			break;
26824 
26825 		case ARP_CMD:
26826 		case XARP_CMD:
26827 			extract_funcp = ip_extract_arpreq;
26828 			break;
26829 
26830 		case TUN_CMD:
26831 			extract_funcp = ip_extract_tunreq;
26832 			break;
26833 
26834 		case MSFILT_CMD:
26835 			extract_funcp = ip_extract_msfilter;
26836 			break;
26837 
26838 		default:
26839 			ASSERT(0);
26840 		}
26841 
26842 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
26843 		if (err != 0) {
26844 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26845 			return;
26846 		}
26847 
26848 		/*
26849 		 * All of the extraction functions return a refheld ipif.
26850 		 */
26851 		ASSERT(ci.ci_ipif != NULL);
26852 	}
26853 
26854 	if (!(ipip->ipi_flags & IPI_WR)) {
26855 		/*
26856 		 * A return value of EINPROGRESS means the ioctl is
26857 		 * either queued and waiting for some reason or has
26858 		 * already completed.
26859 		 */
26860 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26861 		    ci.ci_lifr);
26862 		if (ci.ci_ipif != NULL)
26863 			ipif_refrele(ci.ci_ipif);
26864 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26865 		return;
26866 	}
26867 
26868 	ASSERT(ci.ci_ipif != NULL);
26869 
26870 	/*
26871 	 * If ipsq is non-NULL, we are already being called exclusively.
26872 	 */
26873 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26874 	if (ipsq == NULL) {
26875 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
26876 		    NEW_OP, B_TRUE);
26877 		if (ipsq == NULL) {
26878 			ipif_refrele(ci.ci_ipif);
26879 			return;
26880 		}
26881 		entered_ipsq = B_TRUE;
26882 	}
26883 
26884 	/*
26885 	 * Release the ipif so that ipif_down and friends that wait for
26886 	 * references to go away are not misled about the current ipif_refcnt
26887 	 * values. We are writer so we can access the ipif even after releasing
26888 	 * the ipif.
26889 	 */
26890 	ipif_refrele(ci.ci_ipif);
26891 
26892 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
26893 
26894 	/*
26895 	 * For most set ioctls that come here, this serves as a single point
26896 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
26897 	 * be any new references to the ipif. This helps functions that go
26898 	 * through this path and end up trying to wait for the refcnts
26899 	 * associated with the ipif to go down to zero.  The exception is
26900 	 * SIOCSLIFREMOVEIF, which sets IPIF_CONDEMNED internally after
26901 	 * identifying the right ipif to operate on.
26902 	 */
26903 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
26904 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF)
26905 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
26906 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
26907 
26908 	/*
26909 	 * A return value of EINPROGRESS means the ioctl is
26910 	 * either queued and waiting for some reason or has
26911 	 * already completed.
26912 	 */
26913 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
26914 
26915 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26916 
26917 	if (entered_ipsq)
26918 		ipsq_exit(ipsq);
26919 }
26920 
26921 /*
26922  * Complete the ioctl. Typically ioctls use the mi package and need to
26923  * do mi_copyout/mi_copy_done.
26924  */
26925 void
26926 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
26927 {
26928 	conn_t	*connp = NULL;
26929 
26930 	if (err == EINPROGRESS)
26931 		return;
26932 
26933 	if (CONN_Q(q)) {
26934 		connp = Q_TO_CONN(q);
26935 		ASSERT(connp->conn_ref >= 2);
26936 	}
26937 
26938 	switch (mode) {
26939 	case COPYOUT:
26940 		if (err == 0)
26941 			mi_copyout(q, mp);
26942 		else
26943 			mi_copy_done(q, mp, err);
26944 		break;
26945 
26946 	case NO_COPYOUT:
26947 		mi_copy_done(q, mp, err);
26948 		break;
26949 
26950 	default:
26951 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
26952 		break;
26953 	}
26954 
26955 	/*
26956 	 * The refhold placed at the start of the ioctl is released here.
26957 	 */
26958 	if (connp != NULL)
26959 		CONN_OPER_PENDING_DONE(connp);
26960 
26961 	if (ipsq != NULL)
26962 		ipsq_current_finish(ipsq);
26963 }
26964 
26965 /* Called from ip_wput for all non data messages */
26966 /* ARGSUSED */
26967 void
26968 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26969 {
26970 	mblk_t		*mp1;
26971 	ire_t		*ire, *fake_ire;
26972 	ill_t		*ill;
26973 	struct iocblk	*iocp;
26974 	ip_ioctl_cmd_t	*ipip;
26975 	cred_t		*cr;
26976 	conn_t		*connp;
26977 	int		err;
26978 	nce_t		*nce;
26979 	ipif_t		*ipif;
26980 	ip_stack_t	*ipst;
26981 	char		*proto_str;
26982 
26983 	if (CONN_Q(q)) {
26984 		connp = Q_TO_CONN(q);
26985 		ipst = connp->conn_netstack->netstack_ip;
26986 	} else {
26987 		connp = NULL;
26988 		ipst = ILLQ_TO_IPST(q);
26989 	}
26990 
26991 	switch (DB_TYPE(mp)) {
26992 	case M_IOCTL:
26993 		/*
26994 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
26995 		 * will arrange to copy in associated control structures.
26996 		 */
26997 		ip_sioctl_copyin_setup(q, mp);
26998 		return;
26999 	case M_IOCDATA:
27000 		/*
27001 		 * Ensure that this is associated with one of our trans-
27002 		 * parent ioctls.  If it's not ours, discard it if we're
27003 		 * running as a driver, or pass it on if we're a module.
27004 		 */
27005 		iocp = (struct iocblk *)mp->b_rptr;
27006 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27007 		if (ipip == NULL) {
27008 			if (q->q_next == NULL) {
27009 				goto nak;
27010 			} else {
27011 				putnext(q, mp);
27012 			}
27013 			return;
27014 		}
27015 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27016 			/*
27017 			 * the ioctl is one we recognise, but is not
27018 			 * consumed by IP as a module, pass M_IOCDATA
27019 			 * for processing downstream, but only for
27020 			 * common Streams ioctls.
27021 			 */
27022 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27023 				putnext(q, mp);
27024 				return;
27025 			} else {
27026 				goto nak;
27027 			}
27028 		}
27029 
27030 		/* IOCTL continuation following copyin or copyout. */
27031 		if (mi_copy_state(q, mp, NULL) == -1) {
27032 			/*
27033 			 * The copy operation failed.  mi_copy_state already
27034 			 * cleaned up, so we're out of here.
27035 			 */
27036 			return;
27037 		}
27038 		/*
27039 		 * If we just completed a copy in, we become writer and
27040 		 * continue processing in ip_sioctl_copyin_done.  If it
27041 		 * was a copy out, we call mi_copyout again.  If there is
27042 		 * nothing more to copy out, it will complete the IOCTL.
27043 		 */
27044 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27045 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27046 				mi_copy_done(q, mp, EPROTO);
27047 				return;
27048 			}
27049 			/*
27050 			 * Check for cases that need more copying.  A return
27051 			 * value of 0 means a second copyin has been started,
27052 			 * so we return; a return value of 1 means no more
27053 			 * copying is needed, so we continue.
27054 			 */
27055 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27056 			    MI_COPY_COUNT(mp) == 1) {
27057 				if (ip_copyin_msfilter(q, mp) == 0)
27058 					return;
27059 			}
27060 			/*
27061 			 * Refhold the conn, till the ioctl completes. This is
27062 			 * needed in case the ioctl ends up in the pending mp
27063 			 * list. Every mp in the ill_pending_mp list and
27064 			 * the ipx_pending_mp must have a refhold on the conn
27065 			 * to resume processing. The refhold is released when
27066 			 * the ioctl completes. (normally or abnormally)
27067 			 * In all cases ip_ioctl_finish is called to finish
27068 			 * the ioctl.
27069 			 */
27070 			if (connp != NULL) {
27071 				/* This is not a reentry */
27072 				ASSERT(ipsq == NULL);
27073 				CONN_INC_REF(connp);
27074 			} else {
27075 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27076 					mi_copy_done(q, mp, EINVAL);
27077 					return;
27078 				}
27079 			}
27080 
27081 			ip_process_ioctl(ipsq, q, mp, ipip);
27082 
27083 		} else {
27084 			mi_copyout(q, mp);
27085 		}
27086 		return;
27087 nak:
27088 		iocp->ioc_error = EINVAL;
27089 		mp->b_datap->db_type = M_IOCNAK;
27090 		iocp->ioc_count = 0;
27091 		qreply(q, mp);
27092 		return;
27093 
27094 	case M_IOCNAK:
27095 		/*
27096 		 * The only way we could get here is if a resolver didn't like
27097 		 * an IOCTL we sent it.	 This shouldn't happen.
27098 		 */
27099 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27100 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27101 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27102 		freemsg(mp);
27103 		return;
27104 	case M_IOCACK:
27105 		/* /dev/ip shouldn't see this */
27106 		if (CONN_Q(q))
27107 			goto nak;
27108 
27109 		/*
27110 		 * Finish socket ioctls passed through to ARP.  We use the
27111 		 * ioc_cmd values we set in ip_sioctl_arp() to decide whether
27112 		 * we need to become writer before calling ip_sioctl_iocack().
27113 		 * Note that qwriter_ip() will release the refhold, and that a
27114 		 * refhold is OK without ILL_CAN_LOOKUP() since we're on the
27115 		 * ill stream.
27116 		 */
27117 		iocp = (struct iocblk *)mp->b_rptr;
27118 		if (iocp->ioc_cmd == AR_ENTRY_SQUERY) {
27119 			ip_sioctl_iocack(NULL, q, mp, NULL);
27120 			return;
27121 		}
27122 
27123 		ASSERT(iocp->ioc_cmd == AR_ENTRY_DELETE ||
27124 		    iocp->ioc_cmd == AR_ENTRY_ADD);
27125 		ill = q->q_ptr;
27126 		ill_refhold(ill);
27127 		qwriter_ip(ill, q, mp, ip_sioctl_iocack, CUR_OP, B_FALSE);
27128 		return;
27129 	case M_FLUSH:
27130 		if (*mp->b_rptr & FLUSHW)
27131 			flushq(q, FLUSHALL);
27132 		if (q->q_next) {
27133 			putnext(q, mp);
27134 			return;
27135 		}
27136 		if (*mp->b_rptr & FLUSHR) {
27137 			*mp->b_rptr &= ~FLUSHW;
27138 			qreply(q, mp);
27139 			return;
27140 		}
27141 		freemsg(mp);
27142 		return;
27143 	case IRE_DB_REQ_TYPE:
27144 		if (connp == NULL) {
27145 			proto_str = "IRE_DB_REQ_TYPE";
27146 			goto protonak;
27147 		}
27148 		/* An Upper Level Protocol wants a copy of an IRE. */
27149 		ip_ire_req(q, mp);
27150 		return;
27151 	case M_CTL:
27152 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27153 			break;
27154 
27155 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27156 		    TUN_HELLO) {
27157 			ASSERT(connp != NULL);
27158 			connp->conn_flags |= IPCL_IPTUN;
27159 			freeb(mp);
27160 			return;
27161 		}
27162 
27163 		/* M_CTL messages are used by ARP to tell us things. */
27164 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27165 			break;
27166 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27167 		case AR_ENTRY_SQUERY:
27168 			ip_wput_ctl(q, mp);
27169 			return;
27170 		case AR_CLIENT_NOTIFY:
27171 			ip_arp_news(q, mp);
27172 			return;
27173 		case AR_DLPIOP_DONE:
27174 			ASSERT(q->q_next != NULL);
27175 			ill = (ill_t *)q->q_ptr;
27176 			/* qwriter_ip releases the refhold */
27177 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27178 			ill_refhold(ill);
27179 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27180 			return;
27181 		case AR_ARP_CLOSING:
27182 			/*
27183 			 * ARP (above us) is closing. If no ARP bringup is
27184 			 * currently pending, ack the message so that ARP
27185 			 * can complete its close. Also mark ill_arp_closing
27186 			 * so that new ARP bringups will fail. If any
27187 			 * ARP bringup is currently in progress, we will
27188 			 * ack this when the current ARP bringup completes.
27189 			 */
27190 			ASSERT(q->q_next != NULL);
27191 			ill = (ill_t *)q->q_ptr;
27192 			mutex_enter(&ill->ill_lock);
27193 			ill->ill_arp_closing = 1;
27194 			if (!ill->ill_arp_bringup_pending) {
27195 				mutex_exit(&ill->ill_lock);
27196 				qreply(q, mp);
27197 			} else {
27198 				mutex_exit(&ill->ill_lock);
27199 				freemsg(mp);
27200 			}
27201 			return;
27202 		case AR_ARP_EXTEND:
27203 			/*
27204 			 * The ARP module above us is capable of duplicate
27205 			 * address detection.  Old ATM drivers will not send
27206 			 * this message.
27207 			 */
27208 			ASSERT(q->q_next != NULL);
27209 			ill = (ill_t *)q->q_ptr;
27210 			ill->ill_arp_extend = B_TRUE;
27211 			freemsg(mp);
27212 			return;
27213 		default:
27214 			break;
27215 		}
27216 		break;
27217 	case M_PROTO:
27218 	case M_PCPROTO:
27219 		/*
27220 		 * The only PROTO messages we expect are copies of option
27221 		 * negotiation acknowledgements, AH and ESP bind requests
27222 		 * are also expected.
27223 		 */
27224 		switch (((union T_primitives *)mp->b_rptr)->type) {
27225 		case O_T_BIND_REQ:
27226 		case T_BIND_REQ: {
27227 			/* Request can get queued in bind */
27228 			if (connp == NULL) {
27229 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27230 				goto protonak;
27231 			}
27232 			/*
27233 			 * The transports except SCTP call ip_bind_{v4,v6}()
27234 			 * directly instead of a a putnext. SCTP doesn't
27235 			 * generate any T_BIND_REQ since it has its own
27236 			 * fanout data structures. However, ESP and AH
27237 			 * come in for regular binds; all other cases are
27238 			 * bind retries.
27239 			 */
27240 			ASSERT(!IPCL_IS_SCTP(connp));
27241 
27242 			/* Don't increment refcnt if this is a re-entry */
27243 			if (ipsq == NULL)
27244 				CONN_INC_REF(connp);
27245 
27246 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27247 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27248 			ASSERT(mp != NULL);
27249 
27250 			ASSERT(!IPCL_IS_TCP(connp));
27251 			ASSERT(!IPCL_IS_UDP(connp));
27252 			ASSERT(!IPCL_IS_RAWIP(connp));
27253 
27254 			/* The case of AH and ESP */
27255 			qreply(q, mp);
27256 			CONN_OPER_PENDING_DONE(connp);
27257 			return;
27258 		}
27259 		case T_SVR4_OPTMGMT_REQ:
27260 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27261 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27262 
27263 			if (connp == NULL) {
27264 				proto_str = "T_SVR4_OPTMGMT_REQ";
27265 				goto protonak;
27266 			}
27267 
27268 			/*
27269 			 * All Solaris components should pass a db_credp
27270 			 * for this TPI message, hence we ASSERT.
27271 			 * But in case there is some other M_PROTO that looks
27272 			 * like a TPI message sent by some other kernel
27273 			 * component, we check and return an error.
27274 			 */
27275 			cr = msg_getcred(mp, NULL);
27276 			ASSERT(cr != NULL);
27277 			if (cr == NULL) {
27278 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27279 				if (mp != NULL)
27280 					qreply(q, mp);
27281 				return;
27282 			}
27283 
27284 			if (!snmpcom_req(q, mp, ip_snmp_set,
27285 			    ip_snmp_get, cr)) {
27286 				/*
27287 				 * Call svr4_optcom_req so that it can
27288 				 * generate the ack. We don't come here
27289 				 * if this operation is being restarted.
27290 				 * ip_restart_optmgmt will drop the conn ref.
27291 				 * In the case of ipsec option after the ipsec
27292 				 * load is complete conn_restart_ipsec_waiter
27293 				 * drops the conn ref.
27294 				 */
27295 				ASSERT(ipsq == NULL);
27296 				CONN_INC_REF(connp);
27297 				if (ip_check_for_ipsec_opt(q, mp))
27298 					return;
27299 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27300 				    B_FALSE);
27301 				if (err != EINPROGRESS) {
27302 					/* Operation is done */
27303 					CONN_OPER_PENDING_DONE(connp);
27304 				}
27305 			}
27306 			return;
27307 		case T_OPTMGMT_REQ:
27308 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27309 			/*
27310 			 * Note: No snmpcom_req support through new
27311 			 * T_OPTMGMT_REQ.
27312 			 * Call tpi_optcom_req so that it can
27313 			 * generate the ack.
27314 			 */
27315 			if (connp == NULL) {
27316 				proto_str = "T_OPTMGMT_REQ";
27317 				goto protonak;
27318 			}
27319 
27320 			/*
27321 			 * All Solaris components should pass a db_credp
27322 			 * for this TPI message, hence we ASSERT.
27323 			 * But in case there is some other M_PROTO that looks
27324 			 * like a TPI message sent by some other kernel
27325 			 * component, we check and return an error.
27326 			 */
27327 			cr = msg_getcred(mp, NULL);
27328 			ASSERT(cr != NULL);
27329 			if (cr == NULL) {
27330 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27331 				if (mp != NULL)
27332 					qreply(q, mp);
27333 				return;
27334 			}
27335 			ASSERT(ipsq == NULL);
27336 			/*
27337 			 * We don't come here for restart. ip_restart_optmgmt
27338 			 * will drop the conn ref. In the case of ipsec option
27339 			 * after the ipsec load is complete
27340 			 * conn_restart_ipsec_waiter drops the conn ref.
27341 			 */
27342 			CONN_INC_REF(connp);
27343 			if (ip_check_for_ipsec_opt(q, mp))
27344 				return;
27345 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27346 			if (err != EINPROGRESS) {
27347 				/* Operation is done */
27348 				CONN_OPER_PENDING_DONE(connp);
27349 			}
27350 			return;
27351 		case T_UNBIND_REQ:
27352 			if (connp == NULL) {
27353 				proto_str = "T_UNBIND_REQ";
27354 				goto protonak;
27355 			}
27356 			ip_unbind(Q_TO_CONN(q));
27357 			mp = mi_tpi_ok_ack_alloc(mp);
27358 			qreply(q, mp);
27359 			return;
27360 		default:
27361 			/*
27362 			 * Have to drop any DLPI messages coming down from
27363 			 * arp (such as an info_req which would cause ip
27364 			 * to receive an extra info_ack if it was passed
27365 			 * through.
27366 			 */
27367 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27368 			    (int)*(uint_t *)mp->b_rptr));
27369 			freemsg(mp);
27370 			return;
27371 		}
27372 		/* NOTREACHED */
27373 	case IRE_DB_TYPE: {
27374 		nce_t		*nce;
27375 		ill_t		*ill;
27376 		in6_addr_t	gw_addr_v6;
27377 
27378 		/*
27379 		 * This is a response back from a resolver.  It
27380 		 * consists of a message chain containing:
27381 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27382 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27383 		 * The LL_HDR_MBLK is the DLPI header to use to get
27384 		 * the attached packet, and subsequent ones for the
27385 		 * same destination, transmitted.
27386 		 */
27387 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27388 			break;
27389 		/*
27390 		 * First, check to make sure the resolution succeeded.
27391 		 * If it failed, the second mblk will be empty.
27392 		 * If it is, free the chain, dropping the packet.
27393 		 * (We must ire_delete the ire; that frees the ire mblk)
27394 		 * We're doing this now to support PVCs for ATM; it's
27395 		 * a partial xresolv implementation. When we fully implement
27396 		 * xresolv interfaces, instead of freeing everything here
27397 		 * we'll initiate neighbor discovery.
27398 		 *
27399 		 * For v4 (ARP and other external resolvers) the resolver
27400 		 * frees the message, so no check is needed. This check
27401 		 * is required, though, for a full xresolve implementation.
27402 		 * Including this code here now both shows how external
27403 		 * resolvers can NACK a resolution request using an
27404 		 * existing design that has no specific provisions for NACKs,
27405 		 * and also takes into account that the current non-ARP
27406 		 * external resolver has been coded to use this method of
27407 		 * NACKing for all IPv6 (xresolv) cases,
27408 		 * whether our xresolv implementation is complete or not.
27409 		 *
27410 		 */
27411 		ire = (ire_t *)mp->b_rptr;
27412 		ill = ire_to_ill(ire);
27413 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27414 		if (mp1->b_rptr == mp1->b_wptr) {
27415 			if (ire->ire_ipversion == IPV6_VERSION) {
27416 				/*
27417 				 * XRESOLV interface.
27418 				 */
27419 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27420 				mutex_enter(&ire->ire_lock);
27421 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27422 				mutex_exit(&ire->ire_lock);
27423 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27424 					nce = ndp_lookup_v6(ill, B_FALSE,
27425 					    &ire->ire_addr_v6, B_FALSE);
27426 				} else {
27427 					nce = ndp_lookup_v6(ill, B_FALSE,
27428 					    &gw_addr_v6, B_FALSE);
27429 				}
27430 				if (nce != NULL) {
27431 					nce_resolv_failed(nce);
27432 					ndp_delete(nce);
27433 					NCE_REFRELE(nce);
27434 				}
27435 			}
27436 			mp->b_cont = NULL;
27437 			freemsg(mp1);		/* frees the pkt as well */
27438 			ASSERT(ire->ire_nce == NULL);
27439 			ire_delete((ire_t *)mp->b_rptr);
27440 			return;
27441 		}
27442 
27443 		/*
27444 		 * Split them into IRE_MBLK and pkt and feed it into
27445 		 * ire_add_then_send. Then in ire_add_then_send
27446 		 * the IRE will be added, and then the packet will be
27447 		 * run back through ip_wput. This time it will make
27448 		 * it to the wire.
27449 		 */
27450 		mp->b_cont = NULL;
27451 		mp = mp1->b_cont;		/* now, mp points to pkt */
27452 		mp1->b_cont = NULL;
27453 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27454 		if (ire->ire_ipversion == IPV6_VERSION) {
27455 			/*
27456 			 * XRESOLV interface. Find the nce and put a copy
27457 			 * of the dl_unitdata_req in nce_res_mp
27458 			 */
27459 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27460 			mutex_enter(&ire->ire_lock);
27461 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27462 			mutex_exit(&ire->ire_lock);
27463 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27464 				nce = ndp_lookup_v6(ill, B_FALSE,
27465 				    &ire->ire_addr_v6, B_FALSE);
27466 			} else {
27467 				nce = ndp_lookup_v6(ill, B_FALSE,
27468 				    &gw_addr_v6, B_FALSE);
27469 			}
27470 			if (nce != NULL) {
27471 				/*
27472 				 * We have to protect nce_res_mp here
27473 				 * from being accessed by other threads
27474 				 * while we change the mblk pointer.
27475 				 * Other functions will also lock the nce when
27476 				 * accessing nce_res_mp.
27477 				 *
27478 				 * The reason we change the mblk pointer
27479 				 * here rather than copying the resolved address
27480 				 * into the template is that, unlike with
27481 				 * ethernet, we have no guarantee that the
27482 				 * resolved address length will be
27483 				 * smaller than or equal to the lla length
27484 				 * with which the template was allocated,
27485 				 * (for ethernet, they're equal)
27486 				 * so we have to use the actual resolved
27487 				 * address mblk - which holds the real
27488 				 * dl_unitdata_req with the resolved address.
27489 				 *
27490 				 * Doing this is the same behavior as was
27491 				 * previously used in the v4 ARP case.
27492 				 */
27493 				mutex_enter(&nce->nce_lock);
27494 				if (nce->nce_res_mp != NULL)
27495 					freemsg(nce->nce_res_mp);
27496 				nce->nce_res_mp = mp1;
27497 				mutex_exit(&nce->nce_lock);
27498 				/*
27499 				 * We do a fastpath probe here because
27500 				 * we have resolved the address without
27501 				 * using Neighbor Discovery.
27502 				 * In the non-XRESOLV v6 case, the fastpath
27503 				 * probe is done right after neighbor
27504 				 * discovery completes.
27505 				 */
27506 				if (nce->nce_res_mp != NULL) {
27507 					int res;
27508 					nce_fastpath_list_add(nce);
27509 					res = ill_fastpath_probe(ill,
27510 					    nce->nce_res_mp);
27511 					if (res != 0 && res != EAGAIN)
27512 						nce_fastpath_list_delete(nce);
27513 				}
27514 
27515 				ire_add_then_send(q, ire, mp);
27516 				/*
27517 				 * Now we have to clean out any packets
27518 				 * that may have been queued on the nce
27519 				 * while it was waiting for address resolution
27520 				 * to complete.
27521 				 */
27522 				mutex_enter(&nce->nce_lock);
27523 				mp1 = nce->nce_qd_mp;
27524 				nce->nce_qd_mp = NULL;
27525 				mutex_exit(&nce->nce_lock);
27526 				while (mp1 != NULL) {
27527 					mblk_t *nxt_mp;
27528 					queue_t *fwdq = NULL;
27529 					ill_t   *inbound_ill;
27530 					uint_t ifindex;
27531 
27532 					nxt_mp = mp1->b_next;
27533 					mp1->b_next = NULL;
27534 					/*
27535 					 * Retrieve ifindex stored in
27536 					 * ip_rput_data_v6()
27537 					 */
27538 					ifindex =
27539 					    (uint_t)(uintptr_t)mp1->b_prev;
27540 					inbound_ill =
27541 					    ill_lookup_on_ifindex(ifindex,
27542 					    B_TRUE, NULL, NULL, NULL,
27543 					    NULL, ipst);
27544 					mp1->b_prev = NULL;
27545 					if (inbound_ill != NULL)
27546 						fwdq = inbound_ill->ill_rq;
27547 
27548 					if (fwdq != NULL) {
27549 						put(fwdq, mp1);
27550 						ill_refrele(inbound_ill);
27551 					} else
27552 						put(WR(ill->ill_rq), mp1);
27553 					mp1 = nxt_mp;
27554 				}
27555 				NCE_REFRELE(nce);
27556 			} else {	/* nce is NULL; clean up */
27557 				ire_delete(ire);
27558 				freemsg(mp);
27559 				freemsg(mp1);
27560 				return;
27561 			}
27562 		} else {
27563 			nce_t *arpce;
27564 			/*
27565 			 * Link layer resolution succeeded. Recompute the
27566 			 * ire_nce.
27567 			 */
27568 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27569 			if ((arpce = ndp_lookup_v4(ill,
27570 			    (ire->ire_gateway_addr != INADDR_ANY ?
27571 			    &ire->ire_gateway_addr : &ire->ire_addr),
27572 			    B_FALSE)) == NULL) {
27573 				freeb(ire->ire_mp);
27574 				freeb(mp1);
27575 				freemsg(mp);
27576 				return;
27577 			}
27578 			mutex_enter(&arpce->nce_lock);
27579 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27580 			if (arpce->nce_state == ND_REACHABLE) {
27581 				/*
27582 				 * Someone resolved this before us;
27583 				 * cleanup the res_mp. Since ire has
27584 				 * not been added yet, the call to ire_add_v4
27585 				 * from ire_add_then_send (when a dup is
27586 				 * detected) will clean up the ire.
27587 				 */
27588 				freeb(mp1);
27589 			} else {
27590 				ASSERT(arpce->nce_res_mp == NULL);
27591 				arpce->nce_res_mp = mp1;
27592 				arpce->nce_state = ND_REACHABLE;
27593 			}
27594 			mutex_exit(&arpce->nce_lock);
27595 			if (ire->ire_marks & IRE_MARK_NOADD) {
27596 				/*
27597 				 * this ire will not be added to the ire
27598 				 * cache table, so we can set the ire_nce
27599 				 * here, as there are no atomicity constraints.
27600 				 */
27601 				ire->ire_nce = arpce;
27602 				/*
27603 				 * We are associating this nce with the ire
27604 				 * so change the nce ref taken in
27605 				 * ndp_lookup_v4() from
27606 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27607 				 */
27608 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27609 			} else {
27610 				NCE_REFRELE(arpce);
27611 			}
27612 			ire_add_then_send(q, ire, mp);
27613 		}
27614 		return;	/* All is well, the packet has been sent. */
27615 	}
27616 	case IRE_ARPRESOLVE_TYPE: {
27617 
27618 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27619 			break;
27620 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27621 		mp->b_cont = NULL;
27622 		/*
27623 		 * First, check to make sure the resolution succeeded.
27624 		 * If it failed, the second mblk will be empty.
27625 		 */
27626 		if (mp1->b_rptr == mp1->b_wptr) {
27627 			/* cleanup  the incomplete ire, free queued packets */
27628 			freemsg(mp); /* fake ire */
27629 			freeb(mp1);  /* dl_unitdata response */
27630 			return;
27631 		}
27632 
27633 		/*
27634 		 * Update any incomplete nce_t found. We search the ctable
27635 		 * and find the nce from the ire->ire_nce because we need
27636 		 * to pass the ire to ip_xmit_v4 later, and can find both
27637 		 * ire and nce in one lookup.
27638 		 */
27639 		fake_ire = (ire_t *)mp->b_rptr;
27640 
27641 		/*
27642 		 * By the time we come back here from ARP the logical outgoing
27643 		 * interface of the incomplete ire we added in ire_forward()
27644 		 * could have disappeared, causing the incomplete ire to also
27645 		 * disappear.  So we need to retreive the proper ipif for the
27646 		 * ire before looking in ctable.  In the case of IPMP, the
27647 		 * ipif may be on the IPMP ill, so look it up based on the
27648 		 * ire_ipif_ifindex we stashed back in ire_init_common().
27649 		 * Then, we can verify that ire_ipif_seqid still exists.
27650 		 */
27651 		ill = ill_lookup_on_ifindex(fake_ire->ire_ipif_ifindex, B_FALSE,
27652 		    NULL, NULL, NULL, NULL, ipst);
27653 		if (ill == NULL) {
27654 			ip1dbg(("ill for incomplete ire vanished\n"));
27655 			freemsg(mp); /* fake ire */
27656 			freeb(mp1);  /* dl_unitdata response */
27657 			return;
27658 		}
27659 
27660 		/* Get the outgoing ipif */
27661 		mutex_enter(&ill->ill_lock);
27662 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27663 		if (ipif == NULL) {
27664 			mutex_exit(&ill->ill_lock);
27665 			ill_refrele(ill);
27666 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27667 			freemsg(mp); /* fake_ire */
27668 			freeb(mp1);  /* dl_unitdata response */
27669 			return;
27670 		}
27671 
27672 		ipif_refhold_locked(ipif);
27673 		mutex_exit(&ill->ill_lock);
27674 		ill_refrele(ill);
27675 		ire = ire_arpresolve_lookup(fake_ire->ire_addr,
27676 		    fake_ire->ire_gateway_addr, ipif, fake_ire->ire_zoneid,
27677 		    ipst, ((ill_t *)q->q_ptr)->ill_wq);
27678 		ipif_refrele(ipif);
27679 		if (ire == NULL) {
27680 			/*
27681 			 * no ire was found; check if there is an nce
27682 			 * for this lookup; if it has no ire's pointing at it
27683 			 * cleanup.
27684 			 */
27685 			if ((nce = ndp_lookup_v4(q->q_ptr,
27686 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27687 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27688 			    B_FALSE)) != NULL) {
27689 				/*
27690 				 * cleanup:
27691 				 * We check for refcnt 2 (one for the nce
27692 				 * hash list + 1 for the ref taken by
27693 				 * ndp_lookup_v4) to check that there are
27694 				 * no ire's pointing at the nce.
27695 				 */
27696 				if (nce->nce_refcnt == 2)
27697 					ndp_delete(nce);
27698 				NCE_REFRELE(nce);
27699 			}
27700 			freeb(mp1);  /* dl_unitdata response */
27701 			freemsg(mp); /* fake ire */
27702 			return;
27703 		}
27704 
27705 		nce = ire->ire_nce;
27706 		DTRACE_PROBE2(ire__arpresolve__type,
27707 		    ire_t *, ire, nce_t *, nce);
27708 		ASSERT(nce->nce_state != ND_INITIAL);
27709 		mutex_enter(&nce->nce_lock);
27710 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27711 		if (nce->nce_state == ND_REACHABLE) {
27712 			/*
27713 			 * Someone resolved this before us;
27714 			 * our response is not needed any more.
27715 			 */
27716 			mutex_exit(&nce->nce_lock);
27717 			freeb(mp1);  /* dl_unitdata response */
27718 		} else {
27719 			ASSERT(nce->nce_res_mp == NULL);
27720 			nce->nce_res_mp = mp1;
27721 			nce->nce_state = ND_REACHABLE;
27722 			mutex_exit(&nce->nce_lock);
27723 			nce_fastpath(nce);
27724 		}
27725 		/*
27726 		 * The cached nce_t has been updated to be reachable;
27727 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27728 		 */
27729 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27730 		freemsg(mp);
27731 		/*
27732 		 * send out queued packets.
27733 		 */
27734 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
27735 
27736 		IRE_REFRELE(ire);
27737 		return;
27738 	}
27739 	default:
27740 		break;
27741 	}
27742 	if (q->q_next) {
27743 		putnext(q, mp);
27744 	} else
27745 		freemsg(mp);
27746 	return;
27747 
27748 protonak:
27749 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27750 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27751 		qreply(q, mp);
27752 }
27753 
27754 /*
27755  * Process IP options in an outbound packet.  Modify the destination if there
27756  * is a source route option.
27757  * Returns non-zero if something fails in which case an ICMP error has been
27758  * sent and mp freed.
27759  */
27760 static int
27761 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27762     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27763 {
27764 	ipoptp_t	opts;
27765 	uchar_t		*opt;
27766 	uint8_t		optval;
27767 	uint8_t		optlen;
27768 	ipaddr_t	dst;
27769 	intptr_t	code = 0;
27770 	mblk_t		*mp;
27771 	ire_t		*ire = NULL;
27772 
27773 	ip2dbg(("ip_wput_options\n"));
27774 	mp = ipsec_mp;
27775 	if (mctl_present) {
27776 		mp = ipsec_mp->b_cont;
27777 	}
27778 
27779 	dst = ipha->ipha_dst;
27780 	for (optval = ipoptp_first(&opts, ipha);
27781 	    optval != IPOPT_EOL;
27782 	    optval = ipoptp_next(&opts)) {
27783 		opt = opts.ipoptp_cur;
27784 		optlen = opts.ipoptp_len;
27785 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27786 		    optval, optlen));
27787 		switch (optval) {
27788 			uint32_t off;
27789 		case IPOPT_SSRR:
27790 		case IPOPT_LSRR:
27791 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27792 				ip1dbg((
27793 				    "ip_wput_options: bad option offset\n"));
27794 				code = (char *)&opt[IPOPT_OLEN] -
27795 				    (char *)ipha;
27796 				goto param_prob;
27797 			}
27798 			off = opt[IPOPT_OFFSET];
27799 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27800 			    ntohl(dst)));
27801 			/*
27802 			 * For strict: verify that dst is directly
27803 			 * reachable.
27804 			 */
27805 			if (optval == IPOPT_SSRR) {
27806 				ire = ire_ftable_lookup(dst, 0, 0,
27807 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27808 				    msg_getlabel(mp),
27809 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27810 				if (ire == NULL) {
27811 					ip1dbg(("ip_wput_options: SSRR not"
27812 					    " directly reachable: 0x%x\n",
27813 					    ntohl(dst)));
27814 					goto bad_src_route;
27815 				}
27816 				ire_refrele(ire);
27817 			}
27818 			break;
27819 		case IPOPT_RR:
27820 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27821 				ip1dbg((
27822 				    "ip_wput_options: bad option offset\n"));
27823 				code = (char *)&opt[IPOPT_OLEN] -
27824 				    (char *)ipha;
27825 				goto param_prob;
27826 			}
27827 			break;
27828 		case IPOPT_TS:
27829 			/*
27830 			 * Verify that length >=5 and that there is either
27831 			 * room for another timestamp or that the overflow
27832 			 * counter is not maxed out.
27833 			 */
27834 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27835 			if (optlen < IPOPT_MINLEN_IT) {
27836 				goto param_prob;
27837 			}
27838 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27839 				ip1dbg((
27840 				    "ip_wput_options: bad option offset\n"));
27841 				code = (char *)&opt[IPOPT_OFFSET] -
27842 				    (char *)ipha;
27843 				goto param_prob;
27844 			}
27845 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27846 			case IPOPT_TS_TSONLY:
27847 				off = IPOPT_TS_TIMELEN;
27848 				break;
27849 			case IPOPT_TS_TSANDADDR:
27850 			case IPOPT_TS_PRESPEC:
27851 			case IPOPT_TS_PRESPEC_RFC791:
27852 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27853 				break;
27854 			default:
27855 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27856 				    (char *)ipha;
27857 				goto param_prob;
27858 			}
27859 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27860 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27861 				/*
27862 				 * No room and the overflow counter is 15
27863 				 * already.
27864 				 */
27865 				goto param_prob;
27866 			}
27867 			break;
27868 		}
27869 	}
27870 
27871 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27872 		return (0);
27873 
27874 	ip1dbg(("ip_wput_options: error processing IP options."));
27875 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27876 
27877 param_prob:
27878 	/*
27879 	 * Since ip_wput() isn't close to finished, we fill
27880 	 * in enough of the header for credible error reporting.
27881 	 */
27882 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27883 		/* Failed */
27884 		freemsg(ipsec_mp);
27885 		return (-1);
27886 	}
27887 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
27888 	return (-1);
27889 
27890 bad_src_route:
27891 	/*
27892 	 * Since ip_wput() isn't close to finished, we fill
27893 	 * in enough of the header for credible error reporting.
27894 	 */
27895 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27896 		/* Failed */
27897 		freemsg(ipsec_mp);
27898 		return (-1);
27899 	}
27900 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
27901 	return (-1);
27902 }
27903 
27904 /*
27905  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
27906  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
27907  * thru /etc/system.
27908  */
27909 #define	CONN_MAXDRAINCNT	64
27910 
27911 static void
27912 conn_drain_init(ip_stack_t *ipst)
27913 {
27914 	int i;
27915 
27916 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
27917 
27918 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
27919 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
27920 		/*
27921 		 * Default value of the number of drainers is the
27922 		 * number of cpus, subject to maximum of 8 drainers.
27923 		 */
27924 		if (boot_max_ncpus != -1)
27925 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
27926 		else
27927 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
27928 	}
27929 
27930 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
27931 	    sizeof (idl_t), KM_SLEEP);
27932 
27933 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
27934 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
27935 		    MUTEX_DEFAULT, NULL);
27936 	}
27937 }
27938 
27939 static void
27940 conn_drain_fini(ip_stack_t *ipst)
27941 {
27942 	int i;
27943 
27944 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
27945 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
27946 	kmem_free(ipst->ips_conn_drain_list,
27947 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
27948 	ipst->ips_conn_drain_list = NULL;
27949 }
27950 
27951 /*
27952  * Note: For an overview of how flowcontrol is handled in IP please see the
27953  * IP Flowcontrol notes at the top of this file.
27954  *
27955  * Flow control has blocked us from proceeding. Insert the given conn in one
27956  * of the conn drain lists. These conn wq's will be qenabled later on when
27957  * STREAMS flow control does a backenable. conn_walk_drain will enable
27958  * the first conn in each of these drain lists. Each of these qenabled conns
27959  * in turn enables the next in the list, after it runs, or when it closes,
27960  * thus sustaining the drain process.
27961  *
27962  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
27963  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
27964  * running at any time, on a given conn, since there can be only 1 service proc
27965  * running on a queue at any time.
27966  */
27967 void
27968 conn_drain_insert(conn_t *connp)
27969 {
27970 	idl_t	*idl;
27971 	uint_t	index;
27972 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
27973 
27974 	mutex_enter(&connp->conn_lock);
27975 	if (connp->conn_state_flags & CONN_CLOSING) {
27976 		/*
27977 		 * The conn is closing as a result of which CONN_CLOSING
27978 		 * is set. Return.
27979 		 */
27980 		mutex_exit(&connp->conn_lock);
27981 		return;
27982 	} else if (connp->conn_idl == NULL) {
27983 		/*
27984 		 * Assign the next drain list round robin. We dont' use
27985 		 * a lock, and thus it may not be strictly round robin.
27986 		 * Atomicity of load/stores is enough to make sure that
27987 		 * conn_drain_list_index is always within bounds.
27988 		 */
27989 		index = ipst->ips_conn_drain_list_index;
27990 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
27991 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
27992 		index++;
27993 		if (index == ipst->ips_conn_drain_list_cnt)
27994 			index = 0;
27995 		ipst->ips_conn_drain_list_index = index;
27996 	}
27997 	mutex_exit(&connp->conn_lock);
27998 
27999 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28000 	if ((connp->conn_drain_prev != NULL) ||
28001 	    (connp->conn_state_flags & CONN_CLOSING)) {
28002 		/*
28003 		 * The conn is already in the drain list, OR
28004 		 * the conn is closing. We need to check again for
28005 		 * the closing case again since close can happen
28006 		 * after we drop the conn_lock, and before we
28007 		 * acquire the CONN_DRAIN_LIST_LOCK.
28008 		 */
28009 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28010 		return;
28011 	} else {
28012 		idl = connp->conn_idl;
28013 	}
28014 
28015 	/*
28016 	 * The conn is not in the drain list. Insert it at the
28017 	 * tail of the drain list. The drain list is circular
28018 	 * and doubly linked. idl_conn points to the 1st element
28019 	 * in the list.
28020 	 */
28021 	if (idl->idl_conn == NULL) {
28022 		idl->idl_conn = connp;
28023 		connp->conn_drain_next = connp;
28024 		connp->conn_drain_prev = connp;
28025 	} else {
28026 		conn_t *head = idl->idl_conn;
28027 
28028 		connp->conn_drain_next = head;
28029 		connp->conn_drain_prev = head->conn_drain_prev;
28030 		head->conn_drain_prev->conn_drain_next = connp;
28031 		head->conn_drain_prev = connp;
28032 	}
28033 	/*
28034 	 * For non streams based sockets assert flow control.
28035 	 */
28036 	if (IPCL_IS_NONSTR(connp)) {
28037 		(*connp->conn_upcalls->su_txq_full)
28038 		    (connp->conn_upper_handle, B_TRUE);
28039 	}
28040 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28041 }
28042 
28043 /*
28044  * This conn is closing, and we are called from ip_close. OR
28045  * This conn has been serviced by ip_wsrv, and we need to do the tail
28046  * processing.
28047  * If this conn is part of the drain list, we may need to sustain the drain
28048  * process by qenabling the next conn in the drain list. We may also need to
28049  * remove this conn from the list, if it is done.
28050  */
28051 static void
28052 conn_drain_tail(conn_t *connp, boolean_t closing)
28053 {
28054 	idl_t *idl;
28055 
28056 	/*
28057 	 * connp->conn_idl is stable at this point, and no lock is needed
28058 	 * to check it. If we are called from ip_close, close has already
28059 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28060 	 * called us only because conn_idl is non-null. If we are called thru
28061 	 * service, conn_idl could be null, but it cannot change because
28062 	 * service is single-threaded per queue, and there cannot be another
28063 	 * instance of service trying to call conn_drain_insert on this conn
28064 	 * now.
28065 	 */
28066 	ASSERT(!closing || (connp->conn_idl != NULL));
28067 
28068 	/*
28069 	 * If connp->conn_idl is null, the conn has not been inserted into any
28070 	 * drain list even once since creation of the conn. Just return.
28071 	 */
28072 	if (connp->conn_idl == NULL)
28073 		return;
28074 
28075 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28076 
28077 	if (connp->conn_drain_prev == NULL) {
28078 		/* This conn is currently not in the drain list.  */
28079 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28080 		return;
28081 	}
28082 	idl = connp->conn_idl;
28083 	if (idl->idl_conn_draining == connp) {
28084 		/*
28085 		 * This conn is the current drainer. If this is the last conn
28086 		 * in the drain list, we need to do more checks, in the 'if'
28087 		 * below. Otherwwise we need to just qenable the next conn,
28088 		 * to sustain the draining, and is handled in the 'else'
28089 		 * below.
28090 		 */
28091 		if (connp->conn_drain_next == idl->idl_conn) {
28092 			/*
28093 			 * This conn is the last in this list. This round
28094 			 * of draining is complete. If idl_repeat is set,
28095 			 * it means another flow enabling has happened from
28096 			 * the driver/streams and we need to another round
28097 			 * of draining.
28098 			 * If there are more than 2 conns in the drain list,
28099 			 * do a left rotate by 1, so that all conns except the
28100 			 * conn at the head move towards the head by 1, and the
28101 			 * the conn at the head goes to the tail. This attempts
28102 			 * a more even share for all queues that are being
28103 			 * drained.
28104 			 */
28105 			if ((connp->conn_drain_next != connp) &&
28106 			    (idl->idl_conn->conn_drain_next != connp)) {
28107 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28108 			}
28109 			if (idl->idl_repeat) {
28110 				qenable(idl->idl_conn->conn_wq);
28111 				idl->idl_conn_draining = idl->idl_conn;
28112 				idl->idl_repeat = 0;
28113 			} else {
28114 				idl->idl_conn_draining = NULL;
28115 			}
28116 		} else {
28117 			/*
28118 			 * If the next queue that we are now qenable'ing,
28119 			 * is closing, it will remove itself from this list
28120 			 * and qenable the subsequent queue in ip_close().
28121 			 * Serialization is acheived thru idl_lock.
28122 			 */
28123 			qenable(connp->conn_drain_next->conn_wq);
28124 			idl->idl_conn_draining = connp->conn_drain_next;
28125 		}
28126 	}
28127 	if (!connp->conn_did_putbq || closing) {
28128 		/*
28129 		 * Remove ourself from the drain list, if we did not do
28130 		 * a putbq, or if the conn is closing.
28131 		 * Note: It is possible that q->q_first is non-null. It means
28132 		 * that these messages landed after we did a enableok() in
28133 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28134 		 * service them.
28135 		 */
28136 		if (connp->conn_drain_next == connp) {
28137 			/* Singleton in the list */
28138 			ASSERT(connp->conn_drain_prev == connp);
28139 			idl->idl_conn = NULL;
28140 			idl->idl_conn_draining = NULL;
28141 		} else {
28142 			connp->conn_drain_prev->conn_drain_next =
28143 			    connp->conn_drain_next;
28144 			connp->conn_drain_next->conn_drain_prev =
28145 			    connp->conn_drain_prev;
28146 			if (idl->idl_conn == connp)
28147 				idl->idl_conn = connp->conn_drain_next;
28148 			ASSERT(idl->idl_conn_draining != connp);
28149 
28150 		}
28151 		connp->conn_drain_next = NULL;
28152 		connp->conn_drain_prev = NULL;
28153 
28154 		/*
28155 		 * For non streams based sockets open up flow control.
28156 		 */
28157 		if (IPCL_IS_NONSTR(connp)) {
28158 			(*connp->conn_upcalls->su_txq_full)
28159 			    (connp->conn_upper_handle, B_FALSE);
28160 		}
28161 	}
28162 
28163 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28164 }
28165 
28166 /*
28167  * Write service routine. Shared perimeter entry point.
28168  * ip_wsrv can be called in any of the following ways.
28169  * 1. The device queue's messages has fallen below the low water mark
28170  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28171  *    the drain lists and backenable the first conn in each list.
28172  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28173  *    qenabled non-tcp upper layers. We start dequeing messages and call
28174  *    ip_wput for each message.
28175  */
28176 
28177 void
28178 ip_wsrv(queue_t *q)
28179 {
28180 	conn_t	*connp;
28181 	ill_t	*ill;
28182 	mblk_t	*mp;
28183 
28184 	if (q->q_next) {
28185 		ill = (ill_t *)q->q_ptr;
28186 		if (ill->ill_state_flags == 0) {
28187 			/*
28188 			 * The device flow control has opened up.
28189 			 * Walk through conn drain lists and qenable the
28190 			 * first conn in each list. This makes sense only
28191 			 * if the stream is fully plumbed and setup.
28192 			 * Hence the if check above.
28193 			 */
28194 			ip1dbg(("ip_wsrv: walking\n"));
28195 			conn_walk_drain(ill->ill_ipst);
28196 		}
28197 		return;
28198 	}
28199 
28200 	connp = Q_TO_CONN(q);
28201 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28202 
28203 	/*
28204 	 * 1. Set conn_draining flag to signal that service is active.
28205 	 *
28206 	 * 2. ip_output determines whether it has been called from service,
28207 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28208 	 *    has been called from service.
28209 	 *
28210 	 * 3. Message ordering is preserved by the following logic.
28211 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28212 	 *    the message at the tail, if conn_draining is set (i.e. service
28213 	 *    is running) or if q->q_first is non-null.
28214 	 *
28215 	 *    ii. If ip_output is called from service, and if ip_output cannot
28216 	 *    putnext due to flow control, it does a putbq.
28217 	 *
28218 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28219 	 *    (causing an infinite loop).
28220 	 */
28221 	ASSERT(!connp->conn_did_putbq);
28222 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28223 		connp->conn_draining = 1;
28224 		noenable(q);
28225 		while ((mp = getq(q)) != NULL) {
28226 			ASSERT(CONN_Q(q));
28227 
28228 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28229 			if (connp->conn_did_putbq) {
28230 				/* ip_wput did a putbq */
28231 				break;
28232 			}
28233 		}
28234 		/*
28235 		 * At this point, a thread coming down from top, calling
28236 		 * ip_wput, may end up queueing the message. We have not yet
28237 		 * enabled the queue, so ip_wsrv won't be called again.
28238 		 * To avoid this race, check q->q_first again (in the loop)
28239 		 * If the other thread queued the message before we call
28240 		 * enableok(), we will catch it in the q->q_first check.
28241 		 * If the other thread queues the message after we call
28242 		 * enableok(), ip_wsrv will be called again by STREAMS.
28243 		 */
28244 		connp->conn_draining = 0;
28245 		enableok(q);
28246 
28247 	}
28248 
28249 	/* Enable the next conn for draining */
28250 	conn_drain_tail(connp, B_FALSE);
28251 
28252 	connp->conn_did_putbq = 0;
28253 }
28254 
28255 /*
28256  * Callback to disable flow control in IP.
28257  *
28258  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
28259  * is enabled.
28260  *
28261  * When MAC_TX() is not able to send any more packets, dld sets its queue
28262  * to QFULL and enable the STREAMS flow control. Later, when the underlying
28263  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
28264  * function and wakes up corresponding mac worker threads, which in turn
28265  * calls this callback function, and disables flow control.
28266  */
28267 /* ARGSUSED */
28268 void
28269 ill_flow_enable(void *ill, ip_mac_tx_cookie_t cookie)
28270 {
28271 	qenable(((ill_t *)ill)->ill_wq);
28272 }
28273 
28274 /*
28275  * Walk the list of all conn's calling the function provided with the
28276  * specified argument for each.	 Note that this only walks conn's that
28277  * have been bound.
28278  * Applies to both IPv4 and IPv6.
28279  */
28280 static void
28281 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28282 {
28283 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28284 	    ipst->ips_ipcl_udp_fanout_size,
28285 	    func, arg, zoneid);
28286 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28287 	    ipst->ips_ipcl_conn_fanout_size,
28288 	    func, arg, zoneid);
28289 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28290 	    ipst->ips_ipcl_bind_fanout_size,
28291 	    func, arg, zoneid);
28292 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28293 	    IPPROTO_MAX, func, arg, zoneid);
28294 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28295 	    IPPROTO_MAX, func, arg, zoneid);
28296 }
28297 
28298 /*
28299  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28300  * of conns that need to be drained, check if drain is already in progress.
28301  * If so set the idl_repeat bit, indicating that the last conn in the list
28302  * needs to reinitiate the drain once again, for the list. If drain is not
28303  * in progress for the list, initiate the draining, by qenabling the 1st
28304  * conn in the list. The drain is self-sustaining, each qenabled conn will
28305  * in turn qenable the next conn, when it is done/blocked/closing.
28306  */
28307 static void
28308 conn_walk_drain(ip_stack_t *ipst)
28309 {
28310 	int i;
28311 	idl_t *idl;
28312 
28313 	IP_STAT(ipst, ip_conn_walk_drain);
28314 
28315 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28316 		idl = &ipst->ips_conn_drain_list[i];
28317 		mutex_enter(&idl->idl_lock);
28318 		if (idl->idl_conn == NULL) {
28319 			mutex_exit(&idl->idl_lock);
28320 			continue;
28321 		}
28322 		/*
28323 		 * If this list is not being drained currently by
28324 		 * an ip_wsrv thread, start the process.
28325 		 */
28326 		if (idl->idl_conn_draining == NULL) {
28327 			ASSERT(idl->idl_repeat == 0);
28328 			qenable(idl->idl_conn->conn_wq);
28329 			idl->idl_conn_draining = idl->idl_conn;
28330 		} else {
28331 			idl->idl_repeat = 1;
28332 		}
28333 		mutex_exit(&idl->idl_lock);
28334 	}
28335 }
28336 
28337 /*
28338  * Walk an conn hash table of `count' buckets, calling func for each entry.
28339  */
28340 static void
28341 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28342     zoneid_t zoneid)
28343 {
28344 	conn_t	*connp;
28345 
28346 	while (count-- > 0) {
28347 		mutex_enter(&connfp->connf_lock);
28348 		for (connp = connfp->connf_head; connp != NULL;
28349 		    connp = connp->conn_next) {
28350 			if (zoneid == GLOBAL_ZONEID ||
28351 			    zoneid == connp->conn_zoneid) {
28352 				CONN_INC_REF(connp);
28353 				mutex_exit(&connfp->connf_lock);
28354 				(*func)(connp, arg);
28355 				mutex_enter(&connfp->connf_lock);
28356 				CONN_DEC_REF(connp);
28357 			}
28358 		}
28359 		mutex_exit(&connfp->connf_lock);
28360 		connfp++;
28361 	}
28362 }
28363 
28364 /* conn_walk_fanout routine invoked for ip_conn_report for each conn. */
28365 static void
28366 conn_report1(conn_t *connp, void *mp)
28367 {
28368 	char	buf1[INET6_ADDRSTRLEN];
28369 	char	buf2[INET6_ADDRSTRLEN];
28370 	uint_t	print_len, buf_len;
28371 
28372 	ASSERT(connp != NULL);
28373 
28374 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28375 	if (buf_len <= 0)
28376 		return;
28377 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28378 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28379 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28380 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28381 	    "%5d %s/%05d %s/%05d\n",
28382 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28383 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28384 	    buf1, connp->conn_lport,
28385 	    buf2, connp->conn_fport);
28386 	if (print_len < buf_len) {
28387 		((mblk_t *)mp)->b_wptr += print_len;
28388 	} else {
28389 		((mblk_t *)mp)->b_wptr += buf_len;
28390 	}
28391 }
28392 
28393 /*
28394  * Named Dispatch routine to produce a formatted report on all conns
28395  * that are listed in one of the fanout tables.
28396  * This report is accessed by using the ndd utility to "get" ND variable
28397  * "ip_conn_status".
28398  */
28399 /* ARGSUSED */
28400 static int
28401 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28402 {
28403 	conn_t *connp = Q_TO_CONN(q);
28404 
28405 	(void) mi_mpprintf(mp,
28406 	    "CONN      " MI_COL_HDRPAD_STR
28407 	    "rfq      " MI_COL_HDRPAD_STR
28408 	    "stq      " MI_COL_HDRPAD_STR
28409 	    " zone local		 remote");
28410 
28411 	/*
28412 	 * Because of the ndd constraint, at most we can have 64K buffer
28413 	 * to put in all conn info.  So to be more efficient, just
28414 	 * allocate a 64K buffer here, assuming we need that large buffer.
28415 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28416 	 */
28417 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28418 		/* The following may work even if we cannot get a large buf. */
28419 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28420 		return (0);
28421 	}
28422 
28423 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28424 	    connp->conn_netstack->netstack_ip);
28425 	return (0);
28426 }
28427 
28428 /*
28429  * Determine if the ill and multicast aspects of that packets
28430  * "matches" the conn.
28431  */
28432 boolean_t
28433 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28434     zoneid_t zoneid)
28435 {
28436 	ill_t *bound_ill;
28437 	boolean_t found;
28438 	ipif_t *ipif;
28439 	ire_t *ire;
28440 	ipaddr_t dst, src;
28441 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28442 
28443 	dst = ipha->ipha_dst;
28444 	src = ipha->ipha_src;
28445 
28446 	/*
28447 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28448 	 * unicast, broadcast and multicast reception to
28449 	 * conn_incoming_ill. conn_wantpacket itself is called
28450 	 * only for BROADCAST and multicast.
28451 	 */
28452 	bound_ill = connp->conn_incoming_ill;
28453 	if (bound_ill != NULL) {
28454 		if (IS_IPMP(bound_ill)) {
28455 			if (bound_ill->ill_grp != ill->ill_grp)
28456 				return (B_FALSE);
28457 		} else {
28458 			if (bound_ill != ill)
28459 				return (B_FALSE);
28460 		}
28461 	}
28462 
28463 	if (!CLASSD(dst)) {
28464 		if (IPCL_ZONE_MATCH(connp, zoneid))
28465 			return (B_TRUE);
28466 		/*
28467 		 * The conn is in a different zone; we need to check that this
28468 		 * broadcast address is configured in the application's zone.
28469 		 */
28470 		ipif = ipif_get_next_ipif(NULL, ill);
28471 		if (ipif == NULL)
28472 			return (B_FALSE);
28473 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28474 		    connp->conn_zoneid, NULL,
28475 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL), ipst);
28476 		ipif_refrele(ipif);
28477 		if (ire != NULL) {
28478 			ire_refrele(ire);
28479 			return (B_TRUE);
28480 		} else {
28481 			return (B_FALSE);
28482 		}
28483 	}
28484 
28485 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28486 	    connp->conn_zoneid == zoneid) {
28487 		/*
28488 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28489 		 * disabled, therefore we don't dispatch the multicast packet to
28490 		 * the sending zone.
28491 		 */
28492 		return (B_FALSE);
28493 	}
28494 
28495 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28496 		/*
28497 		 * Multicast packet on the loopback interface: we only match
28498 		 * conns who joined the group in the specified zone.
28499 		 */
28500 		return (B_FALSE);
28501 	}
28502 
28503 	if (connp->conn_multi_router) {
28504 		/* multicast packet and multicast router socket: send up */
28505 		return (B_TRUE);
28506 	}
28507 
28508 	mutex_enter(&connp->conn_lock);
28509 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28510 	mutex_exit(&connp->conn_lock);
28511 	return (found);
28512 }
28513 
28514 /*
28515  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28516  */
28517 /* ARGSUSED */
28518 static void
28519 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28520 {
28521 	ill_t *ill = (ill_t *)q->q_ptr;
28522 	mblk_t	*mp1, *mp2;
28523 	ipif_t  *ipif;
28524 	int err = 0;
28525 	conn_t *connp = NULL;
28526 	ipsq_t	*ipsq;
28527 	arc_t	*arc;
28528 
28529 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28530 
28531 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28532 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28533 
28534 	ASSERT(IAM_WRITER_ILL(ill));
28535 	mp2 = mp->b_cont;
28536 	mp->b_cont = NULL;
28537 
28538 	/*
28539 	 * We have now received the arp bringup completion message
28540 	 * from ARP. Mark the arp bringup as done. Also if the arp
28541 	 * stream has already started closing, send up the AR_ARP_CLOSING
28542 	 * ack now since ARP is waiting in close for this ack.
28543 	 */
28544 	mutex_enter(&ill->ill_lock);
28545 	ill->ill_arp_bringup_pending = 0;
28546 	if (ill->ill_arp_closing) {
28547 		mutex_exit(&ill->ill_lock);
28548 		/* Let's reuse the mp for sending the ack */
28549 		arc = (arc_t *)mp->b_rptr;
28550 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28551 		arc->arc_cmd = AR_ARP_CLOSING;
28552 		qreply(q, mp);
28553 	} else {
28554 		mutex_exit(&ill->ill_lock);
28555 		freeb(mp);
28556 	}
28557 
28558 	ipsq = ill->ill_phyint->phyint_ipsq;
28559 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
28560 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28561 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28562 	if (mp1 == NULL) {
28563 		/* bringup was aborted by the user */
28564 		freemsg(mp2);
28565 		return;
28566 	}
28567 
28568 	/*
28569 	 * If an IOCTL is waiting on this (ipx_current_ioctl != 0), then we
28570 	 * must have an associated conn_t.  Otherwise, we're bringing this
28571 	 * interface back up as part of handling an asynchronous event (e.g.,
28572 	 * physical address change).
28573 	 */
28574 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0) {
28575 		ASSERT(connp != NULL);
28576 		q = CONNP_TO_WQ(connp);
28577 	} else {
28578 		ASSERT(connp == NULL);
28579 		q = ill->ill_rq;
28580 	}
28581 
28582 	/*
28583 	 * If the DL_BIND_REQ fails, it is noted
28584 	 * in arc_name_offset.
28585 	 */
28586 	err = *((int *)mp2->b_rptr);
28587 	if (err == 0) {
28588 		if (ipif->ipif_isv6) {
28589 			if ((err = ipif_up_done_v6(ipif)) != 0)
28590 				ip0dbg(("ip_arp_done: init failed\n"));
28591 		} else {
28592 			if ((err = ipif_up_done(ipif)) != 0)
28593 				ip0dbg(("ip_arp_done: init failed\n"));
28594 		}
28595 	} else {
28596 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28597 	}
28598 
28599 	freemsg(mp2);
28600 
28601 	if ((err == 0) && (ill->ill_up_ipifs)) {
28602 		err = ill_up_ipifs(ill, q, mp1);
28603 		if (err == EINPROGRESS)
28604 			return;
28605 	}
28606 
28607 	/*
28608 	 * If we have a moved ipif to bring up, and everything has succeeded
28609 	 * to this point, bring it up on the IPMP ill.  Otherwise, leave it
28610 	 * down -- the admin can try to bring it up by hand if need be.
28611 	 */
28612 	if (ill->ill_move_ipif != NULL) {
28613 		ipif = ill->ill_move_ipif;
28614 		ill->ill_move_ipif = NULL;
28615 		if (err == 0) {
28616 			err = ipif_up(ipif, q, mp1);
28617 			if (err == EINPROGRESS)
28618 				return;
28619 		}
28620 	}
28621 
28622 	/*
28623 	 * The operation must complete without EINPROGRESS since
28624 	 * ipsq_pending_mp_get() has removed the mblk.  Otherwise, the
28625 	 * operation will be stuck forever in the ipsq.
28626 	 */
28627 	ASSERT(err != EINPROGRESS);
28628 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0)
28629 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28630 	else
28631 		ipsq_current_finish(ipsq);
28632 }
28633 
28634 /* Allocate the private structure */
28635 static int
28636 ip_priv_alloc(void **bufp)
28637 {
28638 	void	*buf;
28639 
28640 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28641 		return (ENOMEM);
28642 
28643 	*bufp = buf;
28644 	return (0);
28645 }
28646 
28647 /* Function to delete the private structure */
28648 void
28649 ip_priv_free(void *buf)
28650 {
28651 	ASSERT(buf != NULL);
28652 	kmem_free(buf, sizeof (ip_priv_t));
28653 }
28654 
28655 /*
28656  * The entry point for IPPF processing.
28657  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28658  * routine just returns.
28659  *
28660  * When called, ip_process generates an ipp_packet_t structure
28661  * which holds the state information for this packet and invokes the
28662  * the classifier (via ipp_packet_process). The classification, depending on
28663  * configured filters, results in a list of actions for this packet. Invoking
28664  * an action may cause the packet to be dropped, in which case the resulting
28665  * mblk (*mpp) is NULL. proc indicates the callout position for
28666  * this packet and ill_index is the interface this packet on or will leave
28667  * on (inbound and outbound resp.).
28668  */
28669 void
28670 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28671 {
28672 	mblk_t		*mp;
28673 	ip_priv_t	*priv;
28674 	ipp_action_id_t	aid;
28675 	int		rc = 0;
28676 	ipp_packet_t	*pp;
28677 #define	IP_CLASS	"ip"
28678 
28679 	/* If the classifier is not loaded, return  */
28680 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28681 		return;
28682 	}
28683 
28684 	mp = *mpp;
28685 	ASSERT(mp != NULL);
28686 
28687 	/* Allocate the packet structure */
28688 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28689 	if (rc != 0) {
28690 		*mpp = NULL;
28691 		freemsg(mp);
28692 		return;
28693 	}
28694 
28695 	/* Allocate the private structure */
28696 	rc = ip_priv_alloc((void **)&priv);
28697 	if (rc != 0) {
28698 		*mpp = NULL;
28699 		freemsg(mp);
28700 		ipp_packet_free(pp);
28701 		return;
28702 	}
28703 	priv->proc = proc;
28704 	priv->ill_index = ill_index;
28705 	ipp_packet_set_private(pp, priv, ip_priv_free);
28706 	ipp_packet_set_data(pp, mp);
28707 
28708 	/* Invoke the classifier */
28709 	rc = ipp_packet_process(&pp);
28710 	if (pp != NULL) {
28711 		mp = ipp_packet_get_data(pp);
28712 		ipp_packet_free(pp);
28713 		if (rc != 0) {
28714 			freemsg(mp);
28715 			*mpp = NULL;
28716 		}
28717 	} else {
28718 		*mpp = NULL;
28719 	}
28720 #undef	IP_CLASS
28721 }
28722 
28723 /*
28724  * Propagate a multicast group membership operation (add/drop) on
28725  * all the interfaces crossed by the related multirt routes.
28726  * The call is considered successful if the operation succeeds
28727  * on at least one interface.
28728  */
28729 static int
28730 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28731     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28732     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28733     mblk_t *first_mp)
28734 {
28735 	ire_t		*ire_gw;
28736 	irb_t		*irb;
28737 	int		error = 0;
28738 	opt_restart_t	*or;
28739 	ip_stack_t	*ipst = ire->ire_ipst;
28740 
28741 	irb = ire->ire_bucket;
28742 	ASSERT(irb != NULL);
28743 
28744 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28745 
28746 	or = (opt_restart_t *)first_mp->b_rptr;
28747 	IRB_REFHOLD(irb);
28748 	for (; ire != NULL; ire = ire->ire_next) {
28749 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28750 			continue;
28751 		if (ire->ire_addr != group)
28752 			continue;
28753 
28754 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28755 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28756 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28757 		/* No resolver exists for the gateway; skip this ire. */
28758 		if (ire_gw == NULL)
28759 			continue;
28760 
28761 		/*
28762 		 * This function can return EINPROGRESS. If so the operation
28763 		 * will be restarted from ip_restart_optmgmt which will
28764 		 * call ip_opt_set and option processing will restart for
28765 		 * this option. So we may end up calling 'fn' more than once.
28766 		 * This requires that 'fn' is idempotent except for the
28767 		 * return value. The operation is considered a success if
28768 		 * it succeeds at least once on any one interface.
28769 		 */
28770 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28771 		    NULL, fmode, src, first_mp);
28772 		if (error == 0)
28773 			or->or_private = CGTP_MCAST_SUCCESS;
28774 
28775 		if (ip_debug > 0) {
28776 			ulong_t	off;
28777 			char	*ksym;
28778 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28779 			ip2dbg(("ip_multirt_apply_membership: "
28780 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28781 			    "error %d [success %u]\n",
28782 			    ksym ? ksym : "?",
28783 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28784 			    error, or->or_private));
28785 		}
28786 
28787 		ire_refrele(ire_gw);
28788 		if (error == EINPROGRESS) {
28789 			IRB_REFRELE(irb);
28790 			return (error);
28791 		}
28792 	}
28793 	IRB_REFRELE(irb);
28794 	/*
28795 	 * Consider the call as successful if we succeeded on at least
28796 	 * one interface. Otherwise, return the last encountered error.
28797 	 */
28798 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28799 }
28800 
28801 /*
28802  * Issue a warning regarding a route crossing an interface with an
28803  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28804  * amount of time is logged.
28805  */
28806 static void
28807 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28808 {
28809 	hrtime_t	current = gethrtime();
28810 	char		buf[INET_ADDRSTRLEN];
28811 	ip_stack_t	*ipst = ire->ire_ipst;
28812 
28813 	/* Convert interval in ms to hrtime in ns */
28814 	if (ipst->ips_multirt_bad_mtu_last_time +
28815 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28816 	    current) {
28817 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28818 		    "to %s, incorrect MTU %u (expected %u)\n",
28819 		    ip_dot_addr(ire->ire_addr, buf),
28820 		    ire->ire_max_frag, max_frag);
28821 
28822 		ipst->ips_multirt_bad_mtu_last_time = current;
28823 	}
28824 }
28825 
28826 /*
28827  * Get the CGTP (multirouting) filtering status.
28828  * If 0, the CGTP hooks are transparent.
28829  */
28830 /* ARGSUSED */
28831 static int
28832 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28833 {
28834 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28835 
28836 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28837 	return (0);
28838 }
28839 
28840 /*
28841  * Set the CGTP (multirouting) filtering status.
28842  * If the status is changed from active to transparent
28843  * or from transparent to active, forward the new status
28844  * to the filtering module (if loaded).
28845  */
28846 /* ARGSUSED */
28847 static int
28848 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28849     cred_t *ioc_cr)
28850 {
28851 	long		new_value;
28852 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28853 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28854 
28855 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
28856 		return (EPERM);
28857 
28858 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28859 	    new_value < 0 || new_value > 1) {
28860 		return (EINVAL);
28861 	}
28862 
28863 	if ((!*ip_cgtp_filter_value) && new_value) {
28864 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28865 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28866 		    " (module not loaded)" : "");
28867 	}
28868 	if (*ip_cgtp_filter_value && (!new_value)) {
28869 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28870 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28871 		    " (module not loaded)" : "");
28872 	}
28873 
28874 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28875 		int	res;
28876 		netstackid_t stackid;
28877 
28878 		stackid = ipst->ips_netstack->netstack_stackid;
28879 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
28880 		    new_value);
28881 		if (res)
28882 			return (res);
28883 	}
28884 
28885 	*ip_cgtp_filter_value = (boolean_t)new_value;
28886 
28887 	return (0);
28888 }
28889 
28890 /*
28891  * Return the expected CGTP hooks version number.
28892  */
28893 int
28894 ip_cgtp_filter_supported(void)
28895 {
28896 	return (ip_cgtp_filter_rev);
28897 }
28898 
28899 /*
28900  * CGTP hooks can be registered by invoking this function.
28901  * Checks that the version number matches.
28902  */
28903 int
28904 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
28905 {
28906 	netstack_t *ns;
28907 	ip_stack_t *ipst;
28908 
28909 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28910 		return (ENOTSUP);
28911 
28912 	ns = netstack_find_by_stackid(stackid);
28913 	if (ns == NULL)
28914 		return (EINVAL);
28915 	ipst = ns->netstack_ip;
28916 	ASSERT(ipst != NULL);
28917 
28918 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28919 		netstack_rele(ns);
28920 		return (EALREADY);
28921 	}
28922 
28923 	ipst->ips_ip_cgtp_filter_ops = ops;
28924 	netstack_rele(ns);
28925 	return (0);
28926 }
28927 
28928 /*
28929  * CGTP hooks can be unregistered by invoking this function.
28930  * Returns ENXIO if there was no registration.
28931  * Returns EBUSY if the ndd variable has not been turned off.
28932  */
28933 int
28934 ip_cgtp_filter_unregister(netstackid_t stackid)
28935 {
28936 	netstack_t *ns;
28937 	ip_stack_t *ipst;
28938 
28939 	ns = netstack_find_by_stackid(stackid);
28940 	if (ns == NULL)
28941 		return (EINVAL);
28942 	ipst = ns->netstack_ip;
28943 	ASSERT(ipst != NULL);
28944 
28945 	if (ipst->ips_ip_cgtp_filter) {
28946 		netstack_rele(ns);
28947 		return (EBUSY);
28948 	}
28949 
28950 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
28951 		netstack_rele(ns);
28952 		return (ENXIO);
28953 	}
28954 	ipst->ips_ip_cgtp_filter_ops = NULL;
28955 	netstack_rele(ns);
28956 	return (0);
28957 }
28958 
28959 /*
28960  * Check whether there is a CGTP filter registration.
28961  * Returns non-zero if there is a registration, otherwise returns zero.
28962  * Note: returns zero if bad stackid.
28963  */
28964 int
28965 ip_cgtp_filter_is_registered(netstackid_t stackid)
28966 {
28967 	netstack_t *ns;
28968 	ip_stack_t *ipst;
28969 	int ret;
28970 
28971 	ns = netstack_find_by_stackid(stackid);
28972 	if (ns == NULL)
28973 		return (0);
28974 	ipst = ns->netstack_ip;
28975 	ASSERT(ipst != NULL);
28976 
28977 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
28978 		ret = 1;
28979 	else
28980 		ret = 0;
28981 
28982 	netstack_rele(ns);
28983 	return (ret);
28984 }
28985 
28986 static int
28987 ip_squeue_switch(int val)
28988 {
28989 	int rval = SQ_FILL;
28990 
28991 	switch (val) {
28992 	case IP_SQUEUE_ENTER_NODRAIN:
28993 		rval = SQ_NODRAIN;
28994 		break;
28995 	case IP_SQUEUE_ENTER:
28996 		rval = SQ_PROCESS;
28997 		break;
28998 	default:
28999 		break;
29000 	}
29001 	return (rval);
29002 }
29003 
29004 /* ARGSUSED */
29005 static int
29006 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29007     caddr_t addr, cred_t *cr)
29008 {
29009 	int *v = (int *)addr;
29010 	long new_value;
29011 
29012 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29013 		return (EPERM);
29014 
29015 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29016 		return (EINVAL);
29017 
29018 	ip_squeue_flag = ip_squeue_switch(new_value);
29019 	*v = new_value;
29020 	return (0);
29021 }
29022 
29023 /*
29024  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29025  * ip_debug.
29026  */
29027 /* ARGSUSED */
29028 static int
29029 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29030     caddr_t addr, cred_t *cr)
29031 {
29032 	int *v = (int *)addr;
29033 	long new_value;
29034 
29035 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29036 		return (EPERM);
29037 
29038 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29039 		return (EINVAL);
29040 
29041 	*v = new_value;
29042 	return (0);
29043 }
29044 
29045 static void *
29046 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29047 {
29048 	kstat_t *ksp;
29049 
29050 	ip_stat_t template = {
29051 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29052 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29053 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29054 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29055 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29056 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29057 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29058 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29059 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29060 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29061 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29062 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29063 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29064 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29065 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29066 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29067 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29068 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29069 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29070 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29071 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29072 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29073 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29074 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29075 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29076 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29077 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29078 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29079 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29080 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29081 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29082 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29083 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29084 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29085 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29086 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29087 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29088 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29089 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29090 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29091 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29092 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29093 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29094 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29095 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29096 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29097 	};
29098 
29099 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29100 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29101 	    KSTAT_FLAG_VIRTUAL, stackid);
29102 
29103 	if (ksp == NULL)
29104 		return (NULL);
29105 
29106 	bcopy(&template, ip_statisticsp, sizeof (template));
29107 	ksp->ks_data = (void *)ip_statisticsp;
29108 	ksp->ks_private = (void *)(uintptr_t)stackid;
29109 
29110 	kstat_install(ksp);
29111 	return (ksp);
29112 }
29113 
29114 static void
29115 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29116 {
29117 	if (ksp != NULL) {
29118 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29119 		kstat_delete_netstack(ksp, stackid);
29120 	}
29121 }
29122 
29123 static void *
29124 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29125 {
29126 	kstat_t	*ksp;
29127 
29128 	ip_named_kstat_t template = {
29129 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29130 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29131 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29132 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29133 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29134 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29135 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29136 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29137 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29138 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29139 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29140 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29141 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29142 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29143 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29144 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29145 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29146 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29147 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29148 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29149 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29150 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29151 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29152 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29153 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29154 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29155 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29156 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29157 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29158 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29159 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29160 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29161 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29162 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29163 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29164 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29165 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29166 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29167 	};
29168 
29169 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29170 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29171 	if (ksp == NULL || ksp->ks_data == NULL)
29172 		return (NULL);
29173 
29174 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29175 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29176 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29177 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29178 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29179 
29180 	template.netToMediaEntrySize.value.i32 =
29181 	    sizeof (mib2_ipNetToMediaEntry_t);
29182 
29183 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29184 
29185 	bcopy(&template, ksp->ks_data, sizeof (template));
29186 	ksp->ks_update = ip_kstat_update;
29187 	ksp->ks_private = (void *)(uintptr_t)stackid;
29188 
29189 	kstat_install(ksp);
29190 	return (ksp);
29191 }
29192 
29193 static void
29194 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29195 {
29196 	if (ksp != NULL) {
29197 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29198 		kstat_delete_netstack(ksp, stackid);
29199 	}
29200 }
29201 
29202 static int
29203 ip_kstat_update(kstat_t *kp, int rw)
29204 {
29205 	ip_named_kstat_t *ipkp;
29206 	mib2_ipIfStatsEntry_t ipmib;
29207 	ill_walk_context_t ctx;
29208 	ill_t *ill;
29209 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29210 	netstack_t	*ns;
29211 	ip_stack_t	*ipst;
29212 
29213 	if (kp == NULL || kp->ks_data == NULL)
29214 		return (EIO);
29215 
29216 	if (rw == KSTAT_WRITE)
29217 		return (EACCES);
29218 
29219 	ns = netstack_find_by_stackid(stackid);
29220 	if (ns == NULL)
29221 		return (-1);
29222 	ipst = ns->netstack_ip;
29223 	if (ipst == NULL) {
29224 		netstack_rele(ns);
29225 		return (-1);
29226 	}
29227 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29228 
29229 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29230 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29231 	ill = ILL_START_WALK_V4(&ctx, ipst);
29232 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29233 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29234 	rw_exit(&ipst->ips_ill_g_lock);
29235 
29236 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29237 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29238 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29239 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29240 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29241 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29242 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29243 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29244 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29245 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29246 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29247 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29248 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29249 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29250 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29251 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29252 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29253 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29254 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29255 
29256 	ipkp->routingDiscards.value.ui32 =	0;
29257 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29258 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29259 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29260 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29261 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29262 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29263 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29264 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29265 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29266 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29267 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29268 
29269 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29270 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29271 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29272 
29273 	netstack_rele(ns);
29274 
29275 	return (0);
29276 }
29277 
29278 static void *
29279 icmp_kstat_init(netstackid_t stackid)
29280 {
29281 	kstat_t	*ksp;
29282 
29283 	icmp_named_kstat_t template = {
29284 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29285 		{ "inErrors",		KSTAT_DATA_UINT32 },
29286 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29287 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29288 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29289 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29290 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29291 		{ "inEchos",		KSTAT_DATA_UINT32 },
29292 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29293 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29294 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29295 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29296 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29297 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29298 		{ "outErrors",		KSTAT_DATA_UINT32 },
29299 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29300 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29301 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29302 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29303 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29304 		{ "outEchos",		KSTAT_DATA_UINT32 },
29305 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29306 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29307 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29308 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29309 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29310 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29311 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29312 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29313 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29314 		{ "outDrops",		KSTAT_DATA_UINT32 },
29315 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29316 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29317 	};
29318 
29319 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29320 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29321 	if (ksp == NULL || ksp->ks_data == NULL)
29322 		return (NULL);
29323 
29324 	bcopy(&template, ksp->ks_data, sizeof (template));
29325 
29326 	ksp->ks_update = icmp_kstat_update;
29327 	ksp->ks_private = (void *)(uintptr_t)stackid;
29328 
29329 	kstat_install(ksp);
29330 	return (ksp);
29331 }
29332 
29333 static void
29334 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29335 {
29336 	if (ksp != NULL) {
29337 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29338 		kstat_delete_netstack(ksp, stackid);
29339 	}
29340 }
29341 
29342 static int
29343 icmp_kstat_update(kstat_t *kp, int rw)
29344 {
29345 	icmp_named_kstat_t *icmpkp;
29346 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29347 	netstack_t	*ns;
29348 	ip_stack_t	*ipst;
29349 
29350 	if ((kp == NULL) || (kp->ks_data == NULL))
29351 		return (EIO);
29352 
29353 	if (rw == KSTAT_WRITE)
29354 		return (EACCES);
29355 
29356 	ns = netstack_find_by_stackid(stackid);
29357 	if (ns == NULL)
29358 		return (-1);
29359 	ipst = ns->netstack_ip;
29360 	if (ipst == NULL) {
29361 		netstack_rele(ns);
29362 		return (-1);
29363 	}
29364 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29365 
29366 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29367 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29368 	icmpkp->inDestUnreachs.value.ui32 =
29369 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29370 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29371 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29372 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29373 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29374 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29375 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29376 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29377 	icmpkp->inTimestampReps.value.ui32 =
29378 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29379 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29380 	icmpkp->inAddrMaskReps.value.ui32 =
29381 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29382 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29383 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29384 	icmpkp->outDestUnreachs.value.ui32 =
29385 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29386 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29387 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29388 	icmpkp->outSrcQuenchs.value.ui32 =
29389 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29390 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29391 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29392 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29393 	icmpkp->outTimestamps.value.ui32 =
29394 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29395 	icmpkp->outTimestampReps.value.ui32 =
29396 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29397 	icmpkp->outAddrMasks.value.ui32 =
29398 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29399 	icmpkp->outAddrMaskReps.value.ui32 =
29400 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29401 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29402 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29403 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29404 	icmpkp->outFragNeeded.value.ui32 =
29405 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29406 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29407 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29408 	icmpkp->inBadRedirects.value.ui32 =
29409 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29410 
29411 	netstack_rele(ns);
29412 	return (0);
29413 }
29414 
29415 /*
29416  * This is the fanout function for raw socket opened for SCTP.  Note
29417  * that it is called after SCTP checks that there is no socket which
29418  * wants a packet.  Then before SCTP handles this out of the blue packet,
29419  * this function is called to see if there is any raw socket for SCTP.
29420  * If there is and it is bound to the correct address, the packet will
29421  * be sent to that socket.  Note that only one raw socket can be bound to
29422  * a port.  This is assured in ipcl_sctp_hash_insert();
29423  */
29424 void
29425 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29426     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29427     zoneid_t zoneid)
29428 {
29429 	conn_t		*connp;
29430 	queue_t		*rq;
29431 	mblk_t		*first_mp;
29432 	boolean_t	secure;
29433 	ip6_t		*ip6h;
29434 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29435 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29436 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29437 	boolean_t	sctp_csum_err = B_FALSE;
29438 
29439 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29440 		sctp_csum_err = B_TRUE;
29441 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29442 	}
29443 
29444 	first_mp = mp;
29445 	if (mctl_present) {
29446 		mp = first_mp->b_cont;
29447 		secure = ipsec_in_is_secure(first_mp);
29448 		ASSERT(mp != NULL);
29449 	} else {
29450 		secure = B_FALSE;
29451 	}
29452 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29453 
29454 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29455 	if (connp == NULL) {
29456 		/*
29457 		 * Although raw sctp is not summed, OOB chunks must be.
29458 		 * Drop the packet here if the sctp checksum failed.
29459 		 */
29460 		if (sctp_csum_err) {
29461 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29462 			freemsg(first_mp);
29463 			return;
29464 		}
29465 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29466 		return;
29467 	}
29468 	rq = connp->conn_rq;
29469 	if (!canputnext(rq)) {
29470 		CONN_DEC_REF(connp);
29471 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29472 		freemsg(first_mp);
29473 		return;
29474 	}
29475 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29476 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29477 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29478 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29479 		if (first_mp == NULL) {
29480 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29481 			CONN_DEC_REF(connp);
29482 			return;
29483 		}
29484 	}
29485 	/*
29486 	 * We probably should not send M_CTL message up to
29487 	 * raw socket.
29488 	 */
29489 	if (mctl_present)
29490 		freeb(first_mp);
29491 
29492 	/* Initiate IPPF processing here if needed. */
29493 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29494 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29495 		ip_process(IPP_LOCAL_IN, &mp,
29496 		    recv_ill->ill_phyint->phyint_ifindex);
29497 		if (mp == NULL) {
29498 			CONN_DEC_REF(connp);
29499 			return;
29500 		}
29501 	}
29502 
29503 	if (connp->conn_recvif || connp->conn_recvslla ||
29504 	    ((connp->conn_ip_recvpktinfo ||
29505 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29506 	    (flags & IP_FF_IPINFO))) {
29507 		int in_flags = 0;
29508 
29509 		/*
29510 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29511 		 * IPF_RECVIF.
29512 		 */
29513 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29514 			in_flags = IPF_RECVIF;
29515 		}
29516 		if (connp->conn_recvslla) {
29517 			in_flags |= IPF_RECVSLLA;
29518 		}
29519 		if (isv4) {
29520 			mp = ip_add_info(mp, recv_ill, in_flags,
29521 			    IPCL_ZONEID(connp), ipst);
29522 		} else {
29523 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29524 			if (mp == NULL) {
29525 				BUMP_MIB(recv_ill->ill_ip_mib,
29526 				    ipIfStatsInDiscards);
29527 				CONN_DEC_REF(connp);
29528 				return;
29529 			}
29530 		}
29531 	}
29532 
29533 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29534 	/*
29535 	 * We are sending the IPSEC_IN message also up. Refer
29536 	 * to comments above this function.
29537 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29538 	 */
29539 	(connp->conn_recv)(connp, mp, NULL);
29540 	CONN_DEC_REF(connp);
29541 }
29542 
29543 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29544 {									\
29545 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29546 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29547 }
29548 /*
29549  * This function should be called only if all packet processing
29550  * including fragmentation is complete. Callers of this function
29551  * must set mp->b_prev to one of these values:
29552  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29553  * prior to handing over the mp as first argument to this function.
29554  *
29555  * If the ire passed by caller is incomplete, this function
29556  * queues the packet and if necessary, sends ARP request and bails.
29557  * If the ire passed is fully resolved, we simply prepend
29558  * the link-layer header to the packet, do ipsec hw acceleration
29559  * work if necessary, and send the packet out on the wire.
29560  *
29561  * NOTE: IPsec will only call this function with fully resolved
29562  * ires if hw acceleration is involved.
29563  * TODO list :
29564  * 	a Handle M_MULTIDATA so that
29565  *	  tcp_multisend->tcp_multisend_data can
29566  *	  call ip_xmit_v4 directly
29567  *	b Handle post-ARP work for fragments so that
29568  *	  ip_wput_frag can call this function.
29569  */
29570 ipxmit_state_t
29571 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io,
29572     boolean_t flow_ctl_enabled, conn_t *connp)
29573 {
29574 	nce_t		*arpce;
29575 	ipha_t		*ipha;
29576 	queue_t		*q;
29577 	int		ill_index;
29578 	mblk_t		*nxt_mp, *first_mp;
29579 	boolean_t	xmit_drop = B_FALSE;
29580 	ip_proc_t	proc;
29581 	ill_t		*out_ill;
29582 	int		pkt_len;
29583 
29584 	arpce = ire->ire_nce;
29585 	ASSERT(arpce != NULL);
29586 
29587 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29588 
29589 	mutex_enter(&arpce->nce_lock);
29590 	switch (arpce->nce_state) {
29591 	case ND_REACHABLE:
29592 		/* If there are other queued packets, queue this packet */
29593 		if (arpce->nce_qd_mp != NULL) {
29594 			if (mp != NULL)
29595 				nce_queue_mp_common(arpce, mp, B_FALSE);
29596 			mp = arpce->nce_qd_mp;
29597 		}
29598 		arpce->nce_qd_mp = NULL;
29599 		mutex_exit(&arpce->nce_lock);
29600 
29601 		/*
29602 		 * Flush the queue.  In the common case, where the
29603 		 * ARP is already resolved,  it will go through the
29604 		 * while loop only once.
29605 		 */
29606 		while (mp != NULL) {
29607 
29608 			nxt_mp = mp->b_next;
29609 			mp->b_next = NULL;
29610 			ASSERT(mp->b_datap->db_type != M_CTL);
29611 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29612 			/*
29613 			 * This info is needed for IPQOS to do COS marking
29614 			 * in ip_wput_attach_llhdr->ip_process.
29615 			 */
29616 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29617 			mp->b_prev = NULL;
29618 
29619 			/* set up ill index for outbound qos processing */
29620 			out_ill = ire_to_ill(ire);
29621 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29622 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29623 			    ill_index, &ipha);
29624 			if (first_mp == NULL) {
29625 				xmit_drop = B_TRUE;
29626 				BUMP_MIB(out_ill->ill_ip_mib,
29627 				    ipIfStatsOutDiscards);
29628 				goto next_mp;
29629 			}
29630 
29631 			/* non-ipsec hw accel case */
29632 			if (io == NULL || !io->ipsec_out_accelerated) {
29633 				/* send it */
29634 				q = ire->ire_stq;
29635 				if (proc == IPP_FWD_OUT) {
29636 					UPDATE_IB_PKT_COUNT(ire);
29637 				} else {
29638 					UPDATE_OB_PKT_COUNT(ire);
29639 				}
29640 				ire->ire_last_used_time = lbolt;
29641 
29642 				if (flow_ctl_enabled || canputnext(q)) {
29643 					if (proc == IPP_FWD_OUT) {
29644 
29645 					BUMP_MIB(out_ill->ill_ip_mib,
29646 					    ipIfStatsHCOutForwDatagrams);
29647 
29648 					}
29649 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29650 					    pkt_len);
29651 
29652 					DTRACE_IP7(send, mblk_t *, first_mp,
29653 					    conn_t *, NULL, void_ip_t *, ipha,
29654 					    __dtrace_ipsr_ill_t *, out_ill,
29655 					    ipha_t *, ipha, ip6_t *, NULL, int,
29656 					    0);
29657 
29658 					ILL_SEND_TX(out_ill,
29659 					    ire, connp, first_mp, 0);
29660 				} else {
29661 					BUMP_MIB(out_ill->ill_ip_mib,
29662 					    ipIfStatsOutDiscards);
29663 					xmit_drop = B_TRUE;
29664 					freemsg(first_mp);
29665 				}
29666 			} else {
29667 				/*
29668 				 * Safety Pup says: make sure this
29669 				 *  is going to the right interface!
29670 				 */
29671 				ill_t *ill1 =
29672 				    (ill_t *)ire->ire_stq->q_ptr;
29673 				int ifindex =
29674 				    ill1->ill_phyint->phyint_ifindex;
29675 				if (ifindex !=
29676 				    io->ipsec_out_capab_ill_index) {
29677 					xmit_drop = B_TRUE;
29678 					freemsg(mp);
29679 				} else {
29680 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29681 					    pkt_len);
29682 
29683 					DTRACE_IP7(send, mblk_t *, first_mp,
29684 					    conn_t *, NULL, void_ip_t *, ipha,
29685 					    __dtrace_ipsr_ill_t *, ill1,
29686 					    ipha_t *, ipha, ip6_t *, NULL,
29687 					    int, 0);
29688 
29689 					ipsec_hw_putnext(ire->ire_stq, mp);
29690 				}
29691 			}
29692 next_mp:
29693 			mp = nxt_mp;
29694 		} /* while (mp != NULL) */
29695 		if (xmit_drop)
29696 			return (SEND_FAILED);
29697 		else
29698 			return (SEND_PASSED);
29699 
29700 	case ND_INITIAL:
29701 	case ND_INCOMPLETE:
29702 
29703 		/*
29704 		 * While we do send off packets to dests that
29705 		 * use fully-resolved CGTP routes, we do not
29706 		 * handle unresolved CGTP routes.
29707 		 */
29708 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29709 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29710 
29711 		if (mp != NULL) {
29712 			/* queue the packet */
29713 			nce_queue_mp_common(arpce, mp, B_FALSE);
29714 		}
29715 
29716 		if (arpce->nce_state == ND_INCOMPLETE) {
29717 			mutex_exit(&arpce->nce_lock);
29718 			DTRACE_PROBE3(ip__xmit__incomplete,
29719 			    (ire_t *), ire, (mblk_t *), mp,
29720 			    (ipsec_out_t *), io);
29721 			return (LOOKUP_IN_PROGRESS);
29722 		}
29723 
29724 		arpce->nce_state = ND_INCOMPLETE;
29725 		mutex_exit(&arpce->nce_lock);
29726 
29727 		/*
29728 		 * Note that ire_add() (called from ire_forward())
29729 		 * holds a ref on the ire until ARP is completed.
29730 		 */
29731 		ire_arpresolve(ire);
29732 		return (LOOKUP_IN_PROGRESS);
29733 	default:
29734 		ASSERT(0);
29735 		mutex_exit(&arpce->nce_lock);
29736 		return (LLHDR_RESLV_FAILED);
29737 	}
29738 }
29739 
29740 #undef	UPDATE_IP_MIB_OB_COUNTERS
29741 
29742 /*
29743  * Return B_TRUE if the buffers differ in length or content.
29744  * This is used for comparing extension header buffers.
29745  * Note that an extension header would be declared different
29746  * even if all that changed was the next header value in that header i.e.
29747  * what really changed is the next extension header.
29748  */
29749 boolean_t
29750 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29751     uint_t blen)
29752 {
29753 	if (!b_valid)
29754 		blen = 0;
29755 
29756 	if (alen != blen)
29757 		return (B_TRUE);
29758 	if (alen == 0)
29759 		return (B_FALSE);	/* Both zero length */
29760 	return (bcmp(abuf, bbuf, alen));
29761 }
29762 
29763 /*
29764  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29765  * Return B_FALSE if memory allocation fails - don't change any state!
29766  */
29767 boolean_t
29768 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29769     const void *src, uint_t srclen)
29770 {
29771 	void *dst;
29772 
29773 	if (!src_valid)
29774 		srclen = 0;
29775 
29776 	ASSERT(*dstlenp == 0);
29777 	if (src != NULL && srclen != 0) {
29778 		dst = mi_alloc(srclen, BPRI_MED);
29779 		if (dst == NULL)
29780 			return (B_FALSE);
29781 	} else {
29782 		dst = NULL;
29783 	}
29784 	if (*dstp != NULL)
29785 		mi_free(*dstp);
29786 	*dstp = dst;
29787 	*dstlenp = dst == NULL ? 0 : srclen;
29788 	return (B_TRUE);
29789 }
29790 
29791 /*
29792  * Replace what is in *dst, *dstlen with the source.
29793  * Assumes ip_allocbuf has already been called.
29794  */
29795 void
29796 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29797     const void *src, uint_t srclen)
29798 {
29799 	if (!src_valid)
29800 		srclen = 0;
29801 
29802 	ASSERT(*dstlenp == srclen);
29803 	if (src != NULL && srclen != 0)
29804 		bcopy(src, *dstp, srclen);
29805 }
29806 
29807 /*
29808  * Free the storage pointed to by the members of an ip6_pkt_t.
29809  */
29810 void
29811 ip6_pkt_free(ip6_pkt_t *ipp)
29812 {
29813 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29814 
29815 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29816 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
29817 		ipp->ipp_hopopts = NULL;
29818 		ipp->ipp_hopoptslen = 0;
29819 	}
29820 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29821 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29822 		ipp->ipp_rtdstopts = NULL;
29823 		ipp->ipp_rtdstoptslen = 0;
29824 	}
29825 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
29826 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
29827 		ipp->ipp_dstopts = NULL;
29828 		ipp->ipp_dstoptslen = 0;
29829 	}
29830 	if (ipp->ipp_fields & IPPF_RTHDR) {
29831 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29832 		ipp->ipp_rthdr = NULL;
29833 		ipp->ipp_rthdrlen = 0;
29834 	}
29835 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
29836 	    IPPF_RTHDR);
29837 }
29838 
29839 zoneid_t
29840 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_stack_t *ipst,
29841     zoneid_t lookup_zoneid)
29842 {
29843 	ire_t		*ire;
29844 	int		ire_flags = MATCH_IRE_TYPE;
29845 	zoneid_t	zoneid = ALL_ZONES;
29846 
29847 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
29848 		return (ALL_ZONES);
29849 
29850 	if (lookup_zoneid != ALL_ZONES)
29851 		ire_flags |= MATCH_IRE_ZONEONLY;
29852 	ire = ire_ctable_lookup(addr, NULL, IRE_LOCAL | IRE_LOOPBACK, NULL,
29853 	    lookup_zoneid, NULL, ire_flags, ipst);
29854 	if (ire != NULL) {
29855 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
29856 		ire_refrele(ire);
29857 	}
29858 	return (zoneid);
29859 }
29860 
29861 zoneid_t
29862 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
29863     ip_stack_t *ipst, zoneid_t lookup_zoneid)
29864 {
29865 	ire_t		*ire;
29866 	int		ire_flags = MATCH_IRE_TYPE;
29867 	zoneid_t	zoneid = ALL_ZONES;
29868 	ipif_t		*ipif_arg = NULL;
29869 
29870 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
29871 		return (ALL_ZONES);
29872 
29873 	if (IN6_IS_ADDR_LINKLOCAL(addr)) {
29874 		ire_flags |= MATCH_IRE_ILL;
29875 		ipif_arg = ill->ill_ipif;
29876 	}
29877 	if (lookup_zoneid != ALL_ZONES)
29878 		ire_flags |= MATCH_IRE_ZONEONLY;
29879 	ire = ire_ctable_lookup_v6(addr, NULL, IRE_LOCAL | IRE_LOOPBACK,
29880 	    ipif_arg, lookup_zoneid, NULL, ire_flags, ipst);
29881 	if (ire != NULL) {
29882 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
29883 		ire_refrele(ire);
29884 	}
29885 	return (zoneid);
29886 }
29887 
29888 /*
29889  * IP obserability hook support functions.
29890  */
29891 
29892 static void
29893 ipobs_init(ip_stack_t *ipst)
29894 {
29895 	ipst->ips_ipobs_enabled = B_FALSE;
29896 	list_create(&ipst->ips_ipobs_cb_list, sizeof (ipobs_cb_t),
29897 	    offsetof(ipobs_cb_t, ipobs_cbnext));
29898 	mutex_init(&ipst->ips_ipobs_cb_lock, NULL, MUTEX_DEFAULT, NULL);
29899 	ipst->ips_ipobs_cb_nwalkers = 0;
29900 	cv_init(&ipst->ips_ipobs_cb_cv, NULL, CV_DRIVER, NULL);
29901 }
29902 
29903 static void
29904 ipobs_fini(ip_stack_t *ipst)
29905 {
29906 	ipobs_cb_t *cb;
29907 
29908 	mutex_enter(&ipst->ips_ipobs_cb_lock);
29909 	while (ipst->ips_ipobs_cb_nwalkers != 0)
29910 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
29911 
29912 	while ((cb = list_head(&ipst->ips_ipobs_cb_list)) != NULL) {
29913 		list_remove(&ipst->ips_ipobs_cb_list, cb);
29914 		kmem_free(cb, sizeof (*cb));
29915 	}
29916 	list_destroy(&ipst->ips_ipobs_cb_list);
29917 	mutex_exit(&ipst->ips_ipobs_cb_lock);
29918 	mutex_destroy(&ipst->ips_ipobs_cb_lock);
29919 	cv_destroy(&ipst->ips_ipobs_cb_cv);
29920 }
29921 
29922 void
29923 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
29924     const ill_t *ill, int ipver, uint32_t hlen, ip_stack_t *ipst)
29925 {
29926 	mblk_t *mp2;
29927 	ipobs_cb_t *ipobs_cb;
29928 	ipobs_hook_data_t *ihd;
29929 	uint64_t grifindex = 0;
29930 
29931 	ASSERT(DB_TYPE(mp) == M_DATA);
29932 
29933 	if (IS_UNDER_IPMP(ill))
29934 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
29935 
29936 	mutex_enter(&ipst->ips_ipobs_cb_lock);
29937 	ipst->ips_ipobs_cb_nwalkers++;
29938 	mutex_exit(&ipst->ips_ipobs_cb_lock);
29939 	for (ipobs_cb = list_head(&ipst->ips_ipobs_cb_list); ipobs_cb != NULL;
29940 	    ipobs_cb = list_next(&ipst->ips_ipobs_cb_list, ipobs_cb)) {
29941 		mp2 = allocb(sizeof (ipobs_hook_data_t), BPRI_HI);
29942 		if (mp2 != NULL) {
29943 			ihd = (ipobs_hook_data_t *)mp2->b_rptr;
29944 			if (((ihd->ihd_mp = dupmsg(mp)) == NULL) &&
29945 			    ((ihd->ihd_mp = copymsg(mp)) == NULL)) {
29946 				freemsg(mp2);
29947 				continue;
29948 			}
29949 			ihd->ihd_mp->b_rptr += hlen;
29950 			ihd->ihd_htype = htype;
29951 			ihd->ihd_ipver = ipver;
29952 			ihd->ihd_zsrc = zsrc;
29953 			ihd->ihd_zdst = zdst;
29954 			ihd->ihd_ifindex = ill->ill_phyint->phyint_ifindex;
29955 			ihd->ihd_grifindex = grifindex;
29956 			ihd->ihd_stack = ipst->ips_netstack;
29957 			mp2->b_wptr += sizeof (*ihd);
29958 			ipobs_cb->ipobs_cbfunc(mp2);
29959 		}
29960 	}
29961 	mutex_enter(&ipst->ips_ipobs_cb_lock);
29962 	ipst->ips_ipobs_cb_nwalkers--;
29963 	if (ipst->ips_ipobs_cb_nwalkers == 0)
29964 		cv_broadcast(&ipst->ips_ipobs_cb_cv);
29965 	mutex_exit(&ipst->ips_ipobs_cb_lock);
29966 }
29967 
29968 void
29969 ipobs_register_hook(netstack_t *ns, pfv_t func)
29970 {
29971 	ipobs_cb_t   *cb;
29972 	ip_stack_t *ipst = ns->netstack_ip;
29973 
29974 	cb = kmem_alloc(sizeof (*cb), KM_SLEEP);
29975 
29976 	mutex_enter(&ipst->ips_ipobs_cb_lock);
29977 	while (ipst->ips_ipobs_cb_nwalkers != 0)
29978 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
29979 	ASSERT(ipst->ips_ipobs_cb_nwalkers == 0);
29980 
29981 	cb->ipobs_cbfunc = func;
29982 	list_insert_head(&ipst->ips_ipobs_cb_list, cb);
29983 	ipst->ips_ipobs_enabled = B_TRUE;
29984 	mutex_exit(&ipst->ips_ipobs_cb_lock);
29985 }
29986 
29987 void
29988 ipobs_unregister_hook(netstack_t *ns, pfv_t func)
29989 {
29990 	ipobs_cb_t	*curcb;
29991 	ip_stack_t	*ipst = ns->netstack_ip;
29992 
29993 	mutex_enter(&ipst->ips_ipobs_cb_lock);
29994 	while (ipst->ips_ipobs_cb_nwalkers != 0)
29995 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
29996 
29997 	for (curcb = list_head(&ipst->ips_ipobs_cb_list); curcb != NULL;
29998 	    curcb = list_next(&ipst->ips_ipobs_cb_list, curcb)) {
29999 		if (func == curcb->ipobs_cbfunc) {
30000 			list_remove(&ipst->ips_ipobs_cb_list, curcb);
30001 			kmem_free(curcb, sizeof (*curcb));
30002 			break;
30003 		}
30004 	}
30005 	if (list_is_empty(&ipst->ips_ipobs_cb_list))
30006 		ipst->ips_ipobs_enabled = B_FALSE;
30007 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30008 }
30009