xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 7ce76caa61769eef87a2368b9ef90e4661e3f193)
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 2008 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 	listptr_t	ird_route;	/* ipRouteEntryTable */
174 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
175 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
176 } iproutedata_t;
177 
178 /*
179  * Cluster specific hooks. These should be NULL when booted as a non-cluster
180  */
181 
182 /*
183  * Hook functions to enable cluster networking
184  * On non-clustered systems these vectors must always be NULL.
185  *
186  * Hook function to Check ip specified ip address is a shared ip address
187  * in the cluster
188  *
189  */
190 int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
191     sa_family_t addr_family, uint8_t *laddrp, void *args) = NULL;
192 
193 /*
194  * Hook function to generate cluster wide ip fragment identifier
195  */
196 uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
197     sa_family_t addr_family, uint8_t *laddrp, uint8_t *faddrp,
198     void *args) = NULL;
199 
200 /*
201  * Hook function to generate cluster wide SPI.
202  */
203 void (*cl_inet_getspi)(netstackid_t, uint8_t, uint8_t *, size_t,
204     void *) = NULL;
205 
206 /*
207  * Hook function to verify if the SPI is already utlized.
208  */
209 
210 int (*cl_inet_checkspi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
211 
212 /*
213  * Hook function to delete the SPI from the cluster wide repository.
214  */
215 
216 void (*cl_inet_deletespi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
217 
218 /*
219  * Hook function to inform the cluster when packet received on an IDLE SA
220  */
221 
222 void (*cl_inet_idlesa)(netstackid_t, uint8_t, uint32_t, sa_family_t,
223     in6_addr_t, in6_addr_t, void *) = NULL;
224 
225 /*
226  * Synchronization notes:
227  *
228  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
229  * MT level protection given by STREAMS. IP uses a combination of its own
230  * internal serialization mechanism and standard Solaris locking techniques.
231  * The internal serialization is per phyint (no IPMP) or per IPMP group.
232  * This is used to serialize plumbing operations, IPMP operations, certain
233  * multicast operations, most set ioctls, igmp/mld timers etc.
234  *
235  * Plumbing is a long sequence of operations involving message
236  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
237  * involved in plumbing operations. A natural model is to serialize these
238  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
239  * parallel without any interference. But various set ioctls on hme0 are best
240  * serialized. However if the system uses IPMP, the operations are easier if
241  * they are serialized on a per IPMP group basis since IPMP operations
242  * happen across ill's of a group. Thus the lowest common denominator is to
243  * serialize most set ioctls, multicast join/leave operations, IPMP operations
244  * igmp/mld timer operations, and processing of DLPI control messages received
245  * from drivers on a per IPMP group basis. If the system does not employ
246  * IPMP the serialization is on a per phyint basis. This serialization is
247  * provided by the ipsq_t and primitives operating on this. Details can
248  * be found in ip_if.c above the core primitives operating on ipsq_t.
249  *
250  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
251  * Simiarly lookup of an ire by a thread also returns a refheld ire.
252  * In addition ipif's and ill's referenced by the ire are also indirectly
253  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
254  * the ipif's address or netmask change as long as an ipif is refheld
255  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
256  * address of an ipif has to go through the ipsq_t. This ensures that only
257  * 1 such exclusive operation proceeds at any time on the ipif. It then
258  * deletes all ires associated with this ipif, and waits for all refcnts
259  * associated with this ipif to come down to zero. The address is changed
260  * only after the ipif has been quiesced. Then the ipif is brought up again.
261  * More details are described above the comment in ip_sioctl_flags.
262  *
263  * Packet processing is based mostly on IREs and are fully multi-threaded
264  * using standard Solaris MT techniques.
265  *
266  * There are explicit locks in IP to handle:
267  * - The ip_g_head list maintained by mi_open_link() and friends.
268  *
269  * - The reassembly data structures (one lock per hash bucket)
270  *
271  * - conn_lock is meant to protect conn_t fields. The fields actually
272  *   protected by conn_lock are documented in the conn_t definition.
273  *
274  * - ire_lock to protect some of the fields of the ire, IRE tables
275  *   (one lock per hash bucket). Refer to ip_ire.c for details.
276  *
277  * - ndp_g_lock and nce_lock for protecting NCEs.
278  *
279  * - ill_lock protects fields of the ill and ipif. Details in ip.h
280  *
281  * - ill_g_lock: This is a global reader/writer lock. Protects the following
282  *	* The AVL tree based global multi list of all ills.
283  *	* The linked list of all ipifs of an ill
284  *	* The <ill-ipsq> mapping
285  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
286  *	* The illgroup list threaded by ill_group_next.
287  *	* <ill-phyint> association
288  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
289  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
290  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
291  *   will all have to hold the ill_g_lock as writer for the actual duration
292  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
293  *   may be found in the IPMP section.
294  *
295  * - ill_lock:  This is a per ill mutex.
296  *   It protects some members of the ill and is documented below.
297  *   It also protects the <ill-ipsq> mapping
298  *   It also protects the illgroup list threaded by ill_group_next.
299  *   It also protects the <ill-phyint> assoc.
300  *   It also protects the list of ipifs hanging off the ill.
301  *
302  * - ipsq_lock: This is a per ipsq_t mutex lock.
303  *   This protects all the other members of the ipsq struct except
304  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
305  *
306  * - illgrp_lock: This is a per ill_group mutex lock.
307  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
308  *   which dictates which is the next ill in an ill_group that is to be chosen
309  *   for sending outgoing packets, through creation of an IRE_CACHE that
310  *   references this ill.
311  *
312  * - phyint_lock: This is a per phyint mutex lock. Protects just the
313  *   phyint_flags
314  *
315  * - ip_g_nd_lock: This is a global reader/writer lock.
316  *   Any call to nd_load to load a new parameter to the ND table must hold the
317  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
318  *   as reader.
319  *
320  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
321  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
322  *   uniqueness check also done atomically.
323  *
324  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
325  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
326  *   as a writer when adding or deleting elements from these lists, and
327  *   as a reader when walking these lists to send a SADB update to the
328  *   IPsec capable ills.
329  *
330  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
331  *   group list linked by ill_usesrc_grp_next. It also protects the
332  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
333  *   group is being added or deleted.  This lock is taken as a reader when
334  *   walking the list/group(eg: to get the number of members in a usesrc group).
335  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
336  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
337  *   example, it is not necessary to take this lock in the initial portion
338  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
339  *   ip_sioctl_flags since the these operations are executed exclusively and
340  *   that ensures that the "usesrc group state" cannot change. The "usesrc
341  *   group state" change can happen only in the latter part of
342  *   ip_sioctl_slifusesrc and in ill_delete.
343  *
344  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
345  *
346  * To change the <ill-phyint> association, the ill_g_lock must be held
347  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
348  * must be held.
349  *
350  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
351  * and the ill_lock of the ill in question must be held.
352  *
353  * To change the <ill-illgroup> association the ill_g_lock must be held as
354  * writer and the ill_lock of the ill in question must be held.
355  *
356  * To add or delete an ipif from the list of ipifs hanging off the ill,
357  * ill_g_lock (writer) and ill_lock must be held and the thread must be
358  * a writer on the associated ipsq,.
359  *
360  * To add or delete an ill to the system, the ill_g_lock must be held as
361  * writer and the thread must be a writer on the associated ipsq.
362  *
363  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
364  * must be a writer on the associated ipsq.
365  *
366  * Lock hierarchy
367  *
368  * Some lock hierarchy scenarios are listed below.
369  *
370  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
371  * ill_g_lock -> illgrp_lock -> ill_lock
372  * ill_g_lock -> ill_lock(s) -> phyint_lock
373  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
374  * ill_g_lock -> ip_addr_avail_lock
375  * conn_lock -> irb_lock -> ill_lock -> ire_lock
376  * ill_g_lock -> ip_g_nd_lock
377  *
378  * When more than 1 ill lock is needed to be held, all ill lock addresses
379  * are sorted on address and locked starting from highest addressed lock
380  * downward.
381  *
382  * IPsec scenarios
383  *
384  * ipsa_lock -> ill_g_lock -> ill_lock
385  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
386  * ipsec_capab_ills_lock -> ipsa_lock
387  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
388  *
389  * Trusted Solaris scenarios
390  *
391  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
392  * igsa_lock -> gcdb_lock
393  * gcgrp_rwlock -> ire_lock
394  * gcgrp_rwlock -> gcdb_lock
395  *
396  * squeue(sq_lock), flow related (ft_lock, fe_lock) locking
397  *
398  * cpu_lock --> ill_lock --> sqset_lock --> sq_lock
399  * sq_lock -> conn_lock -> QLOCK(q)
400  * ill_lock -> ft_lock -> fe_lock
401  *
402  * Routing/forwarding table locking notes:
403  *
404  * Lock acquisition order: Radix tree lock, irb_lock.
405  * Requirements:
406  * i.  Walker must not hold any locks during the walker callback.
407  * ii  Walker must not see a truncated tree during the walk because of any node
408  *     deletion.
409  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
410  *     in many places in the code to walk the irb list. Thus even if all the
411  *     ires in a bucket have been deleted, we still can't free the radix node
412  *     until the ires have actually been inactive'd (freed).
413  *
414  * Tree traversal - Need to hold the global tree lock in read mode.
415  * Before dropping the global tree lock, need to either increment the ire_refcnt
416  * to ensure that the radix node can't be deleted.
417  *
418  * Tree add - Need to hold the global tree lock in write mode to add a
419  * radix node. To prevent the node from being deleted, increment the
420  * irb_refcnt, after the node is added to the tree. The ire itself is
421  * added later while holding the irb_lock, but not the tree lock.
422  *
423  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
424  * All associated ires must be inactive (i.e. freed), and irb_refcnt
425  * must be zero.
426  *
427  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
428  * global tree lock (read mode) for traversal.
429  *
430  * IPsec notes :
431  *
432  * IP interacts with the IPsec code (AH/ESP) by tagging a M_CTL message
433  * in front of the actual packet. For outbound datagrams, the M_CTL
434  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
435  * information used by the IPsec code for applying the right level of
436  * protection. The information initialized by IP in the ipsec_out_t
437  * is determined by the per-socket policy or global policy in the system.
438  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
439  * ipsec_info.h) which starts out with nothing in it. It gets filled
440  * with the right information if it goes through the AH/ESP code, which
441  * happens if the incoming packet is secure. The information initialized
442  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
443  * the policy requirements needed by per-socket policy or global policy
444  * is met or not.
445  *
446  * If there is both per-socket policy (set using setsockopt) and there
447  * is also global policy match for the 5 tuples of the socket,
448  * ipsec_override_policy() makes the decision of which one to use.
449  *
450  * For fully connected sockets i.e dst, src [addr, port] is known,
451  * conn_policy_cached is set indicating that policy has been cached.
452  * conn_in_enforce_policy may or may not be set depending on whether
453  * there is a global policy match or per-socket policy match.
454  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
455  * Once the right policy is set on the conn_t, policy cannot change for
456  * this socket. This makes life simpler for TCP (UDP ?) where
457  * re-transmissions go out with the same policy. For symmetry, policy
458  * is cached for fully connected UDP sockets also. Thus if policy is cached,
459  * it also implies that policy is latched i.e policy cannot change
460  * on these sockets. As we have the right policy on the conn, we don't
461  * have to lookup global policy for every outbound and inbound datagram
462  * and thus serving as an optimization. Note that a global policy change
463  * does not affect fully connected sockets if they have policy. If fully
464  * connected sockets did not have any policy associated with it, global
465  * policy change may affect them.
466  *
467  * IP Flow control notes:
468  *
469  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
470  * cannot be sent down to the driver by IP, because of a canput failure, IP
471  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
472  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
473  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
474  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
475  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
476  * the queued messages, and removes the conn from the drain list, if all
477  * messages were drained. It also qenables the next conn in the drain list to
478  * continue the drain process.
479  *
480  * In reality the drain list is not a single list, but a configurable number
481  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
482  * list. If the ip_wsrv of the next qenabled conn does not run, because the
483  * stream closes, ip_close takes responsibility to qenable the next conn in
484  * the drain list. The directly called ip_wput path always does a putq, if
485  * it cannot putnext. Thus synchronization problems are handled between
486  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
487  * functions that manipulate this drain list. Furthermore conn_drain_insert
488  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
489  * running on a queue at any time. conn_drain_tail can be simultaneously called
490  * from both ip_wsrv and ip_close.
491  *
492  * IPQOS notes:
493  *
494  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
495  * and IPQoS modules. IPPF includes hooks in IP at different control points
496  * (callout positions) which direct packets to IPQoS modules for policy
497  * processing. Policies, if present, are global.
498  *
499  * The callout positions are located in the following paths:
500  *		o local_in (packets destined for this host)
501  *		o local_out (packets orginating from this host )
502  *		o fwd_in  (packets forwarded by this m/c - inbound)
503  *		o fwd_out (packets forwarded by this m/c - outbound)
504  * Hooks at these callout points can be enabled/disabled using the ndd variable
505  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
506  * By default all the callout positions are enabled.
507  *
508  * Outbound (local_out)
509  * Hooks are placed in ip_wput_ire and ipsec_out_process.
510  *
511  * Inbound (local_in)
512  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
513  * TCP and UDP fanout routines.
514  *
515  * Forwarding (in and out)
516  * Hooks are placed in ip_rput_forward.
517  *
518  * IP Policy Framework processing (IPPF processing)
519  * Policy processing for a packet is initiated by ip_process, which ascertains
520  * that the classifier (ipgpc) is loaded and configured, failing which the
521  * packet resumes normal processing in IP. If the clasifier is present, the
522  * packet is acted upon by one or more IPQoS modules (action instances), per
523  * filters configured in ipgpc and resumes normal IP processing thereafter.
524  * An action instance can drop a packet in course of its processing.
525  *
526  * A boolean variable, ip_policy, is used in all the fanout routines that can
527  * invoke ip_process for a packet. This variable indicates if the packet should
528  * to be sent for policy processing. The variable is set to B_TRUE by default,
529  * i.e. when the routines are invoked in the normal ip procesing path for a
530  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
531  * ip_policy is set to B_FALSE for all the routines called in these two
532  * functions because, in the former case,  we don't process loopback traffic
533  * currently while in the latter, the packets have already been processed in
534  * icmp_inbound.
535  *
536  * Zones notes:
537  *
538  * The partitioning rules for networking are as follows:
539  * 1) Packets coming from a zone must have a source address belonging to that
540  * zone.
541  * 2) Packets coming from a zone can only be sent on a physical interface on
542  * which the zone has an IP address.
543  * 3) Between two zones on the same machine, packet delivery is only allowed if
544  * there's a matching route for the destination and zone in the forwarding
545  * table.
546  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
547  * different zones can bind to the same port with the wildcard address
548  * (INADDR_ANY).
549  *
550  * The granularity of interface partitioning is at the logical interface level.
551  * Therefore, every zone has its own IP addresses, and incoming packets can be
552  * attributed to a zone unambiguously. A logical interface is placed into a zone
553  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
554  * structure. Rule (1) is implemented by modifying the source address selection
555  * algorithm so that the list of eligible addresses is filtered based on the
556  * sending process zone.
557  *
558  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
559  * across all zones, depending on their type. Here is the break-up:
560  *
561  * IRE type				Shared/exclusive
562  * --------				----------------
563  * IRE_BROADCAST			Exclusive
564  * IRE_DEFAULT (default routes)		Shared (*)
565  * IRE_LOCAL				Exclusive (x)
566  * IRE_LOOPBACK				Exclusive
567  * IRE_PREFIX (net routes)		Shared (*)
568  * IRE_CACHE				Exclusive
569  * IRE_IF_NORESOLVER (interface routes)	Exclusive
570  * IRE_IF_RESOLVER (interface routes)	Exclusive
571  * IRE_HOST (host routes)		Shared (*)
572  *
573  * (*) A zone can only use a default or off-subnet route if the gateway is
574  * directly reachable from the zone, that is, if the gateway's address matches
575  * one of the zone's logical interfaces.
576  *
577  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
578  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
579  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
580  * address of the zone itself (the destination). Since IRE_LOCAL is used
581  * for communication between zones, ip_wput_ire has special logic to set
582  * the right source address when sending using an IRE_LOCAL.
583  *
584  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
585  * ire_cache_lookup restricts loopback using an IRE_LOCAL
586  * between zone to the case when L2 would have conceptually looped the packet
587  * back, i.e. the loopback which is required since neither Ethernet drivers
588  * nor Ethernet hardware loops them back. This is the case when the normal
589  * routes (ignoring IREs with different zoneids) would send out the packet on
590  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
591  * associated.
592  *
593  * Multiple zones can share a common broadcast address; typically all zones
594  * share the 255.255.255.255 address. Incoming as well as locally originated
595  * broadcast packets must be dispatched to all the zones on the broadcast
596  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
597  * since some zones may not be on the 10.16.72/24 network. To handle this, each
598  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
599  * sent to every zone that has an IRE_BROADCAST entry for the destination
600  * address on the input ill, see conn_wantpacket().
601  *
602  * Applications in different zones can join the same multicast group address.
603  * For IPv4, group memberships are per-logical interface, so they're already
604  * inherently part of a zone. For IPv6, group memberships are per-physical
605  * interface, so we distinguish IPv6 group memberships based on group address,
606  * interface and zoneid. In both cases, received multicast packets are sent to
607  * every zone for which a group membership entry exists. On IPv6 we need to
608  * check that the target zone still has an address on the receiving physical
609  * interface; it could have been removed since the application issued the
610  * IPV6_JOIN_GROUP.
611  */
612 
613 /*
614  * Squeue Fanout flags:
615  *	0: No fanout.
616  *	1: Fanout across all squeues
617  */
618 boolean_t	ip_squeue_fanout = 0;
619 
620 /*
621  * Maximum dups allowed per packet.
622  */
623 uint_t ip_max_frag_dups = 10;
624 
625 #define	IS_SIMPLE_IPH(ipha)						\
626 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
627 
628 /* RFC 1122 Conformance */
629 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
630 
631 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
632 
633 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
634 
635 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
636 		    cred_t *credp, boolean_t isv6);
637 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t,
638 		    ipha_t **);
639 
640 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
641 		    ip_stack_t *);
642 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
643 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
644 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
645 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
646 		    mblk_t *, int, ip_stack_t *);
647 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
648 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
649 		    ill_t *, zoneid_t);
650 static void	icmp_options_update(ipha_t *);
651 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
652 		    ip_stack_t *);
653 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
654 		    zoneid_t zoneid, ip_stack_t *);
655 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
656 static void	icmp_redirect(ill_t *, mblk_t *);
657 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
658 		    ip_stack_t *);
659 
660 static void	ip_arp_news(queue_t *, mblk_t *);
661 static boolean_t ip_bind_get_ire_v4(mblk_t **, ire_t *, iulp_t *, ip_stack_t *);
662 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
663 char		*ip_dot_addr(ipaddr_t, char *);
664 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
665 int		ip_close(queue_t *, int);
666 static char	*ip_dot_saddr(uchar_t *, char *);
667 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
668 		    boolean_t, boolean_t, ill_t *, zoneid_t);
669 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
670 		    boolean_t, boolean_t, zoneid_t);
671 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
672 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
673 static void	ip_lrput(queue_t *, mblk_t *);
674 ipaddr_t	ip_net_mask(ipaddr_t);
675 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
676 		    ip_stack_t *);
677 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
678 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
679 char		*ip_nv_lookup(nv_t *, int);
680 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
681 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
682 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
683 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
684     ipndp_t *, size_t);
685 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
686 void	ip_rput(queue_t *, mblk_t *);
687 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
688 		    void *dummy_arg);
689 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
690 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
691     ip_stack_t *);
692 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
693 			    ire_t *, ip_stack_t *);
694 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
695 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
696 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
697     ip_stack_t *);
698 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
699 		    uint16_t *);
700 int		ip_snmp_get(queue_t *, mblk_t *, int);
701 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
702 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
703 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
704 		    ip_stack_t *);
705 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
706 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
707 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
708 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
709 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
710 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
711 		    ip_stack_t *ipst);
712 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
713 		    ip_stack_t *ipst);
714 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
715 		    ip_stack_t *ipst);
716 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
717 		    ip_stack_t *ipst);
718 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
719 		    ip_stack_t *ipst);
720 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
721 		    ip_stack_t *ipst);
722 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
723 		    ip_stack_t *ipst);
724 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
725 		    ip_stack_t *ipst);
726 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *,
727 		    ip_stack_t *ipst);
728 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *,
729 		    ip_stack_t *ipst);
730 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
731 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
732 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
733 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
734 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
735 static boolean_t	ip_source_route_included(ipha_t *);
736 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
737 
738 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
739 		    zoneid_t, ip_stack_t *, conn_t *);
740 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *);
741 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
742 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
743 		    zoneid_t, ip_stack_t *);
744 
745 static void	conn_drain_init(ip_stack_t *);
746 static void	conn_drain_fini(ip_stack_t *);
747 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
748 
749 static void	conn_walk_drain(ip_stack_t *);
750 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
751     zoneid_t);
752 
753 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
754 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
755 static void	ip_stack_fini(netstackid_t stackid, void *arg);
756 
757 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
758     zoneid_t);
759 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
760     void *dummy_arg);
761 
762 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
763 
764 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
765     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
766     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
767 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
768 
769 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
770 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
771     caddr_t, cred_t *);
772 extern int	ip_helper_stream_setup(queue_t *, dev_t *, int, int,
773     cred_t *, boolean_t);
774 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
775     caddr_t cp, cred_t *cr);
776 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
777     cred_t *);
778 static int	ipmp_hook_emulation_set(queue_t *, mblk_t *, char *, caddr_t,
779     cred_t *);
780 static int	ip_squeue_switch(int);
781 
782 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
783 static void	ip_kstat_fini(netstackid_t, kstat_t *);
784 static int	ip_kstat_update(kstat_t *kp, int rw);
785 static void	*icmp_kstat_init(netstackid_t);
786 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
787 static int	icmp_kstat_update(kstat_t *kp, int rw);
788 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
789 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
790 
791 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
792 
793 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
794     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
795 
796 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
797     ipha_t *, ill_t *, boolean_t, boolean_t);
798 
799 static void ipobs_init(ip_stack_t *);
800 static void ipobs_fini(ip_stack_t *);
801 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
802 
803 /* How long, in seconds, we allow frags to hang around. */
804 #define	IP_FRAG_TIMEOUT	15
805 
806 /*
807  * Threshold which determines whether MDT should be used when
808  * generating IP fragments; payload size must be greater than
809  * this threshold for MDT to take place.
810  */
811 #define	IP_WPUT_FRAG_MDT_MIN	32768
812 
813 /* Setable in /etc/system only */
814 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
815 
816 static long ip_rput_pullups;
817 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
818 
819 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
820 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
821 
822 int	ip_debug;
823 
824 #ifdef DEBUG
825 uint32_t ipsechw_debug = 0;
826 #endif
827 
828 /*
829  * Multirouting/CGTP stuff
830  */
831 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
832 
833 /*
834  * XXX following really should only be in a header. Would need more
835  * header and .c clean up first.
836  */
837 extern optdb_obj_t	ip_opt_obj;
838 
839 ulong_t ip_squeue_enter_unbound = 0;
840 
841 /*
842  * Named Dispatch Parameter Table.
843  * All of these are alterable, within the min/max values given, at run time.
844  */
845 static ipparam_t	lcl_param_arr[] = {
846 	/* min	max	value	name */
847 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
848 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
849 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
850 	{  0,	1,	0,	"ip_respond_to_timestamp"},
851 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
852 	{  0,	1,	1,	"ip_send_redirects"},
853 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
854 	{  0,	10,	0,	"ip_mrtdebug"},
855 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
856 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
857 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
858 	{  1,	255,	255,	"ip_def_ttl" },
859 	{  0,	1,	0,	"ip_forward_src_routed"},
860 	{  0,	256,	32,	"ip_wroff_extra" },
861 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
862 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
863 	{  0,	1,	1,	"ip_path_mtu_discovery" },
864 	{  0,	240,	30,	"ip_ignore_delete_time" },
865 	{  0,	1,	0,	"ip_ignore_redirect" },
866 	{  0,	1,	1,	"ip_output_queue" },
867 	{  1,	254,	1,	"ip_broadcast_ttl" },
868 	{  0,	99999,	100,	"ip_icmp_err_interval" },
869 	{  1,	99999,	10,	"ip_icmp_err_burst" },
870 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
871 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
872 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
873 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
874 	{  0,	1,	1,	"icmp_accept_clear_messages" },
875 	{  0,	1,	1,	"igmp_accept_clear_messages" },
876 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
877 				"ip_ndp_delay_first_probe_time"},
878 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
879 				"ip_ndp_max_unicast_solicit"},
880 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
881 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
882 	{  0,	1,	0,	"ip6_forward_src_routed"},
883 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
884 	{  0,	1,	1,	"ip6_send_redirects"},
885 	{  0,	1,	0,	"ip6_ignore_redirect" },
886 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
887 
888 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
889 
890 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
891 
892 	{  0,	1,	1,	"pim_accept_clear_messages" },
893 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
894 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
895 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
896 	{  0,	15,	0,	"ip_policy_mask" },
897 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
898 	{  0,	255,	1,	"ip_multirt_ttl" },
899 	{  0,	1,	1,	"ip_multidata_outbound" },
900 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
901 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
902 	{  0,	1000,	1,	"ip_max_temp_defend" },
903 	{  0,	1000,	3,	"ip_max_defend" },
904 	{  0,	999999,	30,	"ip_defend_interval" },
905 	{  0,	3600000, 300000, "ip_dup_recovery" },
906 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
907 	{  0,	1,	1,	"ip_lso_outbound" },
908 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
909 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
910 	{ 68,	65535,	576,	"ip_pmtu_min" },
911 #ifdef DEBUG
912 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
913 #else
914 	{  0,	0,	0,	"" },
915 #endif
916 };
917 
918 /*
919  * Extended NDP table
920  * The addresses for the first two are filled in to be ips_ip_g_forward
921  * and ips_ipv6_forward at init time.
922  */
923 static ipndp_t	lcl_ndp_arr[] = {
924 	/* getf			setf		data			name */
925 #define	IPNDP_IP_FORWARDING_OFFSET	0
926 	{  ip_param_generic_get,	ip_forward_set,	NULL,
927 	    "ip_forwarding" },
928 #define	IPNDP_IP6_FORWARDING_OFFSET	1
929 	{  ip_param_generic_get,	ip_forward_set,	NULL,
930 	    "ip6_forwarding" },
931 	{  ip_ill_report,	NULL,		NULL,
932 	    "ip_ill_status" },
933 	{  ip_ipif_report,	NULL,		NULL,
934 	    "ip_ipif_status" },
935 	{  ip_conn_report,	NULL,		NULL,
936 	    "ip_conn_status" },
937 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
938 	    "ip_rput_pullups" },
939 	{  ip_srcid_report,	NULL,		NULL,
940 	    "ip_srcid_status" },
941 	{ ip_param_generic_get, ip_input_proc_set,
942 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
943 	{ ip_param_generic_get, ip_int_set,
944 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
945 #define	IPNDP_CGTP_FILTER_OFFSET	9
946 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
947 	    "ip_cgtp_filter" },
948 #define	IPNDP_IPMP_HOOK_OFFSET		10
949 	{  ip_param_generic_get, ipmp_hook_emulation_set, NULL,
950 	    "ipmp_hook_emulation" },
951 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
952 	    "ip_debug" },
953 };
954 
955 /*
956  * Table of IP ioctls encoding the various properties of the ioctl and
957  * indexed based on the last byte of the ioctl command. Occasionally there
958  * is a clash, and there is more than 1 ioctl with the same last byte.
959  * In such a case 1 ioctl is encoded in the ndx table and the remaining
960  * ioctls are encoded in the misc table. An entry in the ndx table is
961  * retrieved by indexing on the last byte of the ioctl command and comparing
962  * the ioctl command with the value in the ndx table. In the event of a
963  * mismatch the misc table is then searched sequentially for the desired
964  * ioctl command.
965  *
966  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
967  */
968 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
969 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
970 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
971 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
972 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
973 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
974 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
975 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
976 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
977 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
978 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
979 
980 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
981 			MISC_CMD, ip_siocaddrt, NULL },
982 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
983 			MISC_CMD, ip_siocdelrt, NULL },
984 
985 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
986 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
987 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
988 			IF_CMD, ip_sioctl_get_addr, NULL },
989 
990 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
991 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
992 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
993 			IPI_GET_CMD | IPI_REPL,
994 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
995 
996 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
997 			IPI_PRIV | IPI_WR | IPI_REPL,
998 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
999 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1000 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
1001 			IF_CMD, ip_sioctl_get_flags, NULL },
1002 
1003 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1004 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1005 
1006 	/* copyin size cannot be coded for SIOCGIFCONF */
1007 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
1008 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1009 
1010 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1011 			IF_CMD, ip_sioctl_mtu, NULL },
1012 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1013 			IF_CMD, ip_sioctl_get_mtu, NULL },
1014 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1015 			IPI_GET_CMD | IPI_REPL,
1016 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1017 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1018 			IF_CMD, ip_sioctl_brdaddr, NULL },
1019 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1020 			IPI_GET_CMD | IPI_REPL,
1021 			IF_CMD, ip_sioctl_get_netmask, NULL },
1022 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1023 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1024 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1025 			IPI_GET_CMD | IPI_REPL,
1026 			IF_CMD, ip_sioctl_get_metric, NULL },
1027 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1028 			IF_CMD, ip_sioctl_metric, NULL },
1029 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 
1031 	/* See 166-168 below for extended SIOC*XARP ioctls */
1032 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1033 			ARP_CMD, ip_sioctl_arp, NULL },
1034 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1035 			ARP_CMD, ip_sioctl_arp, NULL },
1036 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1037 			ARP_CMD, ip_sioctl_arp, NULL },
1038 
1039 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1040 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1041 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1042 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1060 
1061 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1062 			MISC_CMD, if_unitsel, if_unitsel_restart },
1063 
1064 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1065 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1066 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1079 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1080 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1081 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1082 
1083 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1084 			IPI_PRIV | IPI_WR | IPI_MODOK,
1085 			IF_CMD, ip_sioctl_sifname, NULL },
1086 
1087 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1088 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1089 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1090 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1091 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1092 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1093 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1094 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1095 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1096 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1097 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 
1101 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1102 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1103 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1104 			IF_CMD, ip_sioctl_get_muxid, NULL },
1105 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1106 			IPI_PRIV | IPI_WR | IPI_REPL,
1107 			IF_CMD, ip_sioctl_muxid, NULL },
1108 
1109 	/* Both if and lif variants share same func */
1110 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1111 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1112 	/* Both if and lif variants share same func */
1113 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1114 			IPI_PRIV | IPI_WR | IPI_REPL,
1115 			IF_CMD, ip_sioctl_slifindex, NULL },
1116 
1117 	/* copyin size cannot be coded for SIOCGIFCONF */
1118 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1119 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1120 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1124 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1125 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1126 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1127 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1128 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1129 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1130 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1131 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1132 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1133 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1134 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1135 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1136 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1137 
1138 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1139 			IPI_PRIV | IPI_WR | IPI_REPL,
1140 			LIF_CMD, ip_sioctl_removeif,
1141 			ip_sioctl_removeif_restart },
1142 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1143 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1144 			LIF_CMD, ip_sioctl_addif, NULL },
1145 #define	SIOCLIFADDR_NDX 112
1146 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1147 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1148 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1149 			IPI_GET_CMD | IPI_REPL,
1150 			LIF_CMD, ip_sioctl_get_addr, NULL },
1151 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1152 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1153 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1154 			IPI_GET_CMD | IPI_REPL,
1155 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1156 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1157 			IPI_PRIV | IPI_WR | IPI_REPL,
1158 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1159 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1160 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1161 			LIF_CMD, ip_sioctl_get_flags, NULL },
1162 
1163 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1164 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1165 
1166 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1167 			ip_sioctl_get_lifconf, NULL },
1168 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1169 			LIF_CMD, ip_sioctl_mtu, NULL },
1170 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1171 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1172 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1173 			IPI_GET_CMD | IPI_REPL,
1174 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1175 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1176 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1177 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1178 			IPI_GET_CMD | IPI_REPL,
1179 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1180 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1181 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1182 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1183 			IPI_GET_CMD | IPI_REPL,
1184 			LIF_CMD, ip_sioctl_get_metric, NULL },
1185 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1186 			LIF_CMD, ip_sioctl_metric, NULL },
1187 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1188 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1189 			LIF_CMD, ip_sioctl_slifname,
1190 			ip_sioctl_slifname_restart },
1191 
1192 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1193 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1194 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1195 			IPI_GET_CMD | IPI_REPL,
1196 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1197 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1198 			IPI_PRIV | IPI_WR | IPI_REPL,
1199 			LIF_CMD, ip_sioctl_muxid, NULL },
1200 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1201 			IPI_GET_CMD | IPI_REPL,
1202 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1203 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1204 			IPI_PRIV | IPI_WR | IPI_REPL,
1205 			LIF_CMD, ip_sioctl_slifindex, 0 },
1206 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1207 			LIF_CMD, ip_sioctl_token, NULL },
1208 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1209 			IPI_GET_CMD | IPI_REPL,
1210 			LIF_CMD, ip_sioctl_get_token, NULL },
1211 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1212 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1213 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1214 			IPI_GET_CMD | IPI_REPL,
1215 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1216 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1217 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1218 
1219 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1220 			IPI_GET_CMD | IPI_REPL,
1221 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1222 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1223 			LIF_CMD, ip_siocdelndp_v6, NULL },
1224 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1225 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1226 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1227 			LIF_CMD, ip_siocsetndp_v6, NULL },
1228 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1229 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1230 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1231 			MISC_CMD, ip_sioctl_tonlink, NULL },
1232 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1233 			MISC_CMD, ip_sioctl_tmysite, NULL },
1234 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1235 		    TUN_CMD, ip_sioctl_tunparam, NULL },
1236 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1237 		    IPI_PRIV | IPI_WR,
1238 		    TUN_CMD, ip_sioctl_tunparam, NULL },
1239 
1240 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1241 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1242 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1243 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1244 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1245 
1246 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1247 			IPI_PRIV | IPI_WR | IPI_REPL,
1248 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1249 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1250 			IPI_PRIV | IPI_WR | IPI_REPL,
1251 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1252 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1253 			IPI_PRIV | IPI_WR | IPI_REPL,
1254 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1255 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1256 			IPI_GET_CMD | IPI_REPL,
1257 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1258 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1259 			IPI_GET_CMD | IPI_REPL,
1260 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1261 
1262 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1263 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1264 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1265 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1266 
1267 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1268 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1269 
1270 	/* These are handled in ip_sioctl_copyin_setup itself */
1271 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1272 			MISC_CMD, NULL, NULL },
1273 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1274 			MISC_CMD, NULL, NULL },
1275 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1276 
1277 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1278 			ip_sioctl_get_lifconf, NULL },
1279 
1280 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1281 			XARP_CMD, ip_sioctl_arp, NULL },
1282 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1283 			XARP_CMD, ip_sioctl_arp, NULL },
1284 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1285 			XARP_CMD, ip_sioctl_arp, NULL },
1286 
1287 	/* SIOCPOPSOCKFS is not handled by IP */
1288 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1289 
1290 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1291 			IPI_GET_CMD | IPI_REPL,
1292 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1293 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1294 			IPI_PRIV | IPI_WR | IPI_REPL,
1295 			LIF_CMD, ip_sioctl_slifzone,
1296 			ip_sioctl_slifzone_restart },
1297 	/* 172-174 are SCTP ioctls and not handled by IP */
1298 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1299 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1300 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1301 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1302 			IPI_GET_CMD, LIF_CMD,
1303 			ip_sioctl_get_lifusesrc, 0 },
1304 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1305 			IPI_PRIV | IPI_WR,
1306 			LIF_CMD, ip_sioctl_slifusesrc,
1307 			NULL },
1308 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1309 			ip_sioctl_get_lifsrcof, NULL },
1310 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1311 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1312 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1313 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1314 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1315 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1316 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1317 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1318 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1319 			ip_sioctl_set_ipmpfailback, NULL },
1320 	/* SIOCSENABLESDP is handled by SDP */
1321 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1322 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1323 };
1324 
1325 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1326 
1327 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1328 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1329 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1330 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1331 		TUN_CMD, ip_sioctl_tunparam, NULL },
1332 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1333 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1334 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1335 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1336 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1337 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1338 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1339 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1340 		MISC_CMD, mrt_ioctl},
1341 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1342 		MISC_CMD, mrt_ioctl},
1343 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1344 		MISC_CMD, mrt_ioctl}
1345 };
1346 
1347 int ip_misc_ioctl_count =
1348     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1349 
1350 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1351 					/* Settable in /etc/system */
1352 /* Defined in ip_ire.c */
1353 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1354 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1355 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1356 
1357 static nv_t	ire_nv_arr[] = {
1358 	{ IRE_BROADCAST, "BROADCAST" },
1359 	{ IRE_LOCAL, "LOCAL" },
1360 	{ IRE_LOOPBACK, "LOOPBACK" },
1361 	{ IRE_CACHE, "CACHE" },
1362 	{ IRE_DEFAULT, "DEFAULT" },
1363 	{ IRE_PREFIX, "PREFIX" },
1364 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1365 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1366 	{ IRE_HOST, "HOST" },
1367 	{ 0 }
1368 };
1369 
1370 nv_t	*ire_nv_tbl = ire_nv_arr;
1371 
1372 /* Simple ICMP IP Header Template */
1373 static ipha_t icmp_ipha = {
1374 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1375 };
1376 
1377 struct module_info ip_mod_info = {
1378 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1379 	IP_MOD_LOWAT
1380 };
1381 
1382 /*
1383  * Duplicate static symbols within a module confuses mdb; so we avoid the
1384  * problem by making the symbols here distinct from those in udp.c.
1385  */
1386 
1387 /*
1388  * Entry points for IP as a device and as a module.
1389  * FIXME: down the road we might want a separate module and driver qinit.
1390  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1391  */
1392 static struct qinit iprinitv4 = {
1393 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1394 	&ip_mod_info
1395 };
1396 
1397 struct qinit iprinitv6 = {
1398 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1399 	&ip_mod_info
1400 };
1401 
1402 static struct qinit ipwinitv4 = {
1403 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1404 	&ip_mod_info
1405 };
1406 
1407 struct qinit ipwinitv6 = {
1408 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1409 	&ip_mod_info
1410 };
1411 
1412 static struct qinit iplrinit = {
1413 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1414 	&ip_mod_info
1415 };
1416 
1417 static struct qinit iplwinit = {
1418 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1419 	&ip_mod_info
1420 };
1421 
1422 /* For AF_INET aka /dev/ip */
1423 struct streamtab ipinfov4 = {
1424 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1425 };
1426 
1427 /* For AF_INET6 aka /dev/ip6 */
1428 struct streamtab ipinfov6 = {
1429 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1430 };
1431 
1432 #ifdef	DEBUG
1433 static boolean_t skip_sctp_cksum = B_FALSE;
1434 #endif
1435 
1436 /*
1437  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1438  * ip_rput_v6(), ip_output(), etc.  If the message
1439  * block already has a M_CTL at the front of it, then simply set the zoneid
1440  * appropriately.
1441  */
1442 mblk_t *
1443 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1444 {
1445 	mblk_t		*first_mp;
1446 	ipsec_out_t	*io;
1447 
1448 	ASSERT(zoneid != ALL_ZONES);
1449 	if (mp->b_datap->db_type == M_CTL) {
1450 		io = (ipsec_out_t *)mp->b_rptr;
1451 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1452 		io->ipsec_out_zoneid = zoneid;
1453 		return (mp);
1454 	}
1455 
1456 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1457 	if (first_mp == NULL)
1458 		return (NULL);
1459 	io = (ipsec_out_t *)first_mp->b_rptr;
1460 	/* This is not a secure packet */
1461 	io->ipsec_out_secure = B_FALSE;
1462 	io->ipsec_out_zoneid = zoneid;
1463 	first_mp->b_cont = mp;
1464 	return (first_mp);
1465 }
1466 
1467 /*
1468  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1469  */
1470 mblk_t *
1471 ip_copymsg(mblk_t *mp)
1472 {
1473 	mblk_t *nmp;
1474 	ipsec_info_t *in;
1475 
1476 	if (mp->b_datap->db_type != M_CTL)
1477 		return (copymsg(mp));
1478 
1479 	in = (ipsec_info_t *)mp->b_rptr;
1480 
1481 	/*
1482 	 * Note that M_CTL is also used for delivering ICMP error messages
1483 	 * upstream to transport layers.
1484 	 */
1485 	if (in->ipsec_info_type != IPSEC_OUT &&
1486 	    in->ipsec_info_type != IPSEC_IN)
1487 		return (copymsg(mp));
1488 
1489 	nmp = copymsg(mp->b_cont);
1490 
1491 	if (in->ipsec_info_type == IPSEC_OUT) {
1492 		return (ipsec_out_tag(mp, nmp,
1493 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1494 	} else {
1495 		return (ipsec_in_tag(mp, nmp,
1496 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1497 	}
1498 }
1499 
1500 /* Generate an ICMP fragmentation needed message. */
1501 static void
1502 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1503     ip_stack_t *ipst)
1504 {
1505 	icmph_t	icmph;
1506 	mblk_t *first_mp;
1507 	boolean_t mctl_present;
1508 
1509 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1510 
1511 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1512 		if (mctl_present)
1513 			freeb(first_mp);
1514 		return;
1515 	}
1516 
1517 	bzero(&icmph, sizeof (icmph_t));
1518 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1519 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1520 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1521 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1522 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1523 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1524 	    ipst);
1525 }
1526 
1527 /*
1528  * icmp_inbound deals with ICMP messages in the following ways.
1529  *
1530  * 1) It needs to send a reply back and possibly delivering it
1531  *    to the "interested" upper clients.
1532  * 2) It needs to send it to the upper clients only.
1533  * 3) It needs to change some values in IP only.
1534  * 4) It needs to change some values in IP and upper layers e.g TCP.
1535  *
1536  * We need to accomodate icmp messages coming in clear until we get
1537  * everything secure from the wire. If icmp_accept_clear_messages
1538  * is zero we check with the global policy and act accordingly. If
1539  * it is non-zero, we accept the message without any checks. But
1540  * *this does not mean* that this will be delivered to the upper
1541  * clients. By accepting we might send replies back, change our MTU
1542  * value etc. but delivery to the ULP/clients depends on their policy
1543  * dispositions.
1544  *
1545  * We handle the above 4 cases in the context of IPsec in the
1546  * following way :
1547  *
1548  * 1) Send the reply back in the same way as the request came in.
1549  *    If it came in encrypted, it goes out encrypted. If it came in
1550  *    clear, it goes out in clear. Thus, this will prevent chosen
1551  *    plain text attack.
1552  * 2) The client may or may not expect things to come in secure.
1553  *    If it comes in secure, the policy constraints are checked
1554  *    before delivering it to the upper layers. If it comes in
1555  *    clear, ipsec_inbound_accept_clear will decide whether to
1556  *    accept this in clear or not. In both the cases, if the returned
1557  *    message (IP header + 8 bytes) that caused the icmp message has
1558  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1559  *    sending up. If there are only 8 bytes of returned message, then
1560  *    upper client will not be notified.
1561  * 3) Check with global policy to see whether it matches the constaints.
1562  *    But this will be done only if icmp_accept_messages_in_clear is
1563  *    zero.
1564  * 4) If we need to change both in IP and ULP, then the decision taken
1565  *    while affecting the values in IP and while delivering up to TCP
1566  *    should be the same.
1567  *
1568  * 	There are two cases.
1569  *
1570  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1571  *	   failed), we will not deliver it to the ULP, even though they
1572  *	   are *willing* to accept in *clear*. This is fine as our global
1573  *	   disposition to icmp messages asks us reject the datagram.
1574  *
1575  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1576  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1577  *	   to deliver it to ULP (policy failed), it can lead to
1578  *	   consistency problems. The cases known at this time are
1579  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1580  *	   values :
1581  *
1582  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1583  *	     and Upper layer rejects. Then the communication will
1584  *	     come to a stop. This is solved by making similar decisions
1585  *	     at both levels. Currently, when we are unable to deliver
1586  *	     to the Upper Layer (due to policy failures) while IP has
1587  *	     adjusted ire_max_frag, the next outbound datagram would
1588  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1589  *	     will be with the right level of protection. Thus the right
1590  *	     value will be communicated even if we are not able to
1591  *	     communicate when we get from the wire initially. But this
1592  *	     assumes there would be at least one outbound datagram after
1593  *	     IP has adjusted its ire_max_frag value. To make things
1594  *	     simpler, we accept in clear after the validation of
1595  *	     AH/ESP headers.
1596  *
1597  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1598  *	     upper layer depending on the level of protection the upper
1599  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1600  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1601  *	     should be accepted in clear when the Upper layer expects secure.
1602  *	     Thus the communication may get aborted by some bad ICMP
1603  *	     packets.
1604  *
1605  * IPQoS Notes:
1606  * The only instance when a packet is sent for processing is when there
1607  * isn't an ICMP client and if we are interested in it.
1608  * If there is a client, IPPF processing will take place in the
1609  * ip_fanout_proto routine.
1610  *
1611  * Zones notes:
1612  * The packet is only processed in the context of the specified zone: typically
1613  * only this zone will reply to an echo request, and only interested clients in
1614  * this zone will receive a copy of the packet. This means that the caller must
1615  * call icmp_inbound() for each relevant zone.
1616  */
1617 static void
1618 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1619     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1620     ill_t *recv_ill, zoneid_t zoneid)
1621 {
1622 	icmph_t	*icmph;
1623 	ipha_t	*ipha;
1624 	int	iph_hdr_length;
1625 	int	hdr_length;
1626 	boolean_t	interested;
1627 	uint32_t	ts;
1628 	uchar_t	*wptr;
1629 	ipif_t	*ipif;
1630 	mblk_t *first_mp;
1631 	ipsec_in_t *ii;
1632 	ire_t *src_ire;
1633 	boolean_t onlink;
1634 	timestruc_t now;
1635 	uint32_t ill_index;
1636 	ip_stack_t *ipst;
1637 
1638 	ASSERT(ill != NULL);
1639 	ipst = ill->ill_ipst;
1640 
1641 	first_mp = mp;
1642 	if (mctl_present) {
1643 		mp = first_mp->b_cont;
1644 		ASSERT(mp != NULL);
1645 	}
1646 
1647 	ipha = (ipha_t *)mp->b_rptr;
1648 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1649 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1650 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1651 		if (first_mp == NULL)
1652 			return;
1653 	}
1654 
1655 	/*
1656 	 * On a labeled system, we have to check whether the zone itself is
1657 	 * permitted to receive raw traffic.
1658 	 */
1659 	if (is_system_labeled()) {
1660 		if (zoneid == ALL_ZONES)
1661 			zoneid = tsol_packet_to_zoneid(mp);
1662 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1663 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1664 			    zoneid));
1665 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1666 			freemsg(first_mp);
1667 			return;
1668 		}
1669 	}
1670 
1671 	/*
1672 	 * We have accepted the ICMP message. It means that we will
1673 	 * respond to the packet if needed. It may not be delivered
1674 	 * to the upper client depending on the policy constraints
1675 	 * and the disposition in ipsec_inbound_accept_clear.
1676 	 */
1677 
1678 	ASSERT(ill != NULL);
1679 
1680 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1681 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1682 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1683 		/* Last chance to get real. */
1684 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1685 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1686 			freemsg(first_mp);
1687 			return;
1688 		}
1689 		/* Refresh iph following the pullup. */
1690 		ipha = (ipha_t *)mp->b_rptr;
1691 	}
1692 	/* ICMP header checksum, including checksum field, should be zero. */
1693 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1694 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1695 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1696 		freemsg(first_mp);
1697 		return;
1698 	}
1699 	/* The IP header will always be a multiple of four bytes */
1700 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1701 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1702 	    icmph->icmph_code));
1703 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1704 	/* We will set "interested" to "true" if we want a copy */
1705 	interested = B_FALSE;
1706 	switch (icmph->icmph_type) {
1707 	case ICMP_ECHO_REPLY:
1708 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1709 		break;
1710 	case ICMP_DEST_UNREACHABLE:
1711 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1712 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1713 		interested = B_TRUE;	/* Pass up to transport */
1714 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1715 		break;
1716 	case ICMP_SOURCE_QUENCH:
1717 		interested = B_TRUE;	/* Pass up to transport */
1718 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1719 		break;
1720 	case ICMP_REDIRECT:
1721 		if (!ipst->ips_ip_ignore_redirect)
1722 			interested = B_TRUE;
1723 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1724 		break;
1725 	case ICMP_ECHO_REQUEST:
1726 		/*
1727 		 * Whether to respond to echo requests that come in as IP
1728 		 * broadcasts or as IP multicast is subject to debate
1729 		 * (what isn't?).  We aim to please, you pick it.
1730 		 * Default is do it.
1731 		 */
1732 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1733 			/* unicast: always respond */
1734 			interested = B_TRUE;
1735 		} else if (CLASSD(ipha->ipha_dst)) {
1736 			/* multicast: respond based on tunable */
1737 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1738 		} else if (broadcast) {
1739 			/* broadcast: respond based on tunable */
1740 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1741 		}
1742 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1743 		break;
1744 	case ICMP_ROUTER_ADVERTISEMENT:
1745 	case ICMP_ROUTER_SOLICITATION:
1746 		break;
1747 	case ICMP_TIME_EXCEEDED:
1748 		interested = B_TRUE;	/* Pass up to transport */
1749 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1750 		break;
1751 	case ICMP_PARAM_PROBLEM:
1752 		interested = B_TRUE;	/* Pass up to transport */
1753 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1754 		break;
1755 	case ICMP_TIME_STAMP_REQUEST:
1756 		/* Response to Time Stamp Requests is local policy. */
1757 		if (ipst->ips_ip_g_resp_to_timestamp &&
1758 		    /* So is whether to respond if it was an IP broadcast. */
1759 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1760 			int tstamp_len = 3 * sizeof (uint32_t);
1761 
1762 			if (wptr +  tstamp_len > mp->b_wptr) {
1763 				if (!pullupmsg(mp, wptr + tstamp_len -
1764 				    mp->b_rptr)) {
1765 					BUMP_MIB(ill->ill_ip_mib,
1766 					    ipIfStatsInDiscards);
1767 					freemsg(first_mp);
1768 					return;
1769 				}
1770 				/* Refresh ipha following the pullup. */
1771 				ipha = (ipha_t *)mp->b_rptr;
1772 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1773 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1774 			}
1775 			interested = B_TRUE;
1776 		}
1777 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1778 		break;
1779 	case ICMP_TIME_STAMP_REPLY:
1780 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1781 		break;
1782 	case ICMP_INFO_REQUEST:
1783 		/* Per RFC 1122 3.2.2.7, ignore this. */
1784 	case ICMP_INFO_REPLY:
1785 		break;
1786 	case ICMP_ADDRESS_MASK_REQUEST:
1787 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1788 		    !broadcast) &&
1789 		    /* TODO m_pullup of complete header? */
1790 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1791 			interested = B_TRUE;
1792 		}
1793 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1794 		break;
1795 	case ICMP_ADDRESS_MASK_REPLY:
1796 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1797 		break;
1798 	default:
1799 		interested = B_TRUE;	/* Pass up to transport */
1800 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1801 		break;
1802 	}
1803 	/* See if there is an ICMP client. */
1804 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1805 		/* If there is an ICMP client and we want one too, copy it. */
1806 		mblk_t *first_mp1;
1807 
1808 		if (!interested) {
1809 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1810 			    ip_policy, recv_ill, zoneid);
1811 			return;
1812 		}
1813 		first_mp1 = ip_copymsg(first_mp);
1814 		if (first_mp1 != NULL) {
1815 			ip_fanout_proto(q, first_mp1, ill, ipha,
1816 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1817 		}
1818 	} else if (!interested) {
1819 		freemsg(first_mp);
1820 		return;
1821 	} else {
1822 		/*
1823 		 * Initiate policy processing for this packet if ip_policy
1824 		 * is true.
1825 		 */
1826 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1827 			ill_index = ill->ill_phyint->phyint_ifindex;
1828 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1829 			if (mp == NULL) {
1830 				if (mctl_present) {
1831 					freeb(first_mp);
1832 				}
1833 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1834 				return;
1835 			}
1836 		}
1837 	}
1838 	/* We want to do something with it. */
1839 	/* Check db_ref to make sure we can modify the packet. */
1840 	if (mp->b_datap->db_ref > 1) {
1841 		mblk_t	*first_mp1;
1842 
1843 		first_mp1 = ip_copymsg(first_mp);
1844 		freemsg(first_mp);
1845 		if (!first_mp1) {
1846 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1847 			return;
1848 		}
1849 		first_mp = first_mp1;
1850 		if (mctl_present) {
1851 			mp = first_mp->b_cont;
1852 			ASSERT(mp != NULL);
1853 		} else {
1854 			mp = first_mp;
1855 		}
1856 		ipha = (ipha_t *)mp->b_rptr;
1857 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1858 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1859 	}
1860 	switch (icmph->icmph_type) {
1861 	case ICMP_ADDRESS_MASK_REQUEST:
1862 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1863 		if (ipif == NULL) {
1864 			freemsg(first_mp);
1865 			return;
1866 		}
1867 		/*
1868 		 * outging interface must be IPv4
1869 		 */
1870 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1871 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1872 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1873 		ipif_refrele(ipif);
1874 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1875 		break;
1876 	case ICMP_ECHO_REQUEST:
1877 		icmph->icmph_type = ICMP_ECHO_REPLY;
1878 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1879 		break;
1880 	case ICMP_TIME_STAMP_REQUEST: {
1881 		uint32_t *tsp;
1882 
1883 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1884 		tsp = (uint32_t *)wptr;
1885 		tsp++;		/* Skip past 'originate time' */
1886 		/* Compute # of milliseconds since midnight */
1887 		gethrestime(&now);
1888 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1889 		    now.tv_nsec / (NANOSEC / MILLISEC);
1890 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1891 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1892 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1893 		break;
1894 	}
1895 	default:
1896 		ipha = (ipha_t *)&icmph[1];
1897 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1898 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1899 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1900 				freemsg(first_mp);
1901 				return;
1902 			}
1903 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1904 			ipha = (ipha_t *)&icmph[1];
1905 		}
1906 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1907 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1908 			freemsg(first_mp);
1909 			return;
1910 		}
1911 		hdr_length = IPH_HDR_LENGTH(ipha);
1912 		if (hdr_length < sizeof (ipha_t)) {
1913 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1914 			freemsg(first_mp);
1915 			return;
1916 		}
1917 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1918 			if (!pullupmsg(mp,
1919 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1920 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1921 				freemsg(first_mp);
1922 				return;
1923 			}
1924 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1925 			ipha = (ipha_t *)&icmph[1];
1926 		}
1927 		switch (icmph->icmph_type) {
1928 		case ICMP_REDIRECT:
1929 			/*
1930 			 * As there is no upper client to deliver, we don't
1931 			 * need the first_mp any more.
1932 			 */
1933 			if (mctl_present) {
1934 				freeb(first_mp);
1935 			}
1936 			icmp_redirect(ill, mp);
1937 			return;
1938 		case ICMP_DEST_UNREACHABLE:
1939 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1940 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1941 				    zoneid, mp, iph_hdr_length, ipst)) {
1942 					freemsg(first_mp);
1943 					return;
1944 				}
1945 				/*
1946 				 * icmp_inbound_too_big() may alter mp.
1947 				 * Resynch ipha and icmph accordingly.
1948 				 */
1949 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1950 				ipha = (ipha_t *)&icmph[1];
1951 			}
1952 			/* FALLTHRU */
1953 		default :
1954 			/*
1955 			 * IPQoS notes: Since we have already done IPQoS
1956 			 * processing we don't want to do it again in
1957 			 * the fanout routines called by
1958 			 * icmp_inbound_error_fanout, hence the last
1959 			 * argument, ip_policy, is B_FALSE.
1960 			 */
1961 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1962 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1963 			    B_FALSE, recv_ill, zoneid);
1964 		}
1965 		return;
1966 	}
1967 	/* Send out an ICMP packet */
1968 	icmph->icmph_checksum = 0;
1969 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1970 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1971 		ipif_t	*ipif_chosen;
1972 		/*
1973 		 * Make it look like it was directed to us, so we don't look
1974 		 * like a fool with a broadcast or multicast source address.
1975 		 */
1976 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1977 		/*
1978 		 * Make sure that we haven't grabbed an interface that's DOWN.
1979 		 */
1980 		if (ipif != NULL) {
1981 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1982 			    ipha->ipha_src, zoneid);
1983 			if (ipif_chosen != NULL) {
1984 				ipif_refrele(ipif);
1985 				ipif = ipif_chosen;
1986 			}
1987 		}
1988 		if (ipif == NULL) {
1989 			ip0dbg(("icmp_inbound: "
1990 			    "No source for broadcast/multicast:\n"
1991 			    "\tsrc 0x%x dst 0x%x ill %p "
1992 			    "ipif_lcl_addr 0x%x\n",
1993 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1994 			    (void *)ill,
1995 			    ill->ill_ipif->ipif_lcl_addr));
1996 			freemsg(first_mp);
1997 			return;
1998 		}
1999 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2000 		ipha->ipha_dst = ipif->ipif_src_addr;
2001 		ipif_refrele(ipif);
2002 	}
2003 	/* Reset time to live. */
2004 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2005 	{
2006 		/* Swap source and destination addresses */
2007 		ipaddr_t tmp;
2008 
2009 		tmp = ipha->ipha_src;
2010 		ipha->ipha_src = ipha->ipha_dst;
2011 		ipha->ipha_dst = tmp;
2012 	}
2013 	ipha->ipha_ident = 0;
2014 	if (!IS_SIMPLE_IPH(ipha))
2015 		icmp_options_update(ipha);
2016 
2017 	/*
2018 	 * ICMP echo replies should go out on the same interface
2019 	 * the request came on as probes used by in.mpathd for detecting
2020 	 * NIC failures are ECHO packets. We turn-off load spreading
2021 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2022 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2023 	 * function. This is in turn handled by ip_wput and ip_newroute
2024 	 * to make sure that the packet goes out on the interface it came
2025 	 * in on. If we don't turnoff load spreading, the packets might get
2026 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2027 	 * to go out and in.mpathd would wrongly detect a failure or
2028 	 * mis-detect a NIC failure for link failure. As load spreading
2029 	 * can happen only if ill_group is not NULL, we do only for
2030 	 * that case and this does not affect the normal case.
2031 	 *
2032 	 * We turn off load spreading only on echo packets that came from
2033 	 * on-link hosts. If the interface route has been deleted, this will
2034 	 * not be enforced as we can't do much. For off-link hosts, as the
2035 	 * default routes in IPv4 does not typically have an ire_ipif
2036 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2037 	 * Moreover, expecting a default route through this interface may
2038 	 * not be correct. We use ipha_dst because of the swap above.
2039 	 */
2040 	onlink = B_FALSE;
2041 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2042 		/*
2043 		 * First, we need to make sure that it is not one of our
2044 		 * local addresses. If we set onlink when it is one of
2045 		 * our local addresses, we will end up creating IRE_CACHES
2046 		 * for one of our local addresses. Then, we will never
2047 		 * accept packets for them afterwards.
2048 		 */
2049 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2050 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2051 		if (src_ire == NULL) {
2052 			ipif = ipif_get_next_ipif(NULL, ill);
2053 			if (ipif == NULL) {
2054 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2055 				freemsg(mp);
2056 				return;
2057 			}
2058 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2059 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2060 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2061 			ipif_refrele(ipif);
2062 			if (src_ire != NULL) {
2063 				onlink = B_TRUE;
2064 				ire_refrele(src_ire);
2065 			}
2066 		} else {
2067 			ire_refrele(src_ire);
2068 		}
2069 	}
2070 	if (!mctl_present) {
2071 		/*
2072 		 * This packet should go out the same way as it
2073 		 * came in i.e in clear. To make sure that global
2074 		 * policy will not be applied to this in ip_wput_ire,
2075 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2076 		 */
2077 		ASSERT(first_mp == mp);
2078 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2079 		if (first_mp == NULL) {
2080 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2081 			freemsg(mp);
2082 			return;
2083 		}
2084 		ii = (ipsec_in_t *)first_mp->b_rptr;
2085 
2086 		/* This is not a secure packet */
2087 		ii->ipsec_in_secure = B_FALSE;
2088 		if (onlink) {
2089 			ii->ipsec_in_attach_if = B_TRUE;
2090 			ii->ipsec_in_ill_index =
2091 			    ill->ill_phyint->phyint_ifindex;
2092 			ii->ipsec_in_rill_index =
2093 			    recv_ill->ill_phyint->phyint_ifindex;
2094 		}
2095 		first_mp->b_cont = mp;
2096 	} else if (onlink) {
2097 		ii = (ipsec_in_t *)first_mp->b_rptr;
2098 		ii->ipsec_in_attach_if = B_TRUE;
2099 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2100 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2101 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2102 	} else {
2103 		ii = (ipsec_in_t *)first_mp->b_rptr;
2104 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2105 	}
2106 	ii->ipsec_in_zoneid = zoneid;
2107 	ASSERT(zoneid != ALL_ZONES);
2108 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2109 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2110 		return;
2111 	}
2112 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2113 	put(WR(q), first_mp);
2114 }
2115 
2116 static ipaddr_t
2117 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2118 {
2119 	conn_t *connp;
2120 	connf_t *connfp;
2121 	ipaddr_t nexthop_addr = INADDR_ANY;
2122 	int hdr_length = IPH_HDR_LENGTH(ipha);
2123 	uint16_t *up;
2124 	uint32_t ports;
2125 	ip_stack_t *ipst = ill->ill_ipst;
2126 
2127 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2128 	switch (ipha->ipha_protocol) {
2129 		case IPPROTO_TCP:
2130 		{
2131 			tcph_t *tcph;
2132 
2133 			/* do a reverse lookup */
2134 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2135 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2136 			    TCPS_LISTEN, ipst);
2137 			break;
2138 		}
2139 		case IPPROTO_UDP:
2140 		{
2141 			uint32_t dstport, srcport;
2142 
2143 			((uint16_t *)&ports)[0] = up[1];
2144 			((uint16_t *)&ports)[1] = up[0];
2145 
2146 			/* Extract ports in net byte order */
2147 			dstport = htons(ntohl(ports) & 0xFFFF);
2148 			srcport = htons(ntohl(ports) >> 16);
2149 
2150 			connfp = &ipst->ips_ipcl_udp_fanout[
2151 			    IPCL_UDP_HASH(dstport, ipst)];
2152 			mutex_enter(&connfp->connf_lock);
2153 			connp = connfp->connf_head;
2154 
2155 			/* do a reverse lookup */
2156 			while ((connp != NULL) &&
2157 			    (!IPCL_UDP_MATCH(connp, dstport,
2158 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2159 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2160 				connp = connp->conn_next;
2161 			}
2162 			if (connp != NULL)
2163 				CONN_INC_REF(connp);
2164 			mutex_exit(&connfp->connf_lock);
2165 			break;
2166 		}
2167 		case IPPROTO_SCTP:
2168 		{
2169 			in6_addr_t map_src, map_dst;
2170 
2171 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2172 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2173 			((uint16_t *)&ports)[0] = up[1];
2174 			((uint16_t *)&ports)[1] = up[0];
2175 
2176 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2177 			    zoneid, ipst->ips_netstack->netstack_sctp);
2178 			if (connp == NULL) {
2179 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2180 				    zoneid, ports, ipha, ipst);
2181 			} else {
2182 				CONN_INC_REF(connp);
2183 				SCTP_REFRELE(CONN2SCTP(connp));
2184 			}
2185 			break;
2186 		}
2187 		default:
2188 		{
2189 			ipha_t ripha;
2190 
2191 			ripha.ipha_src = ipha->ipha_dst;
2192 			ripha.ipha_dst = ipha->ipha_src;
2193 			ripha.ipha_protocol = ipha->ipha_protocol;
2194 
2195 			connfp = &ipst->ips_ipcl_proto_fanout[
2196 			    ipha->ipha_protocol];
2197 			mutex_enter(&connfp->connf_lock);
2198 			connp = connfp->connf_head;
2199 			for (connp = connfp->connf_head; connp != NULL;
2200 			    connp = connp->conn_next) {
2201 				if (IPCL_PROTO_MATCH(connp,
2202 				    ipha->ipha_protocol, &ripha, ill,
2203 				    0, zoneid)) {
2204 					CONN_INC_REF(connp);
2205 					break;
2206 				}
2207 			}
2208 			mutex_exit(&connfp->connf_lock);
2209 		}
2210 	}
2211 	if (connp != NULL) {
2212 		if (connp->conn_nexthop_set)
2213 			nexthop_addr = connp->conn_nexthop_v4;
2214 		CONN_DEC_REF(connp);
2215 	}
2216 	return (nexthop_addr);
2217 }
2218 
2219 /* Table from RFC 1191 */
2220 static int icmp_frag_size_table[] =
2221 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2222 
2223 /*
2224  * Process received ICMP Packet too big.
2225  * After updating any IRE it does the fanout to any matching transport streams.
2226  * Assumes the message has been pulled up till the IP header that caused
2227  * the error.
2228  *
2229  * Returns B_FALSE on failure and B_TRUE on success.
2230  */
2231 static boolean_t
2232 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2233     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2234     ip_stack_t *ipst)
2235 {
2236 	ire_t	*ire, *first_ire;
2237 	int	mtu, orig_mtu;
2238 	int	hdr_length;
2239 	ipaddr_t nexthop_addr;
2240 	boolean_t disable_pmtud;
2241 
2242 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2243 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2244 	ASSERT(ill != NULL);
2245 
2246 	hdr_length = IPH_HDR_LENGTH(ipha);
2247 
2248 	/* Drop if the original packet contained a source route */
2249 	if (ip_source_route_included(ipha)) {
2250 		return (B_FALSE);
2251 	}
2252 	/*
2253 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2254 	 * header.
2255 	 */
2256 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2257 	    mp->b_wptr) {
2258 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2259 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2260 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2261 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2262 			return (B_FALSE);
2263 		}
2264 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2265 		ipha = (ipha_t *)&icmph[1];
2266 	}
2267 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2268 	if (nexthop_addr != INADDR_ANY) {
2269 		/* nexthop set */
2270 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2271 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2272 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2273 	} else {
2274 		/* nexthop not set */
2275 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2276 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2277 	}
2278 
2279 	if (!first_ire) {
2280 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2281 		    ntohl(ipha->ipha_dst)));
2282 		return (B_FALSE);
2283 	}
2284 
2285 	/* Check for MTU discovery advice as described in RFC 1191 */
2286 	mtu = ntohs(icmph->icmph_du_mtu);
2287 	orig_mtu = mtu;
2288 	disable_pmtud = B_FALSE;
2289 
2290 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2291 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2292 	    ire = ire->ire_next) {
2293 		/*
2294 		 * Look for the connection to which this ICMP message is
2295 		 * directed. If it has the IP_NEXTHOP option set, then the
2296 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2297 		 * option. Else the search is limited to regular IREs.
2298 		 */
2299 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2300 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2301 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2302 		    (nexthop_addr != INADDR_ANY)))
2303 			continue;
2304 
2305 		mutex_enter(&ire->ire_lock);
2306 		if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
2307 			uint32_t length;
2308 			int	i;
2309 
2310 			/*
2311 			 * Use the table from RFC 1191 to figure out
2312 			 * the next "plateau" based on the length in
2313 			 * the original IP packet.
2314 			 */
2315 			length = ntohs(ipha->ipha_length);
2316 			DTRACE_PROBE2(ip4__pmtu__guess, ire_t *, ire,
2317 			    uint32_t, length);
2318 			if (ire->ire_max_frag <= length &&
2319 			    ire->ire_max_frag >= length - hdr_length) {
2320 				/*
2321 				 * Handle broken BSD 4.2 systems that
2322 				 * return the wrong iph_length in ICMP
2323 				 * errors.
2324 				 */
2325 				length -= hdr_length;
2326 			}
2327 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2328 				if (length > icmp_frag_size_table[i])
2329 					break;
2330 			}
2331 			if (i == A_CNT(icmp_frag_size_table)) {
2332 				/* Smaller than 68! */
2333 				disable_pmtud = B_TRUE;
2334 				mtu = ipst->ips_ip_pmtu_min;
2335 			} else {
2336 				mtu = icmp_frag_size_table[i];
2337 				if (mtu < ipst->ips_ip_pmtu_min) {
2338 					mtu = ipst->ips_ip_pmtu_min;
2339 					disable_pmtud = B_TRUE;
2340 				}
2341 			}
2342 			/* Fool the ULP into believing our guessed PMTU. */
2343 			icmph->icmph_du_zero = 0;
2344 			icmph->icmph_du_mtu = htons(mtu);
2345 		}
2346 		if (disable_pmtud)
2347 			ire->ire_frag_flag = 0;
2348 		/* Reduce the IRE max frag value as advised. */
2349 		ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2350 		mutex_exit(&ire->ire_lock);
2351 		DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, ire_t *,
2352 		    ire, int, orig_mtu, int, mtu);
2353 	}
2354 	rw_exit(&first_ire->ire_bucket->irb_lock);
2355 	ire_refrele(first_ire);
2356 	return (B_TRUE);
2357 }
2358 
2359 /*
2360  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2361  * calls this function.
2362  */
2363 static mblk_t *
2364 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2365 {
2366 	ipha_t *ipha;
2367 	icmph_t *icmph;
2368 	ipha_t *in_ipha;
2369 	int length;
2370 
2371 	ASSERT(mp->b_datap->db_type == M_DATA);
2372 
2373 	/*
2374 	 * For Self-encapsulated packets, we added an extra IP header
2375 	 * without the options. Inner IP header is the one from which
2376 	 * the outer IP header was formed. Thus, we need to remove the
2377 	 * outer IP header. To do this, we pullup the whole message
2378 	 * and overlay whatever follows the outer IP header over the
2379 	 * outer IP header.
2380 	 */
2381 
2382 	if (!pullupmsg(mp, -1))
2383 		return (NULL);
2384 
2385 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2386 	ipha = (ipha_t *)&icmph[1];
2387 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2388 
2389 	/*
2390 	 * The length that we want to overlay is following the inner
2391 	 * IP header. Subtracting the IP header + icmp header + outer
2392 	 * IP header's length should give us the length that we want to
2393 	 * overlay.
2394 	 */
2395 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2396 	    hdr_length;
2397 	/*
2398 	 * Overlay whatever follows the inner header over the
2399 	 * outer header.
2400 	 */
2401 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2402 
2403 	/* Set the wptr to account for the outer header */
2404 	mp->b_wptr -= hdr_length;
2405 	return (mp);
2406 }
2407 
2408 /*
2409  * Try to pass the ICMP message upstream in case the ULP cares.
2410  *
2411  * If the packet that caused the ICMP error is secure, we send
2412  * it to AH/ESP to make sure that the attached packet has a
2413  * valid association. ipha in the code below points to the
2414  * IP header of the packet that caused the error.
2415  *
2416  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2417  * in the context of IPsec. Normally we tell the upper layer
2418  * whenever we send the ire (including ip_bind), the IPsec header
2419  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2420  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2421  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2422  * same thing. As TCP has the IPsec options size that needs to be
2423  * adjusted, we just pass the MTU unchanged.
2424  *
2425  * IFN could have been generated locally or by some router.
2426  *
2427  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2428  *	    This happens because IP adjusted its value of MTU on an
2429  *	    earlier IFN message and could not tell the upper layer,
2430  *	    the new adjusted value of MTU e.g. Packet was encrypted
2431  *	    or there was not enough information to fanout to upper
2432  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2433  *	    generates the IFN, where IPsec processing has *not* been
2434  *	    done.
2435  *
2436  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2437  *	    could have generated this. This happens because ire_max_frag
2438  *	    value in IP was set to a new value, while the IPsec processing
2439  *	    was being done and after we made the fragmentation check in
2440  *	    ip_wput_ire. Thus on return from IPsec processing,
2441  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2442  *	    and generates the IFN. As IPsec processing is over, we fanout
2443  *	    to AH/ESP to remove the header.
2444  *
2445  *	    In both these cases, ipsec_in_loopback will be set indicating
2446  *	    that IFN was generated locally.
2447  *
2448  * ROUTER : IFN could be secure or non-secure.
2449  *
2450  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2451  *	      packet in error has AH/ESP headers to validate the AH/ESP
2452  *	      headers. AH/ESP will verify whether there is a valid SA or
2453  *	      not and send it back. We will fanout again if we have more
2454  *	      data in the packet.
2455  *
2456  *	      If the packet in error does not have AH/ESP, we handle it
2457  *	      like any other case.
2458  *
2459  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2460  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2461  *	      for validation. AH/ESP will verify whether there is a
2462  *	      valid SA or not and send it back. We will fanout again if
2463  *	      we have more data in the packet.
2464  *
2465  *	      If the packet in error does not have AH/ESP, we handle it
2466  *	      like any other case.
2467  */
2468 static void
2469 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2470     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2471     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2472     zoneid_t zoneid)
2473 {
2474 	uint16_t *up;	/* Pointer to ports in ULP header */
2475 	uint32_t ports;	/* reversed ports for fanout */
2476 	ipha_t ripha;	/* With reversed addresses */
2477 	mblk_t *first_mp;
2478 	ipsec_in_t *ii;
2479 	tcph_t	*tcph;
2480 	conn_t	*connp;
2481 	ip_stack_t *ipst;
2482 
2483 	ASSERT(ill != NULL);
2484 
2485 	ASSERT(recv_ill != NULL);
2486 	ipst = recv_ill->ill_ipst;
2487 
2488 	first_mp = mp;
2489 	if (mctl_present) {
2490 		mp = first_mp->b_cont;
2491 		ASSERT(mp != NULL);
2492 
2493 		ii = (ipsec_in_t *)first_mp->b_rptr;
2494 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2495 	} else {
2496 		ii = NULL;
2497 	}
2498 
2499 	switch (ipha->ipha_protocol) {
2500 	case IPPROTO_UDP:
2501 		/*
2502 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2503 		 * transport header.
2504 		 */
2505 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2506 		    mp->b_wptr) {
2507 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2508 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2509 				goto discard_pkt;
2510 			}
2511 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2512 			ipha = (ipha_t *)&icmph[1];
2513 		}
2514 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2515 
2516 		/*
2517 		 * Attempt to find a client stream based on port.
2518 		 * Note that we do a reverse lookup since the header is
2519 		 * in the form we sent it out.
2520 		 * The ripha header is only used for the IP_UDP_MATCH and we
2521 		 * only set the src and dst addresses and protocol.
2522 		 */
2523 		ripha.ipha_src = ipha->ipha_dst;
2524 		ripha.ipha_dst = ipha->ipha_src;
2525 		ripha.ipha_protocol = ipha->ipha_protocol;
2526 		((uint16_t *)&ports)[0] = up[1];
2527 		((uint16_t *)&ports)[1] = up[0];
2528 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2529 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2530 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2531 		    icmph->icmph_type, icmph->icmph_code));
2532 
2533 		/* Have to change db_type after any pullupmsg */
2534 		DB_TYPE(mp) = M_CTL;
2535 
2536 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2537 		    mctl_present, ip_policy, recv_ill, zoneid);
2538 		return;
2539 
2540 	case IPPROTO_TCP:
2541 		/*
2542 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2543 		 * transport header.
2544 		 */
2545 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2546 		    mp->b_wptr) {
2547 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2548 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2549 				goto discard_pkt;
2550 			}
2551 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2552 			ipha = (ipha_t *)&icmph[1];
2553 		}
2554 		/*
2555 		 * Find a TCP client stream for this packet.
2556 		 * Note that we do a reverse lookup since the header is
2557 		 * in the form we sent it out.
2558 		 */
2559 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2560 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2561 		    ipst);
2562 		if (connp == NULL)
2563 			goto discard_pkt;
2564 
2565 		/* Have to change db_type after any pullupmsg */
2566 		DB_TYPE(mp) = M_CTL;
2567 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, tcp_input, connp,
2568 		    SQ_FILL, SQTAG_TCP_INPUT_ICMP_ERR);
2569 		return;
2570 
2571 	case IPPROTO_SCTP:
2572 		/*
2573 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2574 		 * transport header.
2575 		 */
2576 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2577 		    mp->b_wptr) {
2578 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2579 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2580 				goto discard_pkt;
2581 			}
2582 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2583 			ipha = (ipha_t *)&icmph[1];
2584 		}
2585 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2586 		/*
2587 		 * Find a SCTP client stream for this packet.
2588 		 * Note that we do a reverse lookup since the header is
2589 		 * in the form we sent it out.
2590 		 * The ripha header is only used for the matching and we
2591 		 * only set the src and dst addresses, protocol, and version.
2592 		 */
2593 		ripha.ipha_src = ipha->ipha_dst;
2594 		ripha.ipha_dst = ipha->ipha_src;
2595 		ripha.ipha_protocol = ipha->ipha_protocol;
2596 		ripha.ipha_version_and_hdr_length =
2597 		    ipha->ipha_version_and_hdr_length;
2598 		((uint16_t *)&ports)[0] = up[1];
2599 		((uint16_t *)&ports)[1] = up[0];
2600 
2601 		/* Have to change db_type after any pullupmsg */
2602 		DB_TYPE(mp) = M_CTL;
2603 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2604 		    mctl_present, ip_policy, zoneid);
2605 		return;
2606 
2607 	case IPPROTO_ESP:
2608 	case IPPROTO_AH: {
2609 		int ipsec_rc;
2610 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2611 
2612 		/*
2613 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2614 		 * We will re-use the IPSEC_IN if it is already present as
2615 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2616 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2617 		 * one and attach it in the front.
2618 		 */
2619 		if (ii != NULL) {
2620 			/*
2621 			 * ip_fanout_proto_again converts the ICMP errors
2622 			 * that come back from AH/ESP to M_DATA so that
2623 			 * if it is non-AH/ESP and we do a pullupmsg in
2624 			 * this function, it would work. Convert it back
2625 			 * to M_CTL before we send up as this is a ICMP
2626 			 * error. This could have been generated locally or
2627 			 * by some router. Validate the inner IPsec
2628 			 * headers.
2629 			 *
2630 			 * NOTE : ill_index is used by ip_fanout_proto_again
2631 			 * to locate the ill.
2632 			 */
2633 			ASSERT(ill != NULL);
2634 			ii->ipsec_in_ill_index =
2635 			    ill->ill_phyint->phyint_ifindex;
2636 			ii->ipsec_in_rill_index =
2637 			    recv_ill->ill_phyint->phyint_ifindex;
2638 			DB_TYPE(first_mp->b_cont) = M_CTL;
2639 		} else {
2640 			/*
2641 			 * IPSEC_IN is not present. We attach a ipsec_in
2642 			 * message and send up to IPsec for validating
2643 			 * and removing the IPsec headers. Clear
2644 			 * ipsec_in_secure so that when we return
2645 			 * from IPsec, we don't mistakenly think that this
2646 			 * is a secure packet came from the network.
2647 			 *
2648 			 * NOTE : ill_index is used by ip_fanout_proto_again
2649 			 * to locate the ill.
2650 			 */
2651 			ASSERT(first_mp == mp);
2652 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2653 			if (first_mp == NULL) {
2654 				freemsg(mp);
2655 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2656 				return;
2657 			}
2658 			ii = (ipsec_in_t *)first_mp->b_rptr;
2659 
2660 			/* This is not a secure packet */
2661 			ii->ipsec_in_secure = B_FALSE;
2662 			first_mp->b_cont = mp;
2663 			DB_TYPE(mp) = M_CTL;
2664 			ASSERT(ill != NULL);
2665 			ii->ipsec_in_ill_index =
2666 			    ill->ill_phyint->phyint_ifindex;
2667 			ii->ipsec_in_rill_index =
2668 			    recv_ill->ill_phyint->phyint_ifindex;
2669 		}
2670 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2671 
2672 		if (!ipsec_loaded(ipss)) {
2673 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2674 			return;
2675 		}
2676 
2677 		if (ipha->ipha_protocol == IPPROTO_ESP)
2678 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2679 		else
2680 			ipsec_rc = ipsecah_icmp_error(first_mp);
2681 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2682 			return;
2683 
2684 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2685 		return;
2686 	}
2687 	default:
2688 		/*
2689 		 * The ripha header is only used for the lookup and we
2690 		 * only set the src and dst addresses and protocol.
2691 		 */
2692 		ripha.ipha_src = ipha->ipha_dst;
2693 		ripha.ipha_dst = ipha->ipha_src;
2694 		ripha.ipha_protocol = ipha->ipha_protocol;
2695 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2696 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2697 		    ntohl(ipha->ipha_dst),
2698 		    icmph->icmph_type, icmph->icmph_code));
2699 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2700 			ipha_t *in_ipha;
2701 
2702 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2703 			    mp->b_wptr) {
2704 				if (!pullupmsg(mp, (uchar_t *)ipha +
2705 				    hdr_length + sizeof (ipha_t) -
2706 				    mp->b_rptr)) {
2707 					goto discard_pkt;
2708 				}
2709 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2710 				ipha = (ipha_t *)&icmph[1];
2711 			}
2712 			/*
2713 			 * Caller has verified that length has to be
2714 			 * at least the size of IP header.
2715 			 */
2716 			ASSERT(hdr_length >= sizeof (ipha_t));
2717 			/*
2718 			 * Check the sanity of the inner IP header like
2719 			 * we did for the outer header.
2720 			 */
2721 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2722 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2723 				goto discard_pkt;
2724 			}
2725 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2726 				goto discard_pkt;
2727 			}
2728 			/* Check for Self-encapsulated tunnels */
2729 			if (in_ipha->ipha_src == ipha->ipha_src &&
2730 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2731 
2732 				mp = icmp_inbound_self_encap_error(mp,
2733 				    iph_hdr_length, hdr_length);
2734 				if (mp == NULL)
2735 					goto discard_pkt;
2736 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2737 				ipha = (ipha_t *)&icmph[1];
2738 				hdr_length = IPH_HDR_LENGTH(ipha);
2739 				/*
2740 				 * The packet in error is self-encapsualted.
2741 				 * And we are finding it further encapsulated
2742 				 * which we could not have possibly generated.
2743 				 */
2744 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2745 					goto discard_pkt;
2746 				}
2747 				icmp_inbound_error_fanout(q, ill, first_mp,
2748 				    icmph, ipha, iph_hdr_length, hdr_length,
2749 				    mctl_present, ip_policy, recv_ill, zoneid);
2750 				return;
2751 			}
2752 		}
2753 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2754 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2755 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2756 		    ii != NULL &&
2757 		    ii->ipsec_in_loopback &&
2758 		    ii->ipsec_in_secure) {
2759 			/*
2760 			 * For IP tunnels that get a looped-back
2761 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2762 			 * reported new MTU to take into account the IPsec
2763 			 * headers protecting this configured tunnel.
2764 			 *
2765 			 * This allows the tunnel module (tun.c) to blindly
2766 			 * accept the MTU reported in an ICMP "too big"
2767 			 * message.
2768 			 *
2769 			 * Non-looped back ICMP messages will just be
2770 			 * handled by the security protocols (if needed),
2771 			 * and the first subsequent packet will hit this
2772 			 * path.
2773 			 */
2774 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2775 			    ipsec_in_extra_length(first_mp));
2776 		}
2777 		/* Have to change db_type after any pullupmsg */
2778 		DB_TYPE(mp) = M_CTL;
2779 
2780 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2781 		    ip_policy, recv_ill, zoneid);
2782 		return;
2783 	}
2784 	/* NOTREACHED */
2785 discard_pkt:
2786 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2787 drop_pkt:;
2788 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2789 	freemsg(first_mp);
2790 }
2791 
2792 /*
2793  * Common IP options parser.
2794  *
2795  * Setup routine: fill in *optp with options-parsing state, then
2796  * tail-call ipoptp_next to return the first option.
2797  */
2798 uint8_t
2799 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2800 {
2801 	uint32_t totallen; /* total length of all options */
2802 
2803 	totallen = ipha->ipha_version_and_hdr_length -
2804 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2805 	totallen <<= 2;
2806 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2807 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2808 	optp->ipoptp_flags = 0;
2809 	return (ipoptp_next(optp));
2810 }
2811 
2812 /*
2813  * Common IP options parser: extract next option.
2814  */
2815 uint8_t
2816 ipoptp_next(ipoptp_t *optp)
2817 {
2818 	uint8_t *end = optp->ipoptp_end;
2819 	uint8_t *cur = optp->ipoptp_next;
2820 	uint8_t opt, len, pointer;
2821 
2822 	/*
2823 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2824 	 * has been corrupted.
2825 	 */
2826 	ASSERT(cur <= end);
2827 
2828 	if (cur == end)
2829 		return (IPOPT_EOL);
2830 
2831 	opt = cur[IPOPT_OPTVAL];
2832 
2833 	/*
2834 	 * Skip any NOP options.
2835 	 */
2836 	while (opt == IPOPT_NOP) {
2837 		cur++;
2838 		if (cur == end)
2839 			return (IPOPT_EOL);
2840 		opt = cur[IPOPT_OPTVAL];
2841 	}
2842 
2843 	if (opt == IPOPT_EOL)
2844 		return (IPOPT_EOL);
2845 
2846 	/*
2847 	 * Option requiring a length.
2848 	 */
2849 	if ((cur + 1) >= end) {
2850 		optp->ipoptp_flags |= IPOPTP_ERROR;
2851 		return (IPOPT_EOL);
2852 	}
2853 	len = cur[IPOPT_OLEN];
2854 	if (len < 2) {
2855 		optp->ipoptp_flags |= IPOPTP_ERROR;
2856 		return (IPOPT_EOL);
2857 	}
2858 	optp->ipoptp_cur = cur;
2859 	optp->ipoptp_len = len;
2860 	optp->ipoptp_next = cur + len;
2861 	if (cur + len > end) {
2862 		optp->ipoptp_flags |= IPOPTP_ERROR;
2863 		return (IPOPT_EOL);
2864 	}
2865 
2866 	/*
2867 	 * For the options which require a pointer field, make sure
2868 	 * its there, and make sure it points to either something
2869 	 * inside this option, or the end of the option.
2870 	 */
2871 	switch (opt) {
2872 	case IPOPT_RR:
2873 	case IPOPT_TS:
2874 	case IPOPT_LSRR:
2875 	case IPOPT_SSRR:
2876 		if (len <= IPOPT_OFFSET) {
2877 			optp->ipoptp_flags |= IPOPTP_ERROR;
2878 			return (opt);
2879 		}
2880 		pointer = cur[IPOPT_OFFSET];
2881 		if (pointer - 1 > len) {
2882 			optp->ipoptp_flags |= IPOPTP_ERROR;
2883 			return (opt);
2884 		}
2885 		break;
2886 	}
2887 
2888 	/*
2889 	 * Sanity check the pointer field based on the type of the
2890 	 * option.
2891 	 */
2892 	switch (opt) {
2893 	case IPOPT_RR:
2894 	case IPOPT_SSRR:
2895 	case IPOPT_LSRR:
2896 		if (pointer < IPOPT_MINOFF_SR)
2897 			optp->ipoptp_flags |= IPOPTP_ERROR;
2898 		break;
2899 	case IPOPT_TS:
2900 		if (pointer < IPOPT_MINOFF_IT)
2901 			optp->ipoptp_flags |= IPOPTP_ERROR;
2902 		/*
2903 		 * Note that the Internet Timestamp option also
2904 		 * contains two four bit fields (the Overflow field,
2905 		 * and the Flag field), which follow the pointer
2906 		 * field.  We don't need to check that these fields
2907 		 * fall within the length of the option because this
2908 		 * was implicitely done above.  We've checked that the
2909 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2910 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2911 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2912 		 */
2913 		ASSERT(len > IPOPT_POS_OV_FLG);
2914 		break;
2915 	}
2916 
2917 	return (opt);
2918 }
2919 
2920 /*
2921  * Use the outgoing IP header to create an IP_OPTIONS option the way
2922  * it was passed down from the application.
2923  */
2924 int
2925 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2926 {
2927 	ipoptp_t	opts;
2928 	const uchar_t	*opt;
2929 	uint8_t		optval;
2930 	uint8_t		optlen;
2931 	uint32_t	len = 0;
2932 	uchar_t	*buf1 = buf;
2933 
2934 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2935 	len += IP_ADDR_LEN;
2936 	bzero(buf1, IP_ADDR_LEN);
2937 
2938 	/*
2939 	 * OK to cast away const here, as we don't store through the returned
2940 	 * opts.ipoptp_cur pointer.
2941 	 */
2942 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2943 	    optval != IPOPT_EOL;
2944 	    optval = ipoptp_next(&opts)) {
2945 		int	off;
2946 
2947 		opt = opts.ipoptp_cur;
2948 		optlen = opts.ipoptp_len;
2949 		switch (optval) {
2950 		case IPOPT_SSRR:
2951 		case IPOPT_LSRR:
2952 
2953 			/*
2954 			 * Insert ipha_dst as the first entry in the source
2955 			 * route and move down the entries on step.
2956 			 * The last entry gets placed at buf1.
2957 			 */
2958 			buf[IPOPT_OPTVAL] = optval;
2959 			buf[IPOPT_OLEN] = optlen;
2960 			buf[IPOPT_OFFSET] = optlen;
2961 
2962 			off = optlen - IP_ADDR_LEN;
2963 			if (off < 0) {
2964 				/* No entries in source route */
2965 				break;
2966 			}
2967 			/* Last entry in source route */
2968 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2969 			off -= IP_ADDR_LEN;
2970 
2971 			while (off > 0) {
2972 				bcopy(opt + off,
2973 				    buf + off + IP_ADDR_LEN,
2974 				    IP_ADDR_LEN);
2975 				off -= IP_ADDR_LEN;
2976 			}
2977 			/* ipha_dst into first slot */
2978 			bcopy(&ipha->ipha_dst,
2979 			    buf + off + IP_ADDR_LEN,
2980 			    IP_ADDR_LEN);
2981 			buf += optlen;
2982 			len += optlen;
2983 			break;
2984 
2985 		case IPOPT_COMSEC:
2986 		case IPOPT_SECURITY:
2987 			/* if passing up a label is not ok, then remove */
2988 			if (is_system_labeled())
2989 				break;
2990 			/* FALLTHROUGH */
2991 		default:
2992 			bcopy(opt, buf, optlen);
2993 			buf += optlen;
2994 			len += optlen;
2995 			break;
2996 		}
2997 	}
2998 done:
2999 	/* Pad the resulting options */
3000 	while (len & 0x3) {
3001 		*buf++ = IPOPT_EOL;
3002 		len++;
3003 	}
3004 	return (len);
3005 }
3006 
3007 /*
3008  * Update any record route or timestamp options to include this host.
3009  * Reverse any source route option.
3010  * This routine assumes that the options are well formed i.e. that they
3011  * have already been checked.
3012  */
3013 static void
3014 icmp_options_update(ipha_t *ipha)
3015 {
3016 	ipoptp_t	opts;
3017 	uchar_t		*opt;
3018 	uint8_t		optval;
3019 	ipaddr_t	src;		/* Our local address */
3020 	ipaddr_t	dst;
3021 
3022 	ip2dbg(("icmp_options_update\n"));
3023 	src = ipha->ipha_src;
3024 	dst = ipha->ipha_dst;
3025 
3026 	for (optval = ipoptp_first(&opts, ipha);
3027 	    optval != IPOPT_EOL;
3028 	    optval = ipoptp_next(&opts)) {
3029 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3030 		opt = opts.ipoptp_cur;
3031 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3032 		    optval, opts.ipoptp_len));
3033 		switch (optval) {
3034 			int off1, off2;
3035 		case IPOPT_SSRR:
3036 		case IPOPT_LSRR:
3037 			/*
3038 			 * Reverse the source route.  The first entry
3039 			 * should be the next to last one in the current
3040 			 * source route (the last entry is our address).
3041 			 * The last entry should be the final destination.
3042 			 */
3043 			off1 = IPOPT_MINOFF_SR - 1;
3044 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3045 			if (off2 < 0) {
3046 				/* No entries in source route */
3047 				ip1dbg((
3048 				    "icmp_options_update: bad src route\n"));
3049 				break;
3050 			}
3051 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3052 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3053 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3054 			off2 -= IP_ADDR_LEN;
3055 
3056 			while (off1 < off2) {
3057 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3058 				bcopy((char *)opt + off2, (char *)opt + off1,
3059 				    IP_ADDR_LEN);
3060 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3061 				off1 += IP_ADDR_LEN;
3062 				off2 -= IP_ADDR_LEN;
3063 			}
3064 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3065 			break;
3066 		}
3067 	}
3068 }
3069 
3070 /*
3071  * Process received ICMP Redirect messages.
3072  */
3073 static void
3074 icmp_redirect(ill_t *ill, mblk_t *mp)
3075 {
3076 	ipha_t	*ipha;
3077 	int	iph_hdr_length;
3078 	icmph_t	*icmph;
3079 	ipha_t	*ipha_err;
3080 	ire_t	*ire;
3081 	ire_t	*prev_ire;
3082 	ire_t	*save_ire;
3083 	ipaddr_t  src, dst, gateway;
3084 	iulp_t	ulp_info = { 0 };
3085 	int	error;
3086 	ip_stack_t *ipst;
3087 
3088 	ASSERT(ill != NULL);
3089 	ipst = ill->ill_ipst;
3090 
3091 	ipha = (ipha_t *)mp->b_rptr;
3092 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3093 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3094 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3095 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3096 		freemsg(mp);
3097 		return;
3098 	}
3099 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3100 	ipha_err = (ipha_t *)&icmph[1];
3101 	src = ipha->ipha_src;
3102 	dst = ipha_err->ipha_dst;
3103 	gateway = icmph->icmph_rd_gateway;
3104 	/* Make sure the new gateway is reachable somehow. */
3105 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3106 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3107 	/*
3108 	 * Make sure we had a route for the dest in question and that
3109 	 * that route was pointing to the old gateway (the source of the
3110 	 * redirect packet.)
3111 	 */
3112 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3113 	    NULL, MATCH_IRE_GW, ipst);
3114 	/*
3115 	 * Check that
3116 	 *	the redirect was not from ourselves
3117 	 *	the new gateway and the old gateway are directly reachable
3118 	 */
3119 	if (!prev_ire ||
3120 	    !ire ||
3121 	    ire->ire_type == IRE_LOCAL) {
3122 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3123 		freemsg(mp);
3124 		if (ire != NULL)
3125 			ire_refrele(ire);
3126 		if (prev_ire != NULL)
3127 			ire_refrele(prev_ire);
3128 		return;
3129 	}
3130 
3131 	/*
3132 	 * Should we use the old ULP info to create the new gateway?  From
3133 	 * a user's perspective, we should inherit the info so that it
3134 	 * is a "smooth" transition.  If we do not do that, then new
3135 	 * connections going thru the new gateway will have no route metrics,
3136 	 * which is counter-intuitive to user.  From a network point of
3137 	 * view, this may or may not make sense even though the new gateway
3138 	 * is still directly connected to us so the route metrics should not
3139 	 * change much.
3140 	 *
3141 	 * But if the old ire_uinfo is not initialized, we do another
3142 	 * recursive lookup on the dest using the new gateway.  There may
3143 	 * be a route to that.  If so, use it to initialize the redirect
3144 	 * route.
3145 	 */
3146 	if (prev_ire->ire_uinfo.iulp_set) {
3147 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3148 	} else {
3149 		ire_t *tmp_ire;
3150 		ire_t *sire;
3151 
3152 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3153 		    ALL_ZONES, 0, NULL,
3154 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3155 		    ipst);
3156 		if (sire != NULL) {
3157 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3158 			/*
3159 			 * If sire != NULL, ire_ftable_lookup() should not
3160 			 * return a NULL value.
3161 			 */
3162 			ASSERT(tmp_ire != NULL);
3163 			ire_refrele(tmp_ire);
3164 			ire_refrele(sire);
3165 		} else if (tmp_ire != NULL) {
3166 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3167 			    sizeof (iulp_t));
3168 			ire_refrele(tmp_ire);
3169 		}
3170 	}
3171 	if (prev_ire->ire_type == IRE_CACHE)
3172 		ire_delete(prev_ire);
3173 	ire_refrele(prev_ire);
3174 	/*
3175 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3176 	 * require TOS routing
3177 	 */
3178 	switch (icmph->icmph_code) {
3179 	case 0:
3180 	case 1:
3181 		/* TODO: TOS specificity for cases 2 and 3 */
3182 	case 2:
3183 	case 3:
3184 		break;
3185 	default:
3186 		freemsg(mp);
3187 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3188 		ire_refrele(ire);
3189 		return;
3190 	}
3191 	/*
3192 	 * Create a Route Association.  This will allow us to remember that
3193 	 * someone we believe told us to use the particular gateway.
3194 	 */
3195 	save_ire = ire;
3196 	ire = ire_create(
3197 	    (uchar_t *)&dst,			/* dest addr */
3198 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3199 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3200 	    (uchar_t *)&gateway,		/* gateway addr */
3201 	    &save_ire->ire_max_frag,		/* max frag */
3202 	    NULL,				/* no src nce */
3203 	    NULL,				/* no rfq */
3204 	    NULL,				/* no stq */
3205 	    IRE_HOST,
3206 	    NULL,				/* ipif */
3207 	    0,					/* cmask */
3208 	    0,					/* phandle */
3209 	    0,					/* ihandle */
3210 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3211 	    &ulp_info,
3212 	    NULL,				/* tsol_gc_t */
3213 	    NULL,				/* gcgrp */
3214 	    ipst);
3215 
3216 	if (ire == NULL) {
3217 		freemsg(mp);
3218 		ire_refrele(save_ire);
3219 		return;
3220 	}
3221 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3222 	ire_refrele(save_ire);
3223 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3224 
3225 	if (error == 0) {
3226 		ire_refrele(ire);		/* Held in ire_add_v4 */
3227 		/* tell routing sockets that we received a redirect */
3228 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3229 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3230 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3231 	}
3232 
3233 	/*
3234 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3235 	 * This together with the added IRE has the effect of
3236 	 * modifying an existing redirect.
3237 	 */
3238 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3239 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3240 	if (prev_ire != NULL) {
3241 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3242 			ire_delete(prev_ire);
3243 		ire_refrele(prev_ire);
3244 	}
3245 
3246 	freemsg(mp);
3247 }
3248 
3249 /*
3250  * Generate an ICMP parameter problem message.
3251  */
3252 static void
3253 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3254 	ip_stack_t *ipst)
3255 {
3256 	icmph_t	icmph;
3257 	boolean_t mctl_present;
3258 	mblk_t *first_mp;
3259 
3260 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3261 
3262 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3263 		if (mctl_present)
3264 			freeb(first_mp);
3265 		return;
3266 	}
3267 
3268 	bzero(&icmph, sizeof (icmph_t));
3269 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3270 	icmph.icmph_pp_ptr = ptr;
3271 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3272 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3273 	    ipst);
3274 }
3275 
3276 /*
3277  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3278  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3279  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3280  * an icmp error packet can be sent.
3281  * Assigns an appropriate source address to the packet. If ipha_dst is
3282  * one of our addresses use it for source. Otherwise pick a source based
3283  * on a route lookup back to ipha_src.
3284  * Note that ipha_src must be set here since the
3285  * packet is likely to arrive on an ill queue in ip_wput() which will
3286  * not set a source address.
3287  */
3288 static void
3289 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3290     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3291 {
3292 	ipaddr_t dst;
3293 	icmph_t	*icmph;
3294 	ipha_t	*ipha;
3295 	uint_t	len_needed;
3296 	size_t	msg_len;
3297 	mblk_t	*mp1;
3298 	ipaddr_t src;
3299 	ire_t	*ire;
3300 	mblk_t *ipsec_mp;
3301 	ipsec_out_t	*io = NULL;
3302 
3303 	if (mctl_present) {
3304 		/*
3305 		 * If it is :
3306 		 *
3307 		 * 1) a IPSEC_OUT, then this is caused by outbound
3308 		 *    datagram originating on this host. IPsec processing
3309 		 *    may or may not have been done. Refer to comments above
3310 		 *    icmp_inbound_error_fanout for details.
3311 		 *
3312 		 * 2) a IPSEC_IN if we are generating a icmp_message
3313 		 *    for an incoming datagram destined for us i.e called
3314 		 *    from ip_fanout_send_icmp.
3315 		 */
3316 		ipsec_info_t *in;
3317 		ipsec_mp = mp;
3318 		mp = ipsec_mp->b_cont;
3319 
3320 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3321 		ipha = (ipha_t *)mp->b_rptr;
3322 
3323 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3324 		    in->ipsec_info_type == IPSEC_IN);
3325 
3326 		if (in->ipsec_info_type == IPSEC_IN) {
3327 			/*
3328 			 * Convert the IPSEC_IN to IPSEC_OUT.
3329 			 */
3330 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3331 				BUMP_MIB(&ipst->ips_ip_mib,
3332 				    ipIfStatsOutDiscards);
3333 				return;
3334 			}
3335 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3336 		} else {
3337 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3338 			io = (ipsec_out_t *)in;
3339 			/*
3340 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3341 			 * ire lookup.
3342 			 */
3343 			io->ipsec_out_proc_begin = B_FALSE;
3344 		}
3345 		ASSERT(zoneid == io->ipsec_out_zoneid);
3346 		ASSERT(zoneid != ALL_ZONES);
3347 	} else {
3348 		/*
3349 		 * This is in clear. The icmp message we are building
3350 		 * here should go out in clear.
3351 		 *
3352 		 * Pardon the convolution of it all, but it's easier to
3353 		 * allocate a "use cleartext" IPSEC_IN message and convert
3354 		 * it than it is to allocate a new one.
3355 		 */
3356 		ipsec_in_t *ii;
3357 		ASSERT(DB_TYPE(mp) == M_DATA);
3358 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3359 		if (ipsec_mp == NULL) {
3360 			freemsg(mp);
3361 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3362 			return;
3363 		}
3364 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3365 
3366 		/* This is not a secure packet */
3367 		ii->ipsec_in_secure = B_FALSE;
3368 		/*
3369 		 * For trusted extensions using a shared IP address we can
3370 		 * send using any zoneid.
3371 		 */
3372 		if (zoneid == ALL_ZONES)
3373 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3374 		else
3375 			ii->ipsec_in_zoneid = zoneid;
3376 		ipsec_mp->b_cont = mp;
3377 		ipha = (ipha_t *)mp->b_rptr;
3378 		/*
3379 		 * Convert the IPSEC_IN to IPSEC_OUT.
3380 		 */
3381 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3382 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3383 			return;
3384 		}
3385 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3386 	}
3387 
3388 	/* Remember our eventual destination */
3389 	dst = ipha->ipha_src;
3390 
3391 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3392 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3393 	if (ire != NULL &&
3394 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3395 		src = ipha->ipha_dst;
3396 	} else {
3397 		if (ire != NULL)
3398 			ire_refrele(ire);
3399 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3400 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3401 		    ipst);
3402 		if (ire == NULL) {
3403 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3404 			freemsg(ipsec_mp);
3405 			return;
3406 		}
3407 		src = ire->ire_src_addr;
3408 	}
3409 
3410 	if (ire != NULL)
3411 		ire_refrele(ire);
3412 
3413 	/*
3414 	 * Check if we can send back more then 8 bytes in addition to
3415 	 * the IP header.  We try to send 64 bytes of data and the internal
3416 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3417 	 */
3418 	len_needed = IPH_HDR_LENGTH(ipha);
3419 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3420 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3421 
3422 		if (!pullupmsg(mp, -1)) {
3423 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3424 			freemsg(ipsec_mp);
3425 			return;
3426 		}
3427 		ipha = (ipha_t *)mp->b_rptr;
3428 
3429 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3430 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3431 			    len_needed));
3432 		} else {
3433 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3434 
3435 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3436 			len_needed += ip_hdr_length_v6(mp, ip6h);
3437 		}
3438 	}
3439 	len_needed += ipst->ips_ip_icmp_return;
3440 	msg_len = msgdsize(mp);
3441 	if (msg_len > len_needed) {
3442 		(void) adjmsg(mp, len_needed - msg_len);
3443 		msg_len = len_needed;
3444 	}
3445 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3446 	if (mp1 == NULL) {
3447 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3448 		freemsg(ipsec_mp);
3449 		return;
3450 	}
3451 	mp1->b_cont = mp;
3452 	mp = mp1;
3453 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3454 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3455 	    io->ipsec_out_type == IPSEC_OUT);
3456 	ipsec_mp->b_cont = mp;
3457 
3458 	/*
3459 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3460 	 * node generates be accepted in peace by all on-host destinations.
3461 	 * If we do NOT assume that all on-host destinations trust
3462 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3463 	 * (Look for ipsec_out_icmp_loopback).
3464 	 */
3465 	io->ipsec_out_icmp_loopback = B_TRUE;
3466 
3467 	ipha = (ipha_t *)mp->b_rptr;
3468 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3469 	*ipha = icmp_ipha;
3470 	ipha->ipha_src = src;
3471 	ipha->ipha_dst = dst;
3472 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3473 	msg_len += sizeof (icmp_ipha) + len;
3474 	if (msg_len > IP_MAXPACKET) {
3475 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3476 		msg_len = IP_MAXPACKET;
3477 	}
3478 	ipha->ipha_length = htons((uint16_t)msg_len);
3479 	icmph = (icmph_t *)&ipha[1];
3480 	bcopy(stuff, icmph, len);
3481 	icmph->icmph_checksum = 0;
3482 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3483 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3484 	put(q, ipsec_mp);
3485 }
3486 
3487 /*
3488  * Determine if an ICMP error packet can be sent given the rate limit.
3489  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3490  * in milliseconds) and a burst size. Burst size number of packets can
3491  * be sent arbitrarely closely spaced.
3492  * The state is tracked using two variables to implement an approximate
3493  * token bucket filter:
3494  *	icmp_pkt_err_last - lbolt value when the last burst started
3495  *	icmp_pkt_err_sent - number of packets sent in current burst
3496  */
3497 boolean_t
3498 icmp_err_rate_limit(ip_stack_t *ipst)
3499 {
3500 	clock_t now = TICK_TO_MSEC(lbolt);
3501 	uint_t refilled; /* Number of packets refilled in tbf since last */
3502 	/* Guard against changes by loading into local variable */
3503 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3504 
3505 	if (err_interval == 0)
3506 		return (B_FALSE);
3507 
3508 	if (ipst->ips_icmp_pkt_err_last > now) {
3509 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3510 		ipst->ips_icmp_pkt_err_last = 0;
3511 		ipst->ips_icmp_pkt_err_sent = 0;
3512 	}
3513 	/*
3514 	 * If we are in a burst update the token bucket filter.
3515 	 * Update the "last" time to be close to "now" but make sure
3516 	 * we don't loose precision.
3517 	 */
3518 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3519 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3520 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3521 			ipst->ips_icmp_pkt_err_sent = 0;
3522 		} else {
3523 			ipst->ips_icmp_pkt_err_sent -= refilled;
3524 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3525 		}
3526 	}
3527 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3528 		/* Start of new burst */
3529 		ipst->ips_icmp_pkt_err_last = now;
3530 	}
3531 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3532 		ipst->ips_icmp_pkt_err_sent++;
3533 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3534 		    ipst->ips_icmp_pkt_err_sent));
3535 		return (B_FALSE);
3536 	}
3537 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3538 	return (B_TRUE);
3539 }
3540 
3541 /*
3542  * Check if it is ok to send an IPv4 ICMP error packet in
3543  * response to the IPv4 packet in mp.
3544  * Free the message and return null if no
3545  * ICMP error packet should be sent.
3546  */
3547 static mblk_t *
3548 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3549 {
3550 	icmph_t	*icmph;
3551 	ipha_t	*ipha;
3552 	uint_t	len_needed;
3553 	ire_t	*src_ire;
3554 	ire_t	*dst_ire;
3555 
3556 	if (!mp)
3557 		return (NULL);
3558 	ipha = (ipha_t *)mp->b_rptr;
3559 	if (ip_csum_hdr(ipha)) {
3560 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3561 		freemsg(mp);
3562 		return (NULL);
3563 	}
3564 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3565 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3566 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3567 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3568 	if (src_ire != NULL || dst_ire != NULL ||
3569 	    CLASSD(ipha->ipha_dst) ||
3570 	    CLASSD(ipha->ipha_src) ||
3571 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3572 		/* Note: only errors to the fragment with offset 0 */
3573 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3574 		freemsg(mp);
3575 		if (src_ire != NULL)
3576 			ire_refrele(src_ire);
3577 		if (dst_ire != NULL)
3578 			ire_refrele(dst_ire);
3579 		return (NULL);
3580 	}
3581 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3582 		/*
3583 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3584 		 * errors in response to any ICMP errors.
3585 		 */
3586 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3587 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3588 			if (!pullupmsg(mp, len_needed)) {
3589 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3590 				freemsg(mp);
3591 				return (NULL);
3592 			}
3593 			ipha = (ipha_t *)mp->b_rptr;
3594 		}
3595 		icmph = (icmph_t *)
3596 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3597 		switch (icmph->icmph_type) {
3598 		case ICMP_DEST_UNREACHABLE:
3599 		case ICMP_SOURCE_QUENCH:
3600 		case ICMP_TIME_EXCEEDED:
3601 		case ICMP_PARAM_PROBLEM:
3602 		case ICMP_REDIRECT:
3603 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3604 			freemsg(mp);
3605 			return (NULL);
3606 		default:
3607 			break;
3608 		}
3609 	}
3610 	/*
3611 	 * If this is a labeled system, then check to see if we're allowed to
3612 	 * send a response to this particular sender.  If not, then just drop.
3613 	 */
3614 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3615 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3616 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3617 		freemsg(mp);
3618 		return (NULL);
3619 	}
3620 	if (icmp_err_rate_limit(ipst)) {
3621 		/*
3622 		 * Only send ICMP error packets every so often.
3623 		 * This should be done on a per port/source basis,
3624 		 * but for now this will suffice.
3625 		 */
3626 		freemsg(mp);
3627 		return (NULL);
3628 	}
3629 	return (mp);
3630 }
3631 
3632 /*
3633  * Generate an ICMP redirect message.
3634  */
3635 static void
3636 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3637 {
3638 	icmph_t	icmph;
3639 
3640 	/*
3641 	 * We are called from ip_rput where we could
3642 	 * not have attached an IPSEC_IN.
3643 	 */
3644 	ASSERT(mp->b_datap->db_type == M_DATA);
3645 
3646 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3647 		return;
3648 	}
3649 
3650 	bzero(&icmph, sizeof (icmph_t));
3651 	icmph.icmph_type = ICMP_REDIRECT;
3652 	icmph.icmph_code = 1;
3653 	icmph.icmph_rd_gateway = gateway;
3654 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3655 	/* Redirects sent by router, and router is global zone */
3656 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3657 }
3658 
3659 /*
3660  * Generate an ICMP time exceeded message.
3661  */
3662 void
3663 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3664     ip_stack_t *ipst)
3665 {
3666 	icmph_t	icmph;
3667 	boolean_t mctl_present;
3668 	mblk_t *first_mp;
3669 
3670 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3671 
3672 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3673 		if (mctl_present)
3674 			freeb(first_mp);
3675 		return;
3676 	}
3677 
3678 	bzero(&icmph, sizeof (icmph_t));
3679 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3680 	icmph.icmph_code = code;
3681 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3682 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3683 	    ipst);
3684 }
3685 
3686 /*
3687  * Generate an ICMP unreachable message.
3688  */
3689 void
3690 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3691     ip_stack_t *ipst)
3692 {
3693 	icmph_t	icmph;
3694 	mblk_t *first_mp;
3695 	boolean_t mctl_present;
3696 
3697 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3698 
3699 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3700 		if (mctl_present)
3701 			freeb(first_mp);
3702 		return;
3703 	}
3704 
3705 	bzero(&icmph, sizeof (icmph_t));
3706 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3707 	icmph.icmph_code = code;
3708 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3709 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3710 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3711 	    zoneid, ipst);
3712 }
3713 
3714 /*
3715  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3716  * duplicate.  As long as someone else holds the address, the interface will
3717  * stay down.  When that conflict goes away, the interface is brought back up.
3718  * This is done so that accidental shutdowns of addresses aren't made
3719  * permanent.  Your server will recover from a failure.
3720  *
3721  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3722  * user space process (dhcpagent).
3723  *
3724  * Recovery completes if ARP reports that the address is now ours (via
3725  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3726  *
3727  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3728  */
3729 static void
3730 ipif_dup_recovery(void *arg)
3731 {
3732 	ipif_t *ipif = arg;
3733 	ill_t *ill = ipif->ipif_ill;
3734 	mblk_t *arp_add_mp;
3735 	mblk_t *arp_del_mp;
3736 	area_t *area;
3737 	ip_stack_t *ipst = ill->ill_ipst;
3738 
3739 	ipif->ipif_recovery_id = 0;
3740 
3741 	/*
3742 	 * No lock needed for moving or condemned check, as this is just an
3743 	 * optimization.
3744 	 */
3745 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3746 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3747 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3748 		/* No reason to try to bring this address back. */
3749 		return;
3750 	}
3751 
3752 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3753 		goto alloc_fail;
3754 
3755 	if (ipif->ipif_arp_del_mp == NULL) {
3756 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3757 			goto alloc_fail;
3758 		ipif->ipif_arp_del_mp = arp_del_mp;
3759 	}
3760 
3761 	/* Setting the 'unverified' flag restarts DAD */
3762 	area = (area_t *)arp_add_mp->b_rptr;
3763 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3764 	    ACE_F_UNVERIFIED;
3765 	putnext(ill->ill_rq, arp_add_mp);
3766 	return;
3767 
3768 alloc_fail:
3769 	/*
3770 	 * On allocation failure, just restart the timer.  Note that the ipif
3771 	 * is down here, so no other thread could be trying to start a recovery
3772 	 * timer.  The ill_lock protects the condemned flag and the recovery
3773 	 * timer ID.
3774 	 */
3775 	freemsg(arp_add_mp);
3776 	mutex_enter(&ill->ill_lock);
3777 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3778 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3779 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3780 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3781 	}
3782 	mutex_exit(&ill->ill_lock);
3783 }
3784 
3785 /*
3786  * This is for exclusive changes due to ARP.  Either tear down an interface due
3787  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3788  */
3789 /* ARGSUSED */
3790 static void
3791 ip_arp_excl(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 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3798 	char hbuf[MAC_STR_LEN];
3799 	char sbuf[INET_ADDRSTRLEN];
3800 	const char *failtype;
3801 	boolean_t bring_up;
3802 	ip_stack_t *ipst = ill->ill_ipst;
3803 
3804 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3805 	case AR_CN_READY:
3806 		failtype = NULL;
3807 		bring_up = B_TRUE;
3808 		break;
3809 	case AR_CN_FAILED:
3810 		failtype = "in use";
3811 		bring_up = B_FALSE;
3812 		break;
3813 	default:
3814 		failtype = "claimed";
3815 		bring_up = B_FALSE;
3816 		break;
3817 	}
3818 
3819 	arh = (arh_t *)mp->b_cont->b_rptr;
3820 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3821 
3822 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3823 	    sizeof (hbuf));
3824 	(void) ip_dot_addr(src, sbuf);
3825 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3826 
3827 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3828 		    ipif->ipif_lcl_addr != src) {
3829 			continue;
3830 		}
3831 
3832 		/*
3833 		 * If we failed on a recovery probe, then restart the timer to
3834 		 * try again later.
3835 		 */
3836 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3837 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3838 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3839 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3840 		    ipst->ips_ip_dup_recovery > 0 &&
3841 		    ipif->ipif_recovery_id == 0) {
3842 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3843 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3844 			continue;
3845 		}
3846 
3847 		/*
3848 		 * If what we're trying to do has already been done, then do
3849 		 * nothing.
3850 		 */
3851 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3852 			continue;
3853 
3854 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3855 
3856 		if (failtype == NULL) {
3857 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3858 			    ibuf);
3859 		} else {
3860 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3861 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3862 		}
3863 
3864 		if (bring_up) {
3865 			ASSERT(ill->ill_dl_up);
3866 			/*
3867 			 * Free up the ARP delete message so we can allocate
3868 			 * a fresh one through the normal path.
3869 			 */
3870 			freemsg(ipif->ipif_arp_del_mp);
3871 			ipif->ipif_arp_del_mp = NULL;
3872 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3873 			    EINPROGRESS) {
3874 				ipif->ipif_addr_ready = 1;
3875 				(void) ipif_up_done(ipif);
3876 			}
3877 			continue;
3878 		}
3879 
3880 		mutex_enter(&ill->ill_lock);
3881 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3882 		ipif->ipif_flags |= IPIF_DUPLICATE;
3883 		ill->ill_ipif_dup_count++;
3884 		mutex_exit(&ill->ill_lock);
3885 		/*
3886 		 * Already exclusive on the ill; no need to handle deferred
3887 		 * processing here.
3888 		 */
3889 		(void) ipif_down(ipif, NULL, NULL);
3890 		ipif_down_tail(ipif);
3891 		mutex_enter(&ill->ill_lock);
3892 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3893 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3894 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3895 		    ipst->ips_ip_dup_recovery > 0) {
3896 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3897 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3898 		}
3899 		mutex_exit(&ill->ill_lock);
3900 	}
3901 	freemsg(mp);
3902 }
3903 
3904 /* ARGSUSED */
3905 static void
3906 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3907 {
3908 	ill_t	*ill = rq->q_ptr;
3909 	arh_t *arh;
3910 	ipaddr_t src;
3911 	ipif_t	*ipif;
3912 
3913 	arh = (arh_t *)mp->b_cont->b_rptr;
3914 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3915 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3916 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3917 			(void) ipif_resolver_up(ipif, Res_act_defend);
3918 	}
3919 	freemsg(mp);
3920 }
3921 
3922 /*
3923  * News from ARP.  ARP sends notification of interesting events down
3924  * to its clients using M_CTL messages with the interesting ARP packet
3925  * attached via b_cont.
3926  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3927  * queue as opposed to ARP sending the message to all the clients, i.e. all
3928  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3929  * table if a cache IRE is found to delete all the entries for the address in
3930  * the packet.
3931  */
3932 static void
3933 ip_arp_news(queue_t *q, mblk_t *mp)
3934 {
3935 	arcn_t		*arcn;
3936 	arh_t		*arh;
3937 	ire_t		*ire = NULL;
3938 	char		hbuf[MAC_STR_LEN];
3939 	char		sbuf[INET_ADDRSTRLEN];
3940 	ipaddr_t	src;
3941 	in6_addr_t	v6src;
3942 	boolean_t	isv6 = B_FALSE;
3943 	ipif_t		*ipif;
3944 	ill_t		*ill;
3945 	ip_stack_t	*ipst;
3946 
3947 	if (CONN_Q(q)) {
3948 		conn_t *connp = Q_TO_CONN(q);
3949 
3950 		ipst = connp->conn_netstack->netstack_ip;
3951 	} else {
3952 		ill_t *ill = (ill_t *)q->q_ptr;
3953 
3954 		ipst = ill->ill_ipst;
3955 	}
3956 
3957 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3958 		if (q->q_next) {
3959 			putnext(q, mp);
3960 		} else
3961 			freemsg(mp);
3962 		return;
3963 	}
3964 	arh = (arh_t *)mp->b_cont->b_rptr;
3965 	/* Is it one we are interested in? */
3966 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3967 		isv6 = B_TRUE;
3968 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3969 		    IPV6_ADDR_LEN);
3970 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3971 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3972 		    IP_ADDR_LEN);
3973 	} else {
3974 		freemsg(mp);
3975 		return;
3976 	}
3977 
3978 	ill = q->q_ptr;
3979 
3980 	arcn = (arcn_t *)mp->b_rptr;
3981 	switch (arcn->arcn_code) {
3982 	case AR_CN_BOGON:
3983 		/*
3984 		 * Someone is sending ARP packets with a source protocol
3985 		 * address that we have published and for which we believe our
3986 		 * entry is authoritative and (when ill_arp_extend is set)
3987 		 * verified to be unique on the network.
3988 		 *
3989 		 * The ARP module internally handles the cases where the sender
3990 		 * is just probing (for DAD) and where the hardware address of
3991 		 * a non-authoritative entry has changed.  Thus, these are the
3992 		 * real conflicts, and we have to do resolution.
3993 		 *
3994 		 * We back away quickly from the address if it's from DHCP or
3995 		 * otherwise temporary and hasn't been used recently (or at
3996 		 * all).  We'd like to include "deprecated" addresses here as
3997 		 * well (as there's no real reason to defend something we're
3998 		 * discarding), but IPMP "reuses" this flag to mean something
3999 		 * other than the standard meaning.
4000 		 *
4001 		 * If the ARP module above is not extended (meaning that it
4002 		 * doesn't know how to defend the address), then we just log
4003 		 * the problem as we always did and continue on.  It's not
4004 		 * right, but there's little else we can do, and those old ATM
4005 		 * users are going away anyway.
4006 		 */
4007 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
4008 		    hbuf, sizeof (hbuf));
4009 		(void) ip_dot_addr(src, sbuf);
4010 		if (isv6) {
4011 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
4012 			    ipst);
4013 		} else {
4014 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
4015 		}
4016 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4017 			uint32_t now;
4018 			uint32_t maxage;
4019 			clock_t lused;
4020 			uint_t maxdefense;
4021 			uint_t defs;
4022 
4023 			/*
4024 			 * First, figure out if this address hasn't been used
4025 			 * in a while.  If it hasn't, then it's a better
4026 			 * candidate for abandoning.
4027 			 */
4028 			ipif = ire->ire_ipif;
4029 			ASSERT(ipif != NULL);
4030 			now = gethrestime_sec();
4031 			maxage = now - ire->ire_create_time;
4032 			if (maxage > ipst->ips_ip_max_temp_idle)
4033 				maxage = ipst->ips_ip_max_temp_idle;
4034 			lused = drv_hztousec(ddi_get_lbolt() -
4035 			    ire->ire_last_used_time) / MICROSEC + 1;
4036 			if (lused >= maxage && (ipif->ipif_flags &
4037 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4038 				maxdefense = ipst->ips_ip_max_temp_defend;
4039 			else
4040 				maxdefense = ipst->ips_ip_max_defend;
4041 
4042 			/*
4043 			 * Now figure out how many times we've defended
4044 			 * ourselves.  Ignore defenses that happened long in
4045 			 * the past.
4046 			 */
4047 			mutex_enter(&ire->ire_lock);
4048 			if ((defs = ire->ire_defense_count) > 0 &&
4049 			    now - ire->ire_defense_time >
4050 			    ipst->ips_ip_defend_interval) {
4051 				ire->ire_defense_count = defs = 0;
4052 			}
4053 			ire->ire_defense_count++;
4054 			ire->ire_defense_time = now;
4055 			mutex_exit(&ire->ire_lock);
4056 			ill_refhold(ill);
4057 			ire_refrele(ire);
4058 
4059 			/*
4060 			 * If we've defended ourselves too many times already,
4061 			 * then give up and tear down the interface(s) using
4062 			 * this address.  Otherwise, defend by sending out a
4063 			 * gratuitous ARP.
4064 			 */
4065 			if (defs >= maxdefense && ill->ill_arp_extend) {
4066 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4067 				    B_FALSE);
4068 			} else {
4069 				cmn_err(CE_WARN,
4070 				    "node %s is using our IP address %s on %s",
4071 				    hbuf, sbuf, ill->ill_name);
4072 				/*
4073 				 * If this is an old (ATM) ARP module, then
4074 				 * don't try to defend the address.  Remain
4075 				 * compatible with the old behavior.  Defend
4076 				 * only with new ARP.
4077 				 */
4078 				if (ill->ill_arp_extend) {
4079 					qwriter_ip(ill, q, mp, ip_arp_defend,
4080 					    NEW_OP, B_FALSE);
4081 				} else {
4082 					ill_refrele(ill);
4083 				}
4084 			}
4085 			return;
4086 		}
4087 		cmn_err(CE_WARN,
4088 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4089 		    hbuf, sbuf, ill->ill_name);
4090 		if (ire != NULL)
4091 			ire_refrele(ire);
4092 		break;
4093 	case AR_CN_ANNOUNCE:
4094 		if (isv6) {
4095 			/*
4096 			 * For XRESOLV interfaces.
4097 			 * Delete the IRE cache entry and NCE for this
4098 			 * v6 address
4099 			 */
4100 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4101 			/*
4102 			 * If v6src is a non-zero, it's a router address
4103 			 * as below. Do the same sort of thing to clean
4104 			 * out off-net IRE_CACHE entries that go through
4105 			 * the router.
4106 			 */
4107 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4108 				ire_walk_v6(ire_delete_cache_gw_v6,
4109 				    (char *)&v6src, ALL_ZONES, ipst);
4110 			}
4111 		} else {
4112 			nce_hw_map_t hwm;
4113 
4114 			/*
4115 			 * ARP gives us a copy of any packet where it thinks
4116 			 * the address has changed, so that we can update our
4117 			 * caches.  We're responsible for caching known answers
4118 			 * in the current design.  We check whether the
4119 			 * hardware address really has changed in all of our
4120 			 * entries that have cached this mapping, and if so, we
4121 			 * blow them away.  This way we will immediately pick
4122 			 * up the rare case of a host changing hardware
4123 			 * address.
4124 			 */
4125 			if (src == 0)
4126 				break;
4127 			hwm.hwm_addr = src;
4128 			hwm.hwm_hwlen = arh->arh_hlen;
4129 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4130 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4131 			ndp_walk_common(ipst->ips_ndp4, NULL,
4132 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4133 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4134 		}
4135 		break;
4136 	case AR_CN_READY:
4137 		/* No external v6 resolver has a contract to use this */
4138 		if (isv6)
4139 			break;
4140 		/* If the link is down, we'll retry this later */
4141 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4142 			break;
4143 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4144 		    NULL, NULL, ipst);
4145 		if (ipif != NULL) {
4146 			/*
4147 			 * If this is a duplicate recovery, then we now need to
4148 			 * go exclusive to bring this thing back up.
4149 			 */
4150 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4151 			    IPIF_DUPLICATE) {
4152 				ipif_refrele(ipif);
4153 				ill_refhold(ill);
4154 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4155 				    B_FALSE);
4156 				return;
4157 			}
4158 			/*
4159 			 * If this is the first notice that this address is
4160 			 * ready, then let the user know now.
4161 			 */
4162 			if ((ipif->ipif_flags & IPIF_UP) &&
4163 			    !ipif->ipif_addr_ready) {
4164 				ipif_mask_reply(ipif);
4165 				ipif_up_notify(ipif);
4166 			}
4167 			ipif->ipif_addr_ready = 1;
4168 			ipif_refrele(ipif);
4169 		}
4170 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4171 		if (ire != NULL) {
4172 			ire->ire_defense_count = 0;
4173 			ire_refrele(ire);
4174 		}
4175 		break;
4176 	case AR_CN_FAILED:
4177 		/* No external v6 resolver has a contract to use this */
4178 		if (isv6)
4179 			break;
4180 		ill_refhold(ill);
4181 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4182 		return;
4183 	}
4184 	freemsg(mp);
4185 }
4186 
4187 /*
4188  * Create a mblk suitable for carrying the interface index and/or source link
4189  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4190  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4191  * application.
4192  */
4193 mblk_t *
4194 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4195     ip_stack_t *ipst)
4196 {
4197 	mblk_t		*mp;
4198 	ip_pktinfo_t	*pinfo;
4199 	ipha_t *ipha;
4200 	struct ether_header *pether;
4201 
4202 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4203 	if (mp == NULL) {
4204 		ip1dbg(("ip_add_info: allocation failure.\n"));
4205 		return (data_mp);
4206 	}
4207 
4208 	ipha	= (ipha_t *)data_mp->b_rptr;
4209 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4210 	bzero(pinfo, sizeof (ip_pktinfo_t));
4211 	pinfo->ip_pkt_flags = (uchar_t)flags;
4212 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4213 
4214 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4215 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4216 	if (flags & IPF_RECVADDR) {
4217 		ipif_t	*ipif;
4218 		ire_t	*ire;
4219 
4220 		/*
4221 		 * Only valid for V4
4222 		 */
4223 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4224 		    (IPV4_VERSION << 4));
4225 
4226 		ipif = ipif_get_next_ipif(NULL, ill);
4227 		if (ipif != NULL) {
4228 			/*
4229 			 * Since a decision has already been made to deliver the
4230 			 * packet, there is no need to test for SECATTR and
4231 			 * ZONEONLY.
4232 			 * When a multicast packet is transmitted
4233 			 * a cache entry is created for the multicast address.
4234 			 * When delivering a copy of the packet or when new
4235 			 * packets are received we do not want to match on the
4236 			 * cached entry so explicitly match on
4237 			 * IRE_LOCAL and IRE_LOOPBACK
4238 			 */
4239 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4240 			    IRE_LOCAL | IRE_LOOPBACK,
4241 			    ipif, zoneid, NULL,
4242 			    MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP, ipst);
4243 			if (ire == NULL) {
4244 				/*
4245 				 * packet must have come on a different
4246 				 * interface.
4247 				 * Since a decision has already been made to
4248 				 * deliver the packet, there is no need to test
4249 				 * for SECATTR and ZONEONLY.
4250 				 * Only match on local and broadcast ire's.
4251 				 * See detailed comment above.
4252 				 */
4253 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4254 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4255 				    NULL, MATCH_IRE_TYPE, ipst);
4256 			}
4257 
4258 			if (ire == NULL) {
4259 				/*
4260 				 * This is either a multicast packet or
4261 				 * the address has been removed since
4262 				 * the packet was received.
4263 				 * Return INADDR_ANY so that normal source
4264 				 * selection occurs for the response.
4265 				 */
4266 
4267 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4268 			} else {
4269 				pinfo->ip_pkt_match_addr.s_addr =
4270 				    ire->ire_src_addr;
4271 				ire_refrele(ire);
4272 			}
4273 			ipif_refrele(ipif);
4274 		} else {
4275 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4276 		}
4277 	}
4278 
4279 	pether = (struct ether_header *)((char *)ipha
4280 	    - sizeof (struct ether_header));
4281 	/*
4282 	 * Make sure the interface is an ethernet type, since this option
4283 	 * is currently supported only on this type of interface. Also make
4284 	 * sure we are pointing correctly above db_base.
4285 	 */
4286 
4287 	if ((flags & IPF_RECVSLLA) &&
4288 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4289 	    (ill->ill_type == IFT_ETHER) &&
4290 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4291 
4292 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4293 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4294 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4295 	} else {
4296 		/*
4297 		 * Clear the bit. Indicate to upper layer that IP is not
4298 		 * sending this ancillary info.
4299 		 */
4300 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4301 	}
4302 
4303 	mp->b_datap->db_type = M_CTL;
4304 	mp->b_wptr += sizeof (ip_pktinfo_t);
4305 	mp->b_cont = data_mp;
4306 
4307 	return (mp);
4308 }
4309 
4310 /*
4311  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4312  * part of the bind request.
4313  */
4314 
4315 boolean_t
4316 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4317 {
4318 	ipsec_in_t *ii;
4319 
4320 	ASSERT(policy_mp != NULL);
4321 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4322 
4323 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4324 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4325 
4326 	connp->conn_policy = ii->ipsec_in_policy;
4327 	ii->ipsec_in_policy = NULL;
4328 
4329 	if (ii->ipsec_in_action != NULL) {
4330 		if (connp->conn_latch == NULL) {
4331 			connp->conn_latch = iplatch_create();
4332 			if (connp->conn_latch == NULL)
4333 				return (B_FALSE);
4334 		}
4335 		ipsec_latch_inbound(connp->conn_latch, ii);
4336 	}
4337 	return (B_TRUE);
4338 }
4339 
4340 static void
4341 ip_bind_post_handling(conn_t *connp, mblk_t *mp, boolean_t ire_requested)
4342 {
4343 	/*
4344 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4345 	 * We can't do this in ip_bind_get_ire because the policy
4346 	 * may not have been inherited at that point in time and hence
4347 	 * conn_out_enforce_policy may not be set.
4348 	 */
4349 	if (ire_requested && connp->conn_out_enforce_policy &&
4350 	    mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE) {
4351 		ire_t *ire = (ire_t *)mp->b_rptr;
4352 		ASSERT(MBLKL(mp) >= sizeof (ire_t));
4353 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4354 	}
4355 }
4356 
4357 /*
4358  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4359  * and to arrange for power-fanout assist.  The ULP is identified by
4360  * adding a single byte at the end of the original bind message.
4361  * A ULP other than UDP or TCP that wishes to be recognized passes
4362  * down a bind with a zero length address.
4363  *
4364  * The binding works as follows:
4365  * - A zero byte address means just bind to the protocol.
4366  * - A four byte address is treated as a request to validate
4367  *   that the address is a valid local address, appropriate for
4368  *   an application to bind to. This does not affect any fanout
4369  *   information in IP.
4370  * - A sizeof sin_t byte address is used to bind to only the local address
4371  *   and port.
4372  * - A sizeof ipa_conn_t byte address contains complete fanout information
4373  *   consisting of local and remote addresses and ports.  In
4374  *   this case, the addresses are both validated as appropriate
4375  *   for this operation, and, if so, the information is retained
4376  *   for use in the inbound fanout.
4377  *
4378  * The ULP (except in the zero-length bind) can append an
4379  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4380  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4381  * a copy of the source or destination IRE (source for local bind;
4382  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4383  * policy information contained should be copied on to the conn.
4384  *
4385  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4386  */
4387 mblk_t *
4388 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4389 {
4390 	ssize_t		len;
4391 	struct T_bind_req	*tbr;
4392 	sin_t		*sin;
4393 	ipa_conn_t	*ac;
4394 	uchar_t		*ucp;
4395 	mblk_t		*mp1;
4396 	boolean_t	ire_requested;
4397 	int		error = 0;
4398 	int		protocol;
4399 	ipa_conn_x_t	*acx;
4400 
4401 	ASSERT(!connp->conn_af_isv6);
4402 	connp->conn_pkt_isv6 = B_FALSE;
4403 
4404 	len = MBLKL(mp);
4405 	if (len < (sizeof (*tbr) + 1)) {
4406 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4407 		    "ip_bind: bogus msg, len %ld", len);
4408 		/* XXX: Need to return something better */
4409 		goto bad_addr;
4410 	}
4411 	/* Back up and extract the protocol identifier. */
4412 	mp->b_wptr--;
4413 	protocol = *mp->b_wptr & 0xFF;
4414 	tbr = (struct T_bind_req *)mp->b_rptr;
4415 	/* Reset the message type in preparation for shipping it back. */
4416 	DB_TYPE(mp) = M_PCPROTO;
4417 
4418 	connp->conn_ulp = (uint8_t)protocol;
4419 
4420 	/*
4421 	 * Check for a zero length address.  This is from a protocol that
4422 	 * wants to register to receive all packets of its type.
4423 	 */
4424 	if (tbr->ADDR_length == 0) {
4425 		/*
4426 		 * These protocols are now intercepted in ip_bind_v6().
4427 		 * Reject protocol-level binds here for now.
4428 		 *
4429 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4430 		 * so that the protocol type cannot be SCTP.
4431 		 */
4432 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4433 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4434 			goto bad_addr;
4435 		}
4436 
4437 		/*
4438 		 *
4439 		 * The udp module never sends down a zero-length address,
4440 		 * and allowing this on a labeled system will break MLP
4441 		 * functionality.
4442 		 */
4443 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4444 			goto bad_addr;
4445 
4446 		if (connp->conn_mac_exempt)
4447 			goto bad_addr;
4448 
4449 		/* No hash here really.  The table is big enough. */
4450 		connp->conn_srcv6 = ipv6_all_zeros;
4451 
4452 		ipcl_proto_insert(connp, protocol);
4453 
4454 		tbr->PRIM_type = T_BIND_ACK;
4455 		return (mp);
4456 	}
4457 
4458 	/* Extract the address pointer from the message. */
4459 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4460 	    tbr->ADDR_length);
4461 	if (ucp == NULL) {
4462 		ip1dbg(("ip_bind: no address\n"));
4463 		goto bad_addr;
4464 	}
4465 	if (!OK_32PTR(ucp)) {
4466 		ip1dbg(("ip_bind: unaligned address\n"));
4467 		goto bad_addr;
4468 	}
4469 	/*
4470 	 * Check for trailing mps.
4471 	 */
4472 
4473 	mp1 = mp->b_cont;
4474 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4475 
4476 	switch (tbr->ADDR_length) {
4477 	default:
4478 		ip1dbg(("ip_bind: bad address length %d\n",
4479 		    (int)tbr->ADDR_length));
4480 		goto bad_addr;
4481 
4482 	case IP_ADDR_LEN:
4483 		/* Verification of local address only */
4484 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4485 		    *(ipaddr_t *)ucp, 0, B_FALSE);
4486 		break;
4487 
4488 	case sizeof (sin_t):
4489 		sin = (sin_t *)ucp;
4490 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4491 		    sin->sin_addr.s_addr, sin->sin_port, B_TRUE);
4492 		break;
4493 
4494 	case sizeof (ipa_conn_t):
4495 		ac = (ipa_conn_t *)ucp;
4496 		/* For raw socket, the local port is not set. */
4497 		if (ac->ac_lport == 0)
4498 			ac->ac_lport = connp->conn_lport;
4499 		/* Always verify destination reachability. */
4500 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4501 		    &ac->ac_laddr, ac->ac_lport, ac->ac_faddr, ac->ac_fport,
4502 		    B_TRUE, B_TRUE);
4503 		break;
4504 
4505 	case sizeof (ipa_conn_x_t):
4506 		acx = (ipa_conn_x_t *)ucp;
4507 		/*
4508 		 * Whether or not to verify destination reachability depends
4509 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4510 		 */
4511 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4512 		    &acx->acx_conn.ac_laddr, acx->acx_conn.ac_lport,
4513 		    acx->acx_conn.ac_faddr, acx->acx_conn.ac_fport,
4514 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4515 		break;
4516 	}
4517 	ASSERT(error != EINPROGRESS);
4518 	if (error != 0)
4519 		goto bad_addr;
4520 
4521 	ip_bind_post_handling(connp, mp->b_cont, ire_requested);
4522 
4523 	/* Send it home. */
4524 	mp->b_datap->db_type = M_PCPROTO;
4525 	tbr->PRIM_type = T_BIND_ACK;
4526 	return (mp);
4527 
4528 bad_addr:
4529 	/*
4530 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4531 	 * a unix errno.
4532 	 */
4533 	if (error > 0)
4534 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4535 	else
4536 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4537 	return (mp);
4538 }
4539 
4540 /*
4541  * Here address is verified to be a valid local address.
4542  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4543  * address is also considered a valid local address.
4544  * In the case of a broadcast/multicast address, however, the
4545  * upper protocol is expected to reset the src address
4546  * to 0 if it sees a IRE_BROADCAST type returned so that
4547  * no packets are emitted with broadcast/multicast address as
4548  * source address (that violates hosts requirements RFC 1122)
4549  * The addresses valid for bind are:
4550  *	(1) - INADDR_ANY (0)
4551  *	(2) - IP address of an UP interface
4552  *	(3) - IP address of a DOWN interface
4553  *	(4) - valid local IP broadcast addresses. In this case
4554  *	the conn will only receive packets destined to
4555  *	the specified broadcast address.
4556  *	(5) - a multicast address. In this case
4557  *	the conn will only receive packets destined to
4558  *	the specified multicast address. Note: the
4559  *	application still has to issue an
4560  *	IP_ADD_MEMBERSHIP socket option.
4561  *
4562  * On error, return -1 for TBADADDR otherwise pass the
4563  * errno with TSYSERR reply.
4564  *
4565  * In all the above cases, the bound address must be valid in the current zone.
4566  * When the address is loopback, multicast or broadcast, there might be many
4567  * matching IREs so bind has to look up based on the zone.
4568  *
4569  * Note: lport is in network byte order.
4570  *
4571  */
4572 int
4573 ip_bind_laddr_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4574     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4575 {
4576 	int		error = 0;
4577 	ire_t		*src_ire;
4578 	zoneid_t	zoneid;
4579 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4580 	mblk_t		*mp = NULL;
4581 	boolean_t	ire_requested = B_FALSE;
4582 	boolean_t	ipsec_policy_set = B_FALSE;
4583 
4584 	if (mpp)
4585 		mp = *mpp;
4586 
4587 	if (mp != NULL) {
4588 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4589 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4590 	}
4591 
4592 	/*
4593 	 * If it was previously connected, conn_fully_bound would have
4594 	 * been set.
4595 	 */
4596 	connp->conn_fully_bound = B_FALSE;
4597 
4598 	src_ire = NULL;
4599 
4600 	zoneid = IPCL_ZONEID(connp);
4601 
4602 	if (src_addr) {
4603 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4604 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4605 		/*
4606 		 * If an address other than 0.0.0.0 is requested,
4607 		 * we verify that it is a valid address for bind
4608 		 * Note: Following code is in if-else-if form for
4609 		 * readability compared to a condition check.
4610 		 */
4611 		/* LINTED - statement has no consequence */
4612 		if (IRE_IS_LOCAL(src_ire)) {
4613 			/*
4614 			 * (2) Bind to address of local UP interface
4615 			 */
4616 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4617 			/*
4618 			 * (4) Bind to broadcast address
4619 			 * Note: permitted only from transports that
4620 			 * request IRE
4621 			 */
4622 			if (!ire_requested)
4623 				error = EADDRNOTAVAIL;
4624 		} else {
4625 			/*
4626 			 * (3) Bind to address of local DOWN interface
4627 			 * (ipif_lookup_addr() looks up all interfaces
4628 			 * but we do not get here for UP interfaces
4629 			 * - case (2) above)
4630 			 */
4631 			/* LINTED - statement has no consequent */
4632 			if (ip_addr_exists(src_addr, zoneid, ipst)) {
4633 				/* The address exists */
4634 			} else if (CLASSD(src_addr)) {
4635 				error = 0;
4636 				if (src_ire != NULL)
4637 					ire_refrele(src_ire);
4638 				/*
4639 				 * (5) bind to multicast address.
4640 				 * Fake out the IRE returned to upper
4641 				 * layer to be a broadcast IRE.
4642 				 */
4643 				src_ire = ire_ctable_lookup(
4644 				    INADDR_BROADCAST, INADDR_ANY,
4645 				    IRE_BROADCAST, NULL, zoneid, NULL,
4646 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4647 				    ipst);
4648 				if (src_ire == NULL || !ire_requested)
4649 					error = EADDRNOTAVAIL;
4650 			} else {
4651 				/*
4652 				 * Not a valid address for bind
4653 				 */
4654 				error = EADDRNOTAVAIL;
4655 			}
4656 		}
4657 		if (error) {
4658 			/* Red Alert!  Attempting to be a bogon! */
4659 			ip1dbg(("ip_bind_laddr_v4: bad src address 0x%x\n",
4660 			    ntohl(src_addr)));
4661 			goto bad_addr;
4662 		}
4663 	}
4664 
4665 
4666 	/*
4667 	 * Allow setting new policies. For example, disconnects come
4668 	 * down as ipa_t bind. As we would have set conn_policy_cached
4669 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4670 	 * can change after the disconnect.
4671 	 */
4672 	connp->conn_policy_cached = B_FALSE;
4673 
4674 	/*
4675 	 * If not fanout_insert this was just an address verification
4676 	 */
4677 	if (fanout_insert) {
4678 		/*
4679 		 * The addresses have been verified. Time to insert in
4680 		 * the correct fanout list.
4681 		 */
4682 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4683 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4684 		connp->conn_lport = lport;
4685 		connp->conn_fport = 0;
4686 		/*
4687 		 * Do we need to add a check to reject Multicast packets
4688 		 */
4689 		error = ipcl_bind_insert(connp, protocol, src_addr, lport);
4690 	}
4691 
4692 	if (error == 0) {
4693 		if (ire_requested) {
4694 			if (!ip_bind_get_ire_v4(mpp, src_ire, NULL, ipst)) {
4695 				error = -1;
4696 				/* Falls through to bad_addr */
4697 			}
4698 		} else if (ipsec_policy_set) {
4699 			if (!ip_bind_ipsec_policy_set(connp, mp)) {
4700 				error = -1;
4701 				/* Falls through to bad_addr */
4702 			}
4703 		}
4704 	}
4705 bad_addr:
4706 	if (error != 0) {
4707 		if (connp->conn_anon_port) {
4708 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4709 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4710 			    B_FALSE);
4711 		}
4712 		connp->conn_mlp_type = mlptSingle;
4713 	}
4714 	if (src_ire != NULL)
4715 		IRE_REFRELE(src_ire);
4716 	return (error);
4717 }
4718 
4719 int
4720 ip_proto_bind_laddr_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
4721     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4722 {
4723 	int error;
4724 	mblk_t	*mp = NULL;
4725 	boolean_t ire_requested;
4726 
4727 	if (ire_mpp)
4728 		mp = *ire_mpp;
4729 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4730 
4731 	ASSERT(!connp->conn_af_isv6);
4732 	connp->conn_pkt_isv6 = B_FALSE;
4733 	connp->conn_ulp = protocol;
4734 
4735 	error = ip_bind_laddr_v4(connp, ire_mpp, protocol, src_addr, lport,
4736 	    fanout_insert);
4737 	if (error == 0) {
4738 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
4739 		    ire_requested);
4740 	} else if (error < 0) {
4741 		error = -TBADADDR;
4742 	}
4743 	return (error);
4744 }
4745 
4746 /*
4747  * Verify that both the source and destination addresses
4748  * are valid.  If verify_dst is false, then the destination address may be
4749  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4750  * destination reachability, while tunnels do not.
4751  * Note that we allow connect to broadcast and multicast
4752  * addresses when ire_requested is set. Thus the ULP
4753  * has to check for IRE_BROADCAST and multicast.
4754  *
4755  * Returns zero if ok.
4756  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4757  * (for use with TSYSERR reply).
4758  *
4759  * Note: lport and fport are in network byte order.
4760  */
4761 int
4762 ip_bind_connected_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4763     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4764     boolean_t fanout_insert, boolean_t verify_dst)
4765 {
4766 
4767 	ire_t		*src_ire;
4768 	ire_t		*dst_ire;
4769 	int		error = 0;
4770 	ire_t		*sire = NULL;
4771 	ire_t		*md_dst_ire = NULL;
4772 	ire_t		*lso_dst_ire = NULL;
4773 	ill_t		*ill = NULL;
4774 	zoneid_t	zoneid;
4775 	ipaddr_t	src_addr = *src_addrp;
4776 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4777 	mblk_t		*mp = NULL;
4778 	boolean_t	ire_requested = B_FALSE;
4779 	boolean_t	ipsec_policy_set = B_FALSE;
4780 	ts_label_t	*tsl = NULL;
4781 
4782 	if (mpp)
4783 		mp = *mpp;
4784 
4785 	if (mp != NULL) {
4786 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4787 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4788 		tsl = MBLK_GETLABEL(mp);
4789 	}
4790 
4791 	src_ire = dst_ire = NULL;
4792 
4793 	/*
4794 	 * If we never got a disconnect before, clear it now.
4795 	 */
4796 	connp->conn_fully_bound = B_FALSE;
4797 
4798 	zoneid = IPCL_ZONEID(connp);
4799 
4800 	if (CLASSD(dst_addr)) {
4801 		/* Pick up an IRE_BROADCAST */
4802 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4803 		    NULL, zoneid, tsl,
4804 		    (MATCH_IRE_RECURSIVE |
4805 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4806 		    MATCH_IRE_SECATTR), ipst);
4807 	} else {
4808 		/*
4809 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4810 		 * and onlink ipif is not found set ENETUNREACH error.
4811 		 */
4812 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4813 			ipif_t *ipif;
4814 
4815 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4816 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4817 			if (ipif == NULL) {
4818 				error = ENETUNREACH;
4819 				goto bad_addr;
4820 			}
4821 			ipif_refrele(ipif);
4822 		}
4823 
4824 		if (connp->conn_nexthop_set) {
4825 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4826 			    0, 0, NULL, NULL, zoneid, tsl,
4827 			    MATCH_IRE_SECATTR, ipst);
4828 		} else {
4829 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4830 			    &sire, zoneid, tsl,
4831 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4832 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4833 			    MATCH_IRE_SECATTR), ipst);
4834 		}
4835 	}
4836 	/*
4837 	 * dst_ire can't be a broadcast when not ire_requested.
4838 	 * We also prevent ire's with src address INADDR_ANY to
4839 	 * be used, which are created temporarily for
4840 	 * sending out packets from endpoints that have
4841 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4842 	 * reachable.  If verify_dst is false, the destination needn't be
4843 	 * reachable.
4844 	 *
4845 	 * If we match on a reject or black hole, then we've got a
4846 	 * local failure.  May as well fail out the connect() attempt,
4847 	 * since it's never going to succeed.
4848 	 */
4849 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4850 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4851 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4852 		/*
4853 		 * If we're verifying destination reachability, we always want
4854 		 * to complain here.
4855 		 *
4856 		 * If we're not verifying destination reachability but the
4857 		 * destination has a route, we still want to fail on the
4858 		 * temporary address and broadcast address tests.
4859 		 */
4860 		if (verify_dst || (dst_ire != NULL)) {
4861 			if (ip_debug > 2) {
4862 				pr_addr_dbg("ip_bind_connected_v4:"
4863 				    "bad connected dst %s\n",
4864 				    AF_INET, &dst_addr);
4865 			}
4866 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4867 				error = ENETUNREACH;
4868 			else
4869 				error = EHOSTUNREACH;
4870 			goto bad_addr;
4871 		}
4872 	}
4873 
4874 	/*
4875 	 * We now know that routing will allow us to reach the destination.
4876 	 * Check whether Trusted Solaris policy allows communication with this
4877 	 * host, and pretend that the destination is unreachable if not.
4878 	 *
4879 	 * This is never a problem for TCP, since that transport is known to
4880 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4881 	 * handling.  If the remote is unreachable, it will be detected at that
4882 	 * point, so there's no reason to check it here.
4883 	 *
4884 	 * Note that for sendto (and other datagram-oriented friends), this
4885 	 * check is done as part of the data path label computation instead.
4886 	 * The check here is just to make non-TCP connect() report the right
4887 	 * error.
4888 	 */
4889 	if (dst_ire != NULL && is_system_labeled() &&
4890 	    !IPCL_IS_TCP(connp) &&
4891 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4892 	    connp->conn_mac_exempt, ipst) != 0) {
4893 		error = EHOSTUNREACH;
4894 		if (ip_debug > 2) {
4895 			pr_addr_dbg("ip_bind_connected_v4:"
4896 			    " no label for dst %s\n",
4897 			    AF_INET, &dst_addr);
4898 		}
4899 		goto bad_addr;
4900 	}
4901 
4902 	/*
4903 	 * If the app does a connect(), it means that it will most likely
4904 	 * send more than 1 packet to the destination.  It makes sense
4905 	 * to clear the temporary flag.
4906 	 */
4907 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4908 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4909 		irb_t *irb = dst_ire->ire_bucket;
4910 
4911 		rw_enter(&irb->irb_lock, RW_WRITER);
4912 		/*
4913 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4914 		 * the lock to guarantee irb_tmp_ire_cnt.
4915 		 */
4916 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4917 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4918 			irb->irb_tmp_ire_cnt--;
4919 		}
4920 		rw_exit(&irb->irb_lock);
4921 	}
4922 
4923 	/*
4924 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4925 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4926 	 * eligibility tests for passive connects are handled separately
4927 	 * through tcp_adapt_ire().  We do this before the source address
4928 	 * selection, because dst_ire may change after a call to
4929 	 * ipif_select_source().  This is a best-effort check, as the
4930 	 * packet for this connection may not actually go through
4931 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4932 	 * calling ip_newroute().  This is why we further check on the
4933 	 * IRE during LSO/Multidata packet transmission in
4934 	 * tcp_lsosend()/tcp_multisend().
4935 	 */
4936 	if (!ipsec_policy_set && dst_ire != NULL &&
4937 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4938 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4939 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4940 			lso_dst_ire = dst_ire;
4941 			IRE_REFHOLD(lso_dst_ire);
4942 		} else if (ipst->ips_ip_multidata_outbound &&
4943 		    ILL_MDT_CAPABLE(ill)) {
4944 			md_dst_ire = dst_ire;
4945 			IRE_REFHOLD(md_dst_ire);
4946 		}
4947 	}
4948 
4949 	if (dst_ire != NULL &&
4950 	    dst_ire->ire_type == IRE_LOCAL &&
4951 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4952 		/*
4953 		 * If the IRE belongs to a different zone, look for a matching
4954 		 * route in the forwarding table and use the source address from
4955 		 * that route.
4956 		 */
4957 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4958 		    zoneid, 0, NULL,
4959 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4960 		    MATCH_IRE_RJ_BHOLE, ipst);
4961 		if (src_ire == NULL) {
4962 			error = EHOSTUNREACH;
4963 			goto bad_addr;
4964 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4965 			if (!(src_ire->ire_type & IRE_HOST))
4966 				error = ENETUNREACH;
4967 			else
4968 				error = EHOSTUNREACH;
4969 			goto bad_addr;
4970 		}
4971 		if (src_addr == INADDR_ANY)
4972 			src_addr = src_ire->ire_src_addr;
4973 		ire_refrele(src_ire);
4974 		src_ire = NULL;
4975 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4976 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4977 			src_addr = sire->ire_src_addr;
4978 			ire_refrele(dst_ire);
4979 			dst_ire = sire;
4980 			sire = NULL;
4981 		} else {
4982 			/*
4983 			 * Pick a source address so that a proper inbound
4984 			 * load spreading would happen.
4985 			 */
4986 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4987 			ipif_t *src_ipif = NULL;
4988 			ire_t *ipif_ire;
4989 
4990 			/*
4991 			 * Supply a local source address such that inbound
4992 			 * load spreading happens.
4993 			 *
4994 			 * Determine the best source address on this ill for
4995 			 * the destination.
4996 			 *
4997 			 * 1) For broadcast, we should return a broadcast ire
4998 			 *    found above so that upper layers know that the
4999 			 *    destination address is a broadcast address.
5000 			 *
5001 			 * 2) If this is part of a group, select a better
5002 			 *    source address so that better inbound load
5003 			 *    balancing happens. Do the same if the ipif
5004 			 *    is DEPRECATED.
5005 			 *
5006 			 * 3) If the outgoing interface is part of a usesrc
5007 			 *    group, then try selecting a source address from
5008 			 *    the usesrc ILL.
5009 			 */
5010 			if ((dst_ire->ire_zoneid != zoneid &&
5011 			    dst_ire->ire_zoneid != ALL_ZONES) ||
5012 			    (!(dst_ire->ire_flags & RTF_SETSRC)) &&
5013 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
5014 			    ((dst_ill->ill_group != NULL) ||
5015 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
5016 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
5017 				/*
5018 				 * If the destination is reachable via a
5019 				 * given gateway, the selected source address
5020 				 * should be in the same subnet as the gateway.
5021 				 * Otherwise, the destination is not reachable.
5022 				 *
5023 				 * If there are no interfaces on the same subnet
5024 				 * as the destination, ipif_select_source gives
5025 				 * first non-deprecated interface which might be
5026 				 * on a different subnet than the gateway.
5027 				 * This is not desirable. Hence pass the dst_ire
5028 				 * source address to ipif_select_source.
5029 				 * It is sure that the destination is reachable
5030 				 * with the dst_ire source address subnet.
5031 				 * So passing dst_ire source address to
5032 				 * ipif_select_source will make sure that the
5033 				 * selected source will be on the same subnet
5034 				 * as dst_ire source address.
5035 				 */
5036 				ipaddr_t saddr =
5037 				    dst_ire->ire_ipif->ipif_src_addr;
5038 				src_ipif = ipif_select_source(dst_ill,
5039 				    saddr, zoneid);
5040 				if (src_ipif != NULL) {
5041 					if (IS_VNI(src_ipif->ipif_ill)) {
5042 						/*
5043 						 * For VNI there is no
5044 						 * interface route
5045 						 */
5046 						src_addr =
5047 						    src_ipif->ipif_src_addr;
5048 					} else {
5049 						ipif_ire =
5050 						    ipif_to_ire(src_ipif);
5051 						if (ipif_ire != NULL) {
5052 							IRE_REFRELE(dst_ire);
5053 							dst_ire = ipif_ire;
5054 						}
5055 						src_addr =
5056 						    dst_ire->ire_src_addr;
5057 					}
5058 					ipif_refrele(src_ipif);
5059 				} else {
5060 					src_addr = dst_ire->ire_src_addr;
5061 				}
5062 			} else {
5063 				src_addr = dst_ire->ire_src_addr;
5064 			}
5065 		}
5066 	}
5067 
5068 	/*
5069 	 * We do ire_route_lookup() here (and not
5070 	 * interface lookup as we assert that
5071 	 * src_addr should only come from an
5072 	 * UP interface for hard binding.
5073 	 */
5074 	ASSERT(src_ire == NULL);
5075 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5076 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5077 	/* src_ire must be a local|loopback */
5078 	if (!IRE_IS_LOCAL(src_ire)) {
5079 		if (ip_debug > 2) {
5080 			pr_addr_dbg("ip_bind_connected_v4: bad connected "
5081 			    "src %s\n", AF_INET, &src_addr);
5082 		}
5083 		error = EADDRNOTAVAIL;
5084 		goto bad_addr;
5085 	}
5086 
5087 	/*
5088 	 * If the source address is a loopback address, the
5089 	 * destination had best be local or multicast.
5090 	 * The transports that can't handle multicast will reject
5091 	 * those addresses.
5092 	 */
5093 	if (src_ire->ire_type == IRE_LOOPBACK &&
5094 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5095 		ip1dbg(("ip_bind_connected_v4: bad connected loopback\n"));
5096 		error = -1;
5097 		goto bad_addr;
5098 	}
5099 
5100 	/*
5101 	 * Allow setting new policies. For example, disconnects come
5102 	 * down as ipa_t bind. As we would have set conn_policy_cached
5103 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5104 	 * can change after the disconnect.
5105 	 */
5106 	connp->conn_policy_cached = B_FALSE;
5107 
5108 	/*
5109 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5110 	 * can handle their passed-in conn's.
5111 	 */
5112 
5113 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5114 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5115 	connp->conn_lport = lport;
5116 	connp->conn_fport = fport;
5117 	*src_addrp = src_addr;
5118 
5119 	ASSERT(!(ipsec_policy_set && ire_requested));
5120 	if (ire_requested) {
5121 		iulp_t *ulp_info = NULL;
5122 
5123 		/*
5124 		 * Note that sire will not be NULL if this is an off-link
5125 		 * connection and there is not cache for that dest yet.
5126 		 *
5127 		 * XXX Because of an existing bug, if there are multiple
5128 		 * default routes, the IRE returned now may not be the actual
5129 		 * default route used (default routes are chosen in a
5130 		 * round robin fashion).  So if the metrics for different
5131 		 * default routes are different, we may return the wrong
5132 		 * metrics.  This will not be a problem if the existing
5133 		 * bug is fixed.
5134 		 */
5135 		if (sire != NULL) {
5136 			ulp_info = &(sire->ire_uinfo);
5137 		}
5138 		if (!ip_bind_get_ire_v4(mpp, dst_ire, ulp_info, ipst)) {
5139 			error = -1;
5140 			goto bad_addr;
5141 		}
5142 		mp = *mpp;
5143 	} else if (ipsec_policy_set) {
5144 		if (!ip_bind_ipsec_policy_set(connp, mp)) {
5145 			error = -1;
5146 			goto bad_addr;
5147 		}
5148 	}
5149 
5150 	/*
5151 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5152 	 * we'll cache that.  If we don't, we'll inherit global policy.
5153 	 *
5154 	 * We can't insert until the conn reflects the policy. Note that
5155 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5156 	 * connections where we don't have a policy. This is to prevent
5157 	 * global policy lookups in the inbound path.
5158 	 *
5159 	 * If we insert before we set conn_policy_cached,
5160 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5161 	 * because global policy cound be non-empty. We normally call
5162 	 * ipsec_check_policy() for conn_policy_cached connections only if
5163 	 * ipc_in_enforce_policy is set. But in this case,
5164 	 * conn_policy_cached can get set anytime since we made the
5165 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5166 	 * called, which will make the above assumption false.  Thus, we
5167 	 * need to insert after we set conn_policy_cached.
5168 	 */
5169 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5170 		goto bad_addr;
5171 
5172 	if (fanout_insert) {
5173 		/*
5174 		 * The addresses have been verified. Time to insert in
5175 		 * the correct fanout list.
5176 		 */
5177 		error = ipcl_conn_insert(connp, protocol, src_addr,
5178 		    dst_addr, connp->conn_ports);
5179 	}
5180 
5181 	if (error == 0) {
5182 		connp->conn_fully_bound = B_TRUE;
5183 		/*
5184 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5185 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5186 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5187 		 * ip_xxinfo_return(), which performs further checks
5188 		 * against them and upon success, returns the LSO/MDT info
5189 		 * mblk which we will attach to the bind acknowledgment.
5190 		 */
5191 		if (lso_dst_ire != NULL) {
5192 			mblk_t *lsoinfo_mp;
5193 
5194 			ASSERT(ill->ill_lso_capab != NULL);
5195 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5196 			    ill->ill_name, ill->ill_lso_capab)) != NULL) {
5197 				if (mp == NULL) {
5198 					*mpp = lsoinfo_mp;
5199 				} else {
5200 					linkb(mp, lsoinfo_mp);
5201 				}
5202 			}
5203 		} else if (md_dst_ire != NULL) {
5204 			mblk_t *mdinfo_mp;
5205 
5206 			ASSERT(ill->ill_mdt_capab != NULL);
5207 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5208 			    ill->ill_name, ill->ill_mdt_capab)) != NULL) {
5209 				if (mp == NULL) {
5210 					*mpp = mdinfo_mp;
5211 				} else {
5212 					linkb(mp, mdinfo_mp);
5213 				}
5214 			}
5215 		}
5216 	}
5217 bad_addr:
5218 	if (ipsec_policy_set) {
5219 		ASSERT(mp != NULL);
5220 		freeb(mp);
5221 		/*
5222 		 * As of now assume that nothing else accompanies
5223 		 * IPSEC_POLICY_SET.
5224 		 */
5225 		*mpp = NULL;
5226 	}
5227 	if (src_ire != NULL)
5228 		IRE_REFRELE(src_ire);
5229 	if (dst_ire != NULL)
5230 		IRE_REFRELE(dst_ire);
5231 	if (sire != NULL)
5232 		IRE_REFRELE(sire);
5233 	if (md_dst_ire != NULL)
5234 		IRE_REFRELE(md_dst_ire);
5235 	if (lso_dst_ire != NULL)
5236 		IRE_REFRELE(lso_dst_ire);
5237 	return (error);
5238 }
5239 
5240 int
5241 ip_proto_bind_connected_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
5242     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
5243     boolean_t fanout_insert, boolean_t verify_dst)
5244 {
5245 	int error;
5246 	mblk_t	*mp = NULL;
5247 	boolean_t ire_requested;
5248 
5249 	if (ire_mpp)
5250 		mp = *ire_mpp;
5251 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
5252 
5253 	ASSERT(!connp->conn_af_isv6);
5254 	connp->conn_pkt_isv6 = B_FALSE;
5255 	connp->conn_ulp = protocol;
5256 
5257 	/* For raw socket, the local port is not set. */
5258 	if (lport == 0)
5259 		lport = connp->conn_lport;
5260 	error = ip_bind_connected_v4(connp, ire_mpp, protocol,
5261 	    src_addrp, lport, dst_addr, fport, fanout_insert, verify_dst);
5262 	if (error == 0) {
5263 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
5264 		    ire_requested);
5265 	} else if (error < 0) {
5266 		error = -TBADADDR;
5267 	}
5268 	return (error);
5269 }
5270 
5271 /*
5272  * Get the ire in *mpp. Returns false if it fails (due to lack of space).
5273  * Prefers dst_ire over src_ire.
5274  */
5275 static boolean_t
5276 ip_bind_get_ire_v4(mblk_t **mpp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5277 {
5278 	mblk_t	*mp = *mpp;
5279 	ire_t	*ret_ire;
5280 
5281 	ASSERT(mp != NULL);
5282 
5283 	if (ire != NULL) {
5284 		/*
5285 		 * mp initialized above to IRE_DB_REQ_TYPE
5286 		 * appended mblk. Its <upper protocol>'s
5287 		 * job to make sure there is room.
5288 		 */
5289 		if ((mp->b_datap->db_lim - mp->b_rptr) < sizeof (ire_t))
5290 			return (B_FALSE);
5291 
5292 		mp->b_datap->db_type = IRE_DB_TYPE;
5293 		mp->b_wptr = mp->b_rptr + sizeof (ire_t);
5294 		bcopy(ire, mp->b_rptr, sizeof (ire_t));
5295 		ret_ire = (ire_t *)mp->b_rptr;
5296 		/*
5297 		 * Pass the latest setting of the ip_path_mtu_discovery and
5298 		 * copy the ulp info if any.
5299 		 */
5300 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5301 		    IPH_DF : 0;
5302 		if (ulp_info != NULL) {
5303 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5304 			    sizeof (iulp_t));
5305 		}
5306 		ret_ire->ire_mp = mp;
5307 	} else {
5308 		/*
5309 		 * No IRE was found. Remove IRE mblk.
5310 		 */
5311 		*mpp = mp->b_cont;
5312 		freeb(mp);
5313 	}
5314 	return (B_TRUE);
5315 }
5316 
5317 /*
5318  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5319  * the final piece where we don't.  Return a pointer to the first mblk in the
5320  * result, and update the pointer to the next mblk to chew on.  If anything
5321  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5322  * NULL pointer.
5323  */
5324 mblk_t *
5325 ip_carve_mp(mblk_t **mpp, ssize_t len)
5326 {
5327 	mblk_t	*mp0;
5328 	mblk_t	*mp1;
5329 	mblk_t	*mp2;
5330 
5331 	if (!len || !mpp || !(mp0 = *mpp))
5332 		return (NULL);
5333 	/* If we aren't going to consume the first mblk, we need a dup. */
5334 	if (mp0->b_wptr - mp0->b_rptr > len) {
5335 		mp1 = dupb(mp0);
5336 		if (mp1) {
5337 			/* Partition the data between the two mblks. */
5338 			mp1->b_wptr = mp1->b_rptr + len;
5339 			mp0->b_rptr = mp1->b_wptr;
5340 			/*
5341 			 * after adjustments if mblk not consumed is now
5342 			 * unaligned, try to align it. If this fails free
5343 			 * all messages and let upper layer recover.
5344 			 */
5345 			if (!OK_32PTR(mp0->b_rptr)) {
5346 				if (!pullupmsg(mp0, -1)) {
5347 					freemsg(mp0);
5348 					freemsg(mp1);
5349 					*mpp = NULL;
5350 					return (NULL);
5351 				}
5352 			}
5353 		}
5354 		return (mp1);
5355 	}
5356 	/* Eat through as many mblks as we need to get len bytes. */
5357 	len -= mp0->b_wptr - mp0->b_rptr;
5358 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5359 		if (mp2->b_wptr - mp2->b_rptr > len) {
5360 			/*
5361 			 * We won't consume the entire last mblk.  Like
5362 			 * above, dup and partition it.
5363 			 */
5364 			mp1->b_cont = dupb(mp2);
5365 			mp1 = mp1->b_cont;
5366 			if (!mp1) {
5367 				/*
5368 				 * Trouble.  Rather than go to a lot of
5369 				 * trouble to clean up, we free the messages.
5370 				 * This won't be any worse than losing it on
5371 				 * the wire.
5372 				 */
5373 				freemsg(mp0);
5374 				freemsg(mp2);
5375 				*mpp = NULL;
5376 				return (NULL);
5377 			}
5378 			mp1->b_wptr = mp1->b_rptr + len;
5379 			mp2->b_rptr = mp1->b_wptr;
5380 			/*
5381 			 * after adjustments if mblk not consumed is now
5382 			 * unaligned, try to align it. If this fails free
5383 			 * all messages and let upper layer recover.
5384 			 */
5385 			if (!OK_32PTR(mp2->b_rptr)) {
5386 				if (!pullupmsg(mp2, -1)) {
5387 					freemsg(mp0);
5388 					freemsg(mp2);
5389 					*mpp = NULL;
5390 					return (NULL);
5391 				}
5392 			}
5393 			*mpp = mp2;
5394 			return (mp0);
5395 		}
5396 		/* Decrement len by the amount we just got. */
5397 		len -= mp2->b_wptr - mp2->b_rptr;
5398 	}
5399 	/*
5400 	 * len should be reduced to zero now.  If not our caller has
5401 	 * screwed up.
5402 	 */
5403 	if (len) {
5404 		/* Shouldn't happen! */
5405 		freemsg(mp0);
5406 		*mpp = NULL;
5407 		return (NULL);
5408 	}
5409 	/*
5410 	 * We consumed up to exactly the end of an mblk.  Detach the part
5411 	 * we are returning from the rest of the chain.
5412 	 */
5413 	mp1->b_cont = NULL;
5414 	*mpp = mp2;
5415 	return (mp0);
5416 }
5417 
5418 /* The ill stream is being unplumbed. Called from ip_close */
5419 int
5420 ip_modclose(ill_t *ill)
5421 {
5422 	boolean_t success;
5423 	ipsq_t	*ipsq;
5424 	ipif_t	*ipif;
5425 	queue_t	*q = ill->ill_rq;
5426 	ip_stack_t	*ipst = ill->ill_ipst;
5427 
5428 	/*
5429 	 * The punlink prior to this may have initiated a capability
5430 	 * negotiation. But ipsq_enter will block until that finishes or
5431 	 * times out.
5432 	 */
5433 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
5434 
5435 	/*
5436 	 * Open/close/push/pop is guaranteed to be single threaded
5437 	 * per stream by STREAMS. FS guarantees that all references
5438 	 * from top are gone before close is called. So there can't
5439 	 * be another close thread that has set CONDEMNED on this ill.
5440 	 * and cause ipsq_enter to return failure.
5441 	 */
5442 	ASSERT(success);
5443 	ipsq = ill->ill_phyint->phyint_ipsq;
5444 
5445 	/*
5446 	 * Mark it condemned. No new reference will be made to this ill.
5447 	 * Lookup functions will return an error. Threads that try to
5448 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5449 	 * that the refcnt will drop down to zero.
5450 	 */
5451 	mutex_enter(&ill->ill_lock);
5452 	ill->ill_state_flags |= ILL_CONDEMNED;
5453 	for (ipif = ill->ill_ipif; ipif != NULL;
5454 	    ipif = ipif->ipif_next) {
5455 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5456 	}
5457 	/*
5458 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5459 	 * returns  error if ILL_CONDEMNED is set
5460 	 */
5461 	cv_broadcast(&ill->ill_cv);
5462 	mutex_exit(&ill->ill_lock);
5463 
5464 	/*
5465 	 * Send all the deferred DLPI messages downstream which came in
5466 	 * during the small window right before ipsq_enter(). We do this
5467 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5468 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5469 	 */
5470 	ill_dlpi_send_deferred(ill);
5471 
5472 	/*
5473 	 * Shut down fragmentation reassembly.
5474 	 * ill_frag_timer won't start a timer again.
5475 	 * Now cancel any existing timer
5476 	 */
5477 	(void) untimeout(ill->ill_frag_timer_id);
5478 	(void) ill_frag_timeout(ill, 0);
5479 
5480 	/*
5481 	 * If MOVE was in progress, clear the
5482 	 * move_in_progress fields also.
5483 	 */
5484 	if (ill->ill_move_in_progress) {
5485 		ILL_CLEAR_MOVE(ill);
5486 	}
5487 
5488 	/*
5489 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5490 	 * this ill. Then wait for the refcnts to drop to zero.
5491 	 * ill_is_freeable checks whether the ill is really quiescent.
5492 	 * Then make sure that threads that are waiting to enter the
5493 	 * ipsq have seen the error returned by ipsq_enter and have
5494 	 * gone away. Then we call ill_delete_tail which does the
5495 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5496 	 */
5497 	ill_delete(ill);
5498 	mutex_enter(&ill->ill_lock);
5499 	while (!ill_is_freeable(ill))
5500 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5501 	while (ill->ill_waiters)
5502 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5503 
5504 	mutex_exit(&ill->ill_lock);
5505 
5506 	/*
5507 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5508 	 * it held until the end of the function since the cleanup
5509 	 * below needs to be able to use the ip_stack_t.
5510 	 */
5511 	netstack_hold(ipst->ips_netstack);
5512 
5513 	/* qprocsoff is called in ill_delete_tail */
5514 	ill_delete_tail(ill);
5515 	ASSERT(ill->ill_ipst == NULL);
5516 
5517 	/*
5518 	 * Walk through all upper (conn) streams and qenable
5519 	 * those that have queued data.
5520 	 * close synchronization needs this to
5521 	 * be done to ensure that all upper layers blocked
5522 	 * due to flow control to the closing device
5523 	 * get unblocked.
5524 	 */
5525 	ip1dbg(("ip_wsrv: walking\n"));
5526 	conn_walk_drain(ipst);
5527 
5528 	mutex_enter(&ipst->ips_ip_mi_lock);
5529 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5530 	mutex_exit(&ipst->ips_ip_mi_lock);
5531 
5532 	/*
5533 	 * credp could be null if the open didn't succeed and ip_modopen
5534 	 * itself calls ip_close.
5535 	 */
5536 	if (ill->ill_credp != NULL)
5537 		crfree(ill->ill_credp);
5538 
5539 	/*
5540 	 * Now we are done with the module close pieces that
5541 	 * need the netstack_t.
5542 	 */
5543 	netstack_rele(ipst->ips_netstack);
5544 
5545 	mi_close_free((IDP)ill);
5546 	q->q_ptr = WR(q)->q_ptr = NULL;
5547 
5548 	ipsq_exit(ipsq);
5549 
5550 	return (0);
5551 }
5552 
5553 /*
5554  * This is called as part of close() for IP, UDP, ICMP, and RTS
5555  * in order to quiesce the conn.
5556  */
5557 void
5558 ip_quiesce_conn(conn_t *connp)
5559 {
5560 	boolean_t	drain_cleanup_reqd = B_FALSE;
5561 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5562 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5563 	ip_stack_t	*ipst;
5564 
5565 	ASSERT(!IPCL_IS_TCP(connp));
5566 	ipst = connp->conn_netstack->netstack_ip;
5567 
5568 	/*
5569 	 * Mark the conn as closing, and this conn must not be
5570 	 * inserted in future into any list. Eg. conn_drain_insert(),
5571 	 * won't insert this conn into the conn_drain_list.
5572 	 * Similarly ill_pending_mp_add() will not add any mp to
5573 	 * the pending mp list, after this conn has started closing.
5574 	 *
5575 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5576 	 * cannot get set henceforth.
5577 	 */
5578 	mutex_enter(&connp->conn_lock);
5579 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5580 	connp->conn_state_flags |= CONN_CLOSING;
5581 	if (connp->conn_idl != NULL)
5582 		drain_cleanup_reqd = B_TRUE;
5583 	if (connp->conn_oper_pending_ill != NULL)
5584 		conn_ioctl_cleanup_reqd = B_TRUE;
5585 	if (connp->conn_dhcpinit_ill != NULL) {
5586 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5587 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5588 		connp->conn_dhcpinit_ill = NULL;
5589 	}
5590 	if (connp->conn_ilg_inuse != 0)
5591 		ilg_cleanup_reqd = B_TRUE;
5592 	mutex_exit(&connp->conn_lock);
5593 
5594 	if (conn_ioctl_cleanup_reqd)
5595 		conn_ioctl_cleanup(connp);
5596 
5597 	if (is_system_labeled() && connp->conn_anon_port) {
5598 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5599 		    connp->conn_mlp_type, connp->conn_ulp,
5600 		    ntohs(connp->conn_lport), B_FALSE);
5601 		connp->conn_anon_port = 0;
5602 	}
5603 	connp->conn_mlp_type = mlptSingle;
5604 
5605 	/*
5606 	 * Remove this conn from any fanout list it is on.
5607 	 * and then wait for any threads currently operating
5608 	 * on this endpoint to finish
5609 	 */
5610 	ipcl_hash_remove(connp);
5611 
5612 	/*
5613 	 * Remove this conn from the drain list, and do
5614 	 * any other cleanup that may be required.
5615 	 * (Only non-tcp streams may have a non-null conn_idl.
5616 	 * TCP streams are never flow controlled, and
5617 	 * conn_idl will be null)
5618 	 */
5619 	if (drain_cleanup_reqd)
5620 		conn_drain_tail(connp, B_TRUE);
5621 
5622 	if (connp == ipst->ips_ip_g_mrouter)
5623 		(void) ip_mrouter_done(NULL, ipst);
5624 
5625 	if (ilg_cleanup_reqd)
5626 		ilg_delete_all(connp);
5627 
5628 	conn_delete_ire(connp, NULL);
5629 
5630 	/*
5631 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5632 	 * callers from write side can't be there now because close
5633 	 * is in progress. The only other caller is ipcl_walk
5634 	 * which checks for the condemned flag.
5635 	 */
5636 	mutex_enter(&connp->conn_lock);
5637 	connp->conn_state_flags |= CONN_CONDEMNED;
5638 	while (connp->conn_ref != 1)
5639 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5640 	connp->conn_state_flags |= CONN_QUIESCED;
5641 	mutex_exit(&connp->conn_lock);
5642 }
5643 
5644 /* ARGSUSED */
5645 int
5646 ip_close(queue_t *q, int flags)
5647 {
5648 	conn_t		*connp;
5649 
5650 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5651 
5652 	/*
5653 	 * Call the appropriate delete routine depending on whether this is
5654 	 * a module or device.
5655 	 */
5656 	if (WR(q)->q_next != NULL) {
5657 		/* This is a module close */
5658 		return (ip_modclose((ill_t *)q->q_ptr));
5659 	}
5660 
5661 	connp = q->q_ptr;
5662 	ip_quiesce_conn(connp);
5663 
5664 	qprocsoff(q);
5665 
5666 	/*
5667 	 * Now we are truly single threaded on this stream, and can
5668 	 * delete the things hanging off the connp, and finally the connp.
5669 	 * We removed this connp from the fanout list, it cannot be
5670 	 * accessed thru the fanouts, and we already waited for the
5671 	 * conn_ref to drop to 0. We are already in close, so
5672 	 * there cannot be any other thread from the top. qprocsoff
5673 	 * has completed, and service has completed or won't run in
5674 	 * future.
5675 	 */
5676 	ASSERT(connp->conn_ref == 1);
5677 
5678 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5679 
5680 	connp->conn_ref--;
5681 	ipcl_conn_destroy(connp);
5682 
5683 	q->q_ptr = WR(q)->q_ptr = NULL;
5684 	return (0);
5685 }
5686 
5687 /*
5688  * Wapper around putnext() so that ip_rts_request can merely use
5689  * conn_recv.
5690  */
5691 /*ARGSUSED2*/
5692 static void
5693 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5694 {
5695 	conn_t *connp = (conn_t *)arg1;
5696 
5697 	putnext(connp->conn_rq, mp);
5698 }
5699 
5700 /*
5701  * Called when the module is about to be unloaded
5702  */
5703 void
5704 ip_ddi_destroy(void)
5705 {
5706 	tnet_fini();
5707 
5708 	icmp_ddi_g_destroy();
5709 	rts_ddi_g_destroy();
5710 	udp_ddi_g_destroy();
5711 	sctp_ddi_g_destroy();
5712 	tcp_ddi_g_destroy();
5713 	ipsec_policy_g_destroy();
5714 	ipcl_g_destroy();
5715 	ip_net_g_destroy();
5716 	ip_ire_g_fini();
5717 	inet_minor_destroy(ip_minor_arena_sa);
5718 #if defined(_LP64)
5719 	inet_minor_destroy(ip_minor_arena_la);
5720 #endif
5721 
5722 #ifdef DEBUG
5723 	list_destroy(&ip_thread_list);
5724 	rw_destroy(&ip_thread_rwlock);
5725 	tsd_destroy(&ip_thread_data);
5726 #endif
5727 
5728 	netstack_unregister(NS_IP);
5729 }
5730 
5731 /*
5732  * First step in cleanup.
5733  */
5734 /* ARGSUSED */
5735 static void
5736 ip_stack_shutdown(netstackid_t stackid, void *arg)
5737 {
5738 	ip_stack_t *ipst = (ip_stack_t *)arg;
5739 
5740 #ifdef NS_DEBUG
5741 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5742 #endif
5743 
5744 	/* Get rid of loopback interfaces and their IREs */
5745 	ip_loopback_cleanup(ipst);
5746 
5747 	/*
5748 	 * The *_hook_shutdown()s start the process of notifying any
5749 	 * consumers that things are going away.... nothing is destroyed.
5750 	 */
5751 	ipv4_hook_shutdown(ipst);
5752 	ipv6_hook_shutdown(ipst);
5753 
5754 	mutex_enter(&ipst->ips_capab_taskq_lock);
5755 	ipst->ips_capab_taskq_quit = B_TRUE;
5756 	cv_signal(&ipst->ips_capab_taskq_cv);
5757 	mutex_exit(&ipst->ips_capab_taskq_lock);
5758 }
5759 
5760 /*
5761  * Free the IP stack instance.
5762  */
5763 static void
5764 ip_stack_fini(netstackid_t stackid, void *arg)
5765 {
5766 	ip_stack_t *ipst = (ip_stack_t *)arg;
5767 	int ret;
5768 
5769 	/*
5770 	 * At this point, all of the notifications that the events and
5771 	 * protocols are going away have been run, meaning that we can
5772 	 * now set about starting to clean things up.
5773 	 */
5774 	ipv4_hook_destroy(ipst);
5775 	ipv6_hook_destroy(ipst);
5776 	ip_net_destroy(ipst);
5777 
5778 	mutex_destroy(&ipst->ips_capab_taskq_lock);
5779 	cv_destroy(&ipst->ips_capab_taskq_cv);
5780 	list_destroy(&ipst->ips_capab_taskq_list);
5781 
5782 #ifdef NS_DEBUG
5783 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5784 #endif
5785 	rw_destroy(&ipst->ips_srcid_lock);
5786 
5787 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5788 	ipst->ips_ip_mibkp = NULL;
5789 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5790 	ipst->ips_icmp_mibkp = NULL;
5791 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5792 	ipst->ips_ip_kstat = NULL;
5793 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5794 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5795 	ipst->ips_ip6_kstat = NULL;
5796 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5797 
5798 	nd_free(&ipst->ips_ip_g_nd);
5799 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5800 	ipst->ips_param_arr = NULL;
5801 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5802 	ipst->ips_ndp_arr = NULL;
5803 
5804 	ip_mrouter_stack_destroy(ipst);
5805 
5806 	mutex_destroy(&ipst->ips_ip_mi_lock);
5807 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5808 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5809 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5810 
5811 	ret = untimeout(ipst->ips_igmp_timeout_id);
5812 	if (ret == -1) {
5813 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5814 	} else {
5815 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5816 		ipst->ips_igmp_timeout_id = 0;
5817 	}
5818 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5819 	if (ret == -1) {
5820 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5821 	} else {
5822 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5823 		ipst->ips_igmp_slowtimeout_id = 0;
5824 	}
5825 	ret = untimeout(ipst->ips_mld_timeout_id);
5826 	if (ret == -1) {
5827 		ASSERT(ipst->ips_mld_timeout_id == 0);
5828 	} else {
5829 		ASSERT(ipst->ips_mld_timeout_id != 0);
5830 		ipst->ips_mld_timeout_id = 0;
5831 	}
5832 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5833 	if (ret == -1) {
5834 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5835 	} else {
5836 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5837 		ipst->ips_mld_slowtimeout_id = 0;
5838 	}
5839 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5840 	if (ret == -1) {
5841 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5842 	} else {
5843 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5844 		ipst->ips_ip_ire_expire_id = 0;
5845 	}
5846 
5847 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5848 	mutex_destroy(&ipst->ips_mld_timer_lock);
5849 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5850 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5851 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5852 	rw_destroy(&ipst->ips_ill_g_lock);
5853 
5854 	ipobs_fini(ipst);
5855 	ip_ire_fini(ipst);
5856 	ip6_asp_free(ipst);
5857 	conn_drain_fini(ipst);
5858 	ipcl_destroy(ipst);
5859 
5860 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5861 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5862 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5863 	ipst->ips_ndp4 = NULL;
5864 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5865 	ipst->ips_ndp6 = NULL;
5866 
5867 	if (ipst->ips_loopback_ksp != NULL) {
5868 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5869 		ipst->ips_loopback_ksp = NULL;
5870 	}
5871 
5872 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5873 	ipst->ips_phyint_g_list = NULL;
5874 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5875 	ipst->ips_ill_g_heads = NULL;
5876 
5877 	ldi_ident_release(ipst->ips_ldi_ident);
5878 	kmem_free(ipst, sizeof (*ipst));
5879 }
5880 
5881 /*
5882  * This function is called from the TSD destructor, and is used to debug
5883  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5884  * details.
5885  */
5886 static void
5887 ip_thread_exit(void *phash)
5888 {
5889 	th_hash_t *thh = phash;
5890 
5891 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5892 	list_remove(&ip_thread_list, thh);
5893 	rw_exit(&ip_thread_rwlock);
5894 	mod_hash_destroy_hash(thh->thh_hash);
5895 	kmem_free(thh, sizeof (*thh));
5896 }
5897 
5898 /*
5899  * Called when the IP kernel module is loaded into the kernel
5900  */
5901 void
5902 ip_ddi_init(void)
5903 {
5904 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
5905 
5906 	/*
5907 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5908 	 * initial devices: ip, ip6, tcp, tcp6.
5909 	 */
5910 	/*
5911 	 * If this is a 64-bit kernel, then create two separate arenas -
5912 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5913 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5914 	 */
5915 	ip_minor_arena_la = NULL;
5916 	ip_minor_arena_sa = NULL;
5917 #if defined(_LP64)
5918 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5919 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5920 		cmn_err(CE_PANIC,
5921 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5922 	}
5923 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5924 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5925 		cmn_err(CE_PANIC,
5926 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5927 	}
5928 #else
5929 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5930 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5931 		cmn_err(CE_PANIC,
5932 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5933 	}
5934 #endif
5935 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5936 
5937 	ipcl_g_init();
5938 	ip_ire_g_init();
5939 	ip_net_g_init();
5940 
5941 #ifdef DEBUG
5942 	tsd_create(&ip_thread_data, ip_thread_exit);
5943 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5944 	list_create(&ip_thread_list, sizeof (th_hash_t),
5945 	    offsetof(th_hash_t, thh_link));
5946 #endif
5947 
5948 	/*
5949 	 * We want to be informed each time a stack is created or
5950 	 * destroyed in the kernel, so we can maintain the
5951 	 * set of udp_stack_t's.
5952 	 */
5953 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5954 	    ip_stack_fini);
5955 
5956 	ipsec_policy_g_init();
5957 	tcp_ddi_g_init();
5958 	sctp_ddi_g_init();
5959 
5960 	tnet_init();
5961 
5962 	udp_ddi_g_init();
5963 	rts_ddi_g_init();
5964 	icmp_ddi_g_init();
5965 }
5966 
5967 /*
5968  * Initialize the IP stack instance.
5969  */
5970 static void *
5971 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5972 {
5973 	ip_stack_t	*ipst;
5974 	ipparam_t	*pa;
5975 	ipndp_t		*na;
5976 	major_t		major;
5977 
5978 #ifdef NS_DEBUG
5979 	printf("ip_stack_init(stack %d)\n", stackid);
5980 #endif
5981 
5982 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5983 	ipst->ips_netstack = ns;
5984 
5985 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5986 	    KM_SLEEP);
5987 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5988 	    KM_SLEEP);
5989 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5990 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5991 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5992 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5993 
5994 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5995 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5996 	ipst->ips_igmp_deferred_next = INFINITY;
5997 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5998 	ipst->ips_mld_deferred_next = INFINITY;
5999 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6000 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6001 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
6002 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
6003 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
6004 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
6005 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
6006 
6007 	ipcl_init(ipst);
6008 	ip_ire_init(ipst);
6009 	ip6_asp_init(ipst);
6010 	ipif_init(ipst);
6011 	conn_drain_init(ipst);
6012 	ip_mrouter_stack_init(ipst);
6013 
6014 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
6015 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
6016 
6017 	ipst->ips_ip_multirt_log_interval = 1000;
6018 
6019 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
6020 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
6021 	ipst->ips_ill_index = 1;
6022 
6023 	ipst->ips_saved_ip_g_forward = -1;
6024 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6025 
6026 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6027 	ipst->ips_param_arr = pa;
6028 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6029 
6030 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6031 	ipst->ips_ndp_arr = na;
6032 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6033 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6034 	    (caddr_t)&ipst->ips_ip_g_forward;
6035 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6036 	    (caddr_t)&ipst->ips_ipv6_forward;
6037 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6038 	    "ip_cgtp_filter") == 0);
6039 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6040 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
6041 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
6042 	    "ipmp_hook_emulation") == 0);
6043 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
6044 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
6045 
6046 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6047 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6048 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6049 
6050 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6051 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6052 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6053 	ipst->ips_ip6_kstat =
6054 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6055 
6056 	ipst->ips_ipmp_enable_failback = B_TRUE;
6057 
6058 	ipst->ips_ip_src_id = 1;
6059 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6060 
6061 	ipobs_init(ipst);
6062 	ip_net_init(ipst, ns);
6063 	ipv4_hook_init(ipst);
6064 	ipv6_hook_init(ipst);
6065 
6066 	/*
6067 	 * Create the taskq dispatcher thread and initialize related stuff.
6068 	 */
6069 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
6070 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
6071 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
6072 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
6073 	list_create(&ipst->ips_capab_taskq_list, sizeof (mblk_t),
6074 	    offsetof(mblk_t, b_next));
6075 
6076 	major = mod_name_to_major(INET_NAME);
6077 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
6078 	return (ipst);
6079 }
6080 
6081 /*
6082  * Allocate and initialize a DLPI template of the specified length.  (May be
6083  * called as writer.)
6084  */
6085 mblk_t *
6086 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6087 {
6088 	mblk_t	*mp;
6089 
6090 	mp = allocb(len, BPRI_MED);
6091 	if (!mp)
6092 		return (NULL);
6093 
6094 	/*
6095 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6096 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6097 	 * that other DLPI are M_PROTO.
6098 	 */
6099 	if (prim == DL_INFO_REQ) {
6100 		mp->b_datap->db_type = M_PCPROTO;
6101 	} else {
6102 		mp->b_datap->db_type = M_PROTO;
6103 	}
6104 
6105 	mp->b_wptr = mp->b_rptr + len;
6106 	bzero(mp->b_rptr, len);
6107 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6108 	return (mp);
6109 }
6110 
6111 /*
6112  * Debug formatting routine.  Returns a character string representation of the
6113  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6114  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6115  *
6116  * Once the ndd table-printing interfaces are removed, this can be changed to
6117  * standard dotted-decimal form.
6118  */
6119 char *
6120 ip_dot_addr(ipaddr_t addr, char *buf)
6121 {
6122 	uint8_t *ap = (uint8_t *)&addr;
6123 
6124 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6125 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6126 	return (buf);
6127 }
6128 
6129 /*
6130  * Write the given MAC address as a printable string in the usual colon-
6131  * separated format.
6132  */
6133 const char *
6134 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6135 {
6136 	char *bp;
6137 
6138 	if (alen == 0 || buflen < 4)
6139 		return ("?");
6140 	bp = buf;
6141 	for (;;) {
6142 		/*
6143 		 * If there are more MAC address bytes available, but we won't
6144 		 * have any room to print them, then add "..." to the string
6145 		 * instead.  See below for the 'magic number' explanation.
6146 		 */
6147 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6148 			(void) strcpy(bp, "...");
6149 			break;
6150 		}
6151 		(void) sprintf(bp, "%02x", *addr++);
6152 		bp += 2;
6153 		if (--alen == 0)
6154 			break;
6155 		*bp++ = ':';
6156 		buflen -= 3;
6157 		/*
6158 		 * At this point, based on the first 'if' statement above,
6159 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6160 		 * buflen >= 4.  The first case leaves room for the final "xx"
6161 		 * number and trailing NUL byte.  The second leaves room for at
6162 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6163 		 * that statement.
6164 		 */
6165 	}
6166 	return (buf);
6167 }
6168 
6169 /*
6170  * Send an ICMP error after patching up the packet appropriately.  Returns
6171  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6172  */
6173 static boolean_t
6174 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6175     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6176     zoneid_t zoneid, ip_stack_t *ipst)
6177 {
6178 	ipha_t *ipha;
6179 	mblk_t *first_mp;
6180 	boolean_t secure;
6181 	unsigned char db_type;
6182 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6183 
6184 	first_mp = mp;
6185 	if (mctl_present) {
6186 		mp = mp->b_cont;
6187 		secure = ipsec_in_is_secure(first_mp);
6188 		ASSERT(mp != NULL);
6189 	} else {
6190 		/*
6191 		 * If this is an ICMP error being reported - which goes
6192 		 * up as M_CTLs, we need to convert them to M_DATA till
6193 		 * we finish checking with global policy because
6194 		 * ipsec_check_global_policy() assumes M_DATA as clear
6195 		 * and M_CTL as secure.
6196 		 */
6197 		db_type = DB_TYPE(mp);
6198 		DB_TYPE(mp) = M_DATA;
6199 		secure = B_FALSE;
6200 	}
6201 	/*
6202 	 * We are generating an icmp error for some inbound packet.
6203 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6204 	 * Before we generate an error, check with global policy
6205 	 * to see whether this is allowed to enter the system. As
6206 	 * there is no "conn", we are checking with global policy.
6207 	 */
6208 	ipha = (ipha_t *)mp->b_rptr;
6209 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6210 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6211 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6212 		if (first_mp == NULL)
6213 			return (B_FALSE);
6214 	}
6215 
6216 	if (!mctl_present)
6217 		DB_TYPE(mp) = db_type;
6218 
6219 	if (flags & IP_FF_SEND_ICMP) {
6220 		if (flags & IP_FF_HDR_COMPLETE) {
6221 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6222 				freemsg(first_mp);
6223 				return (B_TRUE);
6224 			}
6225 		}
6226 		if (flags & IP_FF_CKSUM) {
6227 			/*
6228 			 * Have to correct checksum since
6229 			 * the packet might have been
6230 			 * fragmented and the reassembly code in ip_rput
6231 			 * does not restore the IP checksum.
6232 			 */
6233 			ipha->ipha_hdr_checksum = 0;
6234 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6235 		}
6236 		switch (icmp_type) {
6237 		case ICMP_DEST_UNREACHABLE:
6238 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6239 			    ipst);
6240 			break;
6241 		default:
6242 			freemsg(first_mp);
6243 			break;
6244 		}
6245 	} else {
6246 		freemsg(first_mp);
6247 		return (B_FALSE);
6248 	}
6249 
6250 	return (B_TRUE);
6251 }
6252 
6253 /*
6254  * Used to send an ICMP error message when a packet is received for
6255  * a protocol that is not supported. The mblk passed as argument
6256  * is consumed by this function.
6257  */
6258 void
6259 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6260     ip_stack_t *ipst)
6261 {
6262 	mblk_t *mp;
6263 	ipha_t *ipha;
6264 	ill_t *ill;
6265 	ipsec_in_t *ii;
6266 
6267 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6268 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6269 
6270 	mp = ipsec_mp->b_cont;
6271 	ipsec_mp->b_cont = NULL;
6272 	ipha = (ipha_t *)mp->b_rptr;
6273 	/* Get ill from index in ipsec_in_t. */
6274 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6275 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6276 	    ipst);
6277 	if (ill != NULL) {
6278 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6279 			if (ip_fanout_send_icmp(q, mp, flags,
6280 			    ICMP_DEST_UNREACHABLE,
6281 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6282 				BUMP_MIB(ill->ill_ip_mib,
6283 				    ipIfStatsInUnknownProtos);
6284 			}
6285 		} else {
6286 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6287 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6288 			    0, B_FALSE, zoneid, ipst)) {
6289 				BUMP_MIB(ill->ill_ip_mib,
6290 				    ipIfStatsInUnknownProtos);
6291 			}
6292 		}
6293 		ill_refrele(ill);
6294 	} else { /* re-link for the freemsg() below. */
6295 		ipsec_mp->b_cont = mp;
6296 	}
6297 
6298 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6299 	freemsg(ipsec_mp);
6300 }
6301 
6302 /*
6303  * See if the inbound datagram has had IPsec processing applied to it.
6304  */
6305 boolean_t
6306 ipsec_in_is_secure(mblk_t *ipsec_mp)
6307 {
6308 	ipsec_in_t *ii;
6309 
6310 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6311 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6312 
6313 	if (ii->ipsec_in_loopback) {
6314 		return (ii->ipsec_in_secure);
6315 	} else {
6316 		return (ii->ipsec_in_ah_sa != NULL ||
6317 		    ii->ipsec_in_esp_sa != NULL ||
6318 		    ii->ipsec_in_decaps);
6319 	}
6320 }
6321 
6322 /*
6323  * Handle protocols with which IP is less intimate.  There
6324  * can be more than one stream bound to a particular
6325  * protocol.  When this is the case, normally each one gets a copy
6326  * of any incoming packets.
6327  *
6328  * IPsec NOTE :
6329  *
6330  * Don't allow a secure packet going up a non-secure connection.
6331  * We don't allow this because
6332  *
6333  * 1) Reply might go out in clear which will be dropped at
6334  *    the sending side.
6335  * 2) If the reply goes out in clear it will give the
6336  *    adversary enough information for getting the key in
6337  *    most of the cases.
6338  *
6339  * Moreover getting a secure packet when we expect clear
6340  * implies that SA's were added without checking for
6341  * policy on both ends. This should not happen once ISAKMP
6342  * is used to negotiate SAs as SAs will be added only after
6343  * verifying the policy.
6344  *
6345  * NOTE : If the packet was tunneled and not multicast we only send
6346  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6347  * back to delivering packets to AF_INET6 raw sockets.
6348  *
6349  * IPQoS Notes:
6350  * Once we have determined the client, invoke IPPF processing.
6351  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6352  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6353  * ip_policy will be false.
6354  *
6355  * Zones notes:
6356  * Currently only applications in the global zone can create raw sockets for
6357  * protocols other than ICMP. So unlike the broadcast / multicast case of
6358  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6359  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6360  */
6361 static void
6362 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6363     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6364     zoneid_t zoneid)
6365 {
6366 	queue_t	*rq;
6367 	mblk_t	*mp1, *first_mp1;
6368 	uint_t	protocol = ipha->ipha_protocol;
6369 	ipaddr_t dst;
6370 	boolean_t one_only;
6371 	mblk_t *first_mp = mp;
6372 	boolean_t secure;
6373 	uint32_t ill_index;
6374 	conn_t	*connp, *first_connp, *next_connp;
6375 	connf_t	*connfp;
6376 	boolean_t shared_addr;
6377 	mib2_ipIfStatsEntry_t *mibptr;
6378 	ip_stack_t *ipst = recv_ill->ill_ipst;
6379 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6380 
6381 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6382 	if (mctl_present) {
6383 		mp = first_mp->b_cont;
6384 		secure = ipsec_in_is_secure(first_mp);
6385 		ASSERT(mp != NULL);
6386 	} else {
6387 		secure = B_FALSE;
6388 	}
6389 	dst = ipha->ipha_dst;
6390 	/*
6391 	 * If the packet was tunneled and not multicast we only send to it
6392 	 * the first match.
6393 	 */
6394 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6395 	    !CLASSD(dst));
6396 
6397 	shared_addr = (zoneid == ALL_ZONES);
6398 	if (shared_addr) {
6399 		/*
6400 		 * We don't allow multilevel ports for raw IP, so no need to
6401 		 * check for that here.
6402 		 */
6403 		zoneid = tsol_packet_to_zoneid(mp);
6404 	}
6405 
6406 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6407 	mutex_enter(&connfp->connf_lock);
6408 	connp = connfp->connf_head;
6409 	for (connp = connfp->connf_head; connp != NULL;
6410 	    connp = connp->conn_next) {
6411 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6412 		    zoneid) &&
6413 		    (!is_system_labeled() ||
6414 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6415 		    connp))) {
6416 			break;
6417 		}
6418 	}
6419 
6420 	if (connp == NULL) {
6421 		/*
6422 		 * No one bound to these addresses.  Is
6423 		 * there a client that wants all
6424 		 * unclaimed datagrams?
6425 		 */
6426 		mutex_exit(&connfp->connf_lock);
6427 		/*
6428 		 * Check for IPPROTO_ENCAP...
6429 		 */
6430 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6431 			/*
6432 			 * If an IPsec mblk is here on a multicast
6433 			 * tunnel (using ip_mroute stuff), check policy here,
6434 			 * THEN ship off to ip_mroute_decap().
6435 			 *
6436 			 * BTW,  If I match a configured IP-in-IP
6437 			 * tunnel, this path will not be reached, and
6438 			 * ip_mroute_decap will never be called.
6439 			 */
6440 			first_mp = ipsec_check_global_policy(first_mp, connp,
6441 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6442 			if (first_mp != NULL) {
6443 				if (mctl_present)
6444 					freeb(first_mp);
6445 				ip_mroute_decap(q, mp, ill);
6446 			} /* Else we already freed everything! */
6447 		} else {
6448 			/*
6449 			 * Otherwise send an ICMP protocol unreachable.
6450 			 */
6451 			if (ip_fanout_send_icmp(q, first_mp, flags,
6452 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6453 			    mctl_present, zoneid, ipst)) {
6454 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6455 			}
6456 		}
6457 		return;
6458 	}
6459 
6460 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
6461 
6462 	CONN_INC_REF(connp);
6463 	first_connp = connp;
6464 
6465 	/*
6466 	 * Only send message to one tunnel driver by immediately
6467 	 * terminating the loop.
6468 	 */
6469 	connp = one_only ? NULL : connp->conn_next;
6470 
6471 	for (;;) {
6472 		while (connp != NULL) {
6473 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6474 			    flags, zoneid) &&
6475 			    (!is_system_labeled() ||
6476 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6477 			    shared_addr, connp)))
6478 				break;
6479 			connp = connp->conn_next;
6480 		}
6481 
6482 		/*
6483 		 * Copy the packet.
6484 		 */
6485 		if (connp == NULL ||
6486 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6487 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6488 			/*
6489 			 * No more interested clients or memory
6490 			 * allocation failed
6491 			 */
6492 			connp = first_connp;
6493 			break;
6494 		}
6495 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
6496 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6497 		CONN_INC_REF(connp);
6498 		mutex_exit(&connfp->connf_lock);
6499 		rq = connp->conn_rq;
6500 
6501 		/*
6502 		 * Check flow control
6503 		 */
6504 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6505 		    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6506 			if (flags & IP_FF_RAWIP) {
6507 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6508 			} else {
6509 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6510 			}
6511 
6512 			freemsg(first_mp1);
6513 		} else {
6514 			/*
6515 			 * Don't enforce here if we're an actual tunnel -
6516 			 * let "tun" do it instead.
6517 			 */
6518 			if (!IPCL_IS_IPTUN(connp) &&
6519 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6520 			    secure)) {
6521 				first_mp1 = ipsec_check_inbound_policy
6522 				    (first_mp1, connp, ipha, NULL,
6523 				    mctl_present);
6524 			}
6525 			if (first_mp1 != NULL) {
6526 				int in_flags = 0;
6527 				/*
6528 				 * ip_fanout_proto also gets called from
6529 				 * icmp_inbound_error_fanout, in which case
6530 				 * the msg type is M_CTL.  Don't add info
6531 				 * in this case for the time being. In future
6532 				 * when there is a need for knowing the
6533 				 * inbound iface index for ICMP error msgs,
6534 				 * then this can be changed.
6535 				 */
6536 				if (connp->conn_recvif)
6537 					in_flags = IPF_RECVIF;
6538 				/*
6539 				 * The ULP may support IP_RECVPKTINFO for both
6540 				 * IP v4 and v6 so pass the appropriate argument
6541 				 * based on conn IP version.
6542 				 */
6543 				if (connp->conn_ip_recvpktinfo) {
6544 					if (connp->conn_af_isv6) {
6545 						/*
6546 						 * V6 only needs index
6547 						 */
6548 						in_flags |= IPF_RECVIF;
6549 					} else {
6550 						/*
6551 						 * V4 needs index +
6552 						 * matching address.
6553 						 */
6554 						in_flags |= IPF_RECVADDR;
6555 					}
6556 				}
6557 				if ((in_flags != 0) &&
6558 				    (mp->b_datap->db_type != M_CTL)) {
6559 					/*
6560 					 * the actual data will be
6561 					 * contained in b_cont upon
6562 					 * successful return of the
6563 					 * following call else
6564 					 * original mblk is returned
6565 					 */
6566 					ASSERT(recv_ill != NULL);
6567 					mp1 = ip_add_info(mp1, recv_ill,
6568 					    in_flags, IPCL_ZONEID(connp), ipst);
6569 				}
6570 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6571 				if (mctl_present)
6572 					freeb(first_mp1);
6573 				(connp->conn_recv)(connp, mp1, NULL);
6574 			}
6575 		}
6576 		mutex_enter(&connfp->connf_lock);
6577 		/* Follow the next pointer before releasing the conn. */
6578 		next_connp = connp->conn_next;
6579 		CONN_DEC_REF(connp);
6580 		connp = next_connp;
6581 	}
6582 
6583 	/* Last one.  Send it upstream. */
6584 	mutex_exit(&connfp->connf_lock);
6585 
6586 	/*
6587 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6588 	 * will be set to false.
6589 	 */
6590 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6591 		ill_index = ill->ill_phyint->phyint_ifindex;
6592 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6593 		if (mp == NULL) {
6594 			CONN_DEC_REF(connp);
6595 			if (mctl_present) {
6596 				freeb(first_mp);
6597 			}
6598 			return;
6599 		}
6600 	}
6601 
6602 	rq = connp->conn_rq;
6603 	/*
6604 	 * Check flow control
6605 	 */
6606 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6607 	    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6608 		if (flags & IP_FF_RAWIP) {
6609 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6610 		} else {
6611 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6612 		}
6613 
6614 		freemsg(first_mp);
6615 	} else {
6616 		if (IPCL_IS_IPTUN(connp)) {
6617 			/*
6618 			 * Tunneled packet.  We enforce policy in the tunnel
6619 			 * module itself.
6620 			 *
6621 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6622 			 * a policy check.
6623 			 * FIXME to use conn_recv for tun later.
6624 			 */
6625 			putnext(rq, first_mp);
6626 			CONN_DEC_REF(connp);
6627 			return;
6628 		}
6629 
6630 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6631 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6632 			    ipha, NULL, mctl_present);
6633 		}
6634 
6635 		if (first_mp != NULL) {
6636 			int in_flags = 0;
6637 
6638 			/*
6639 			 * ip_fanout_proto also gets called
6640 			 * from icmp_inbound_error_fanout, in
6641 			 * which case the msg type is M_CTL.
6642 			 * Don't add info in this case for time
6643 			 * being. In future when there is a
6644 			 * need for knowing the inbound iface
6645 			 * index for ICMP error msgs, then this
6646 			 * can be changed
6647 			 */
6648 			if (connp->conn_recvif)
6649 				in_flags = IPF_RECVIF;
6650 			if (connp->conn_ip_recvpktinfo) {
6651 				if (connp->conn_af_isv6) {
6652 					/*
6653 					 * V6 only needs index
6654 					 */
6655 					in_flags |= IPF_RECVIF;
6656 				} else {
6657 					/*
6658 					 * V4 needs index +
6659 					 * matching address.
6660 					 */
6661 					in_flags |= IPF_RECVADDR;
6662 				}
6663 			}
6664 			if ((in_flags != 0) &&
6665 			    (mp->b_datap->db_type != M_CTL)) {
6666 
6667 				/*
6668 				 * the actual data will be contained in
6669 				 * b_cont upon successful return
6670 				 * of the following call else original
6671 				 * mblk is returned
6672 				 */
6673 				ASSERT(recv_ill != NULL);
6674 				mp = ip_add_info(mp, recv_ill,
6675 				    in_flags, IPCL_ZONEID(connp), ipst);
6676 			}
6677 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6678 			(connp->conn_recv)(connp, mp, NULL);
6679 			if (mctl_present)
6680 				freeb(first_mp);
6681 		}
6682 	}
6683 	CONN_DEC_REF(connp);
6684 }
6685 
6686 /*
6687  * Fanout for TCP packets
6688  * The caller puts <fport, lport> in the ports parameter.
6689  *
6690  * IPQoS Notes
6691  * Before sending it to the client, invoke IPPF processing.
6692  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6693  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6694  * ip_policy is false.
6695  */
6696 static void
6697 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6698     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6699 {
6700 	mblk_t  *first_mp;
6701 	boolean_t secure;
6702 	uint32_t ill_index;
6703 	int	ip_hdr_len;
6704 	tcph_t	*tcph;
6705 	boolean_t syn_present = B_FALSE;
6706 	conn_t	*connp;
6707 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6708 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6709 
6710 	ASSERT(recv_ill != NULL);
6711 
6712 	first_mp = mp;
6713 	if (mctl_present) {
6714 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6715 		mp = first_mp->b_cont;
6716 		secure = ipsec_in_is_secure(first_mp);
6717 		ASSERT(mp != NULL);
6718 	} else {
6719 		secure = B_FALSE;
6720 	}
6721 
6722 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6723 
6724 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6725 	    zoneid, ipst)) == NULL) {
6726 		/*
6727 		 * No connected connection or listener. Send a
6728 		 * TH_RST via tcp_xmit_listeners_reset.
6729 		 */
6730 
6731 		/* Initiate IPPf processing, if needed. */
6732 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6733 			uint32_t ill_index;
6734 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6735 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6736 			if (first_mp == NULL)
6737 				return;
6738 		}
6739 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6740 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6741 		    zoneid));
6742 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6743 		    ipst->ips_netstack->netstack_tcp, NULL);
6744 		return;
6745 	}
6746 
6747 	/*
6748 	 * Allocate the SYN for the TCP connection here itself
6749 	 */
6750 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6751 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6752 		if (IPCL_IS_TCP(connp)) {
6753 			squeue_t *sqp;
6754 
6755 			/*
6756 			 * For fused tcp loopback, assign the eager's
6757 			 * squeue to be that of the active connect's.
6758 			 * Note that we don't check for IP_FF_LOOPBACK
6759 			 * here since this routine gets called only
6760 			 * for loopback (unlike the IPv6 counterpart).
6761 			 */
6762 			ASSERT(Q_TO_CONN(q) != NULL);
6763 			if (do_tcp_fusion &&
6764 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6765 			    !secure &&
6766 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6767 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6768 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6769 				sqp = Q_TO_CONN(q)->conn_sqp;
6770 			} else {
6771 				sqp = IP_SQUEUE_GET(lbolt);
6772 			}
6773 
6774 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6775 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6776 			syn_present = B_TRUE;
6777 		}
6778 	}
6779 
6780 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6781 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6782 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6783 		if ((flags & TH_RST) || (flags & TH_URG)) {
6784 			CONN_DEC_REF(connp);
6785 			freemsg(first_mp);
6786 			return;
6787 		}
6788 		if (flags & TH_ACK) {
6789 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6790 			    ipst->ips_netstack->netstack_tcp, connp);
6791 			CONN_DEC_REF(connp);
6792 			return;
6793 		}
6794 
6795 		CONN_DEC_REF(connp);
6796 		freemsg(first_mp);
6797 		return;
6798 	}
6799 
6800 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6801 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6802 		    NULL, mctl_present);
6803 		if (first_mp == NULL) {
6804 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6805 			CONN_DEC_REF(connp);
6806 			return;
6807 		}
6808 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6809 			ASSERT(syn_present);
6810 			if (mctl_present) {
6811 				ASSERT(first_mp != mp);
6812 				first_mp->b_datap->db_struioflag |=
6813 				    STRUIO_POLICY;
6814 			} else {
6815 				ASSERT(first_mp == mp);
6816 				mp->b_datap->db_struioflag &=
6817 				    ~STRUIO_EAGER;
6818 				mp->b_datap->db_struioflag |=
6819 				    STRUIO_POLICY;
6820 			}
6821 		} else {
6822 			/*
6823 			 * Discard first_mp early since we're dealing with a
6824 			 * fully-connected conn_t and tcp doesn't do policy in
6825 			 * this case.
6826 			 */
6827 			if (mctl_present) {
6828 				freeb(first_mp);
6829 				mctl_present = B_FALSE;
6830 			}
6831 			first_mp = mp;
6832 		}
6833 	}
6834 
6835 	/*
6836 	 * Initiate policy processing here if needed. If we get here from
6837 	 * icmp_inbound_error_fanout, ip_policy is false.
6838 	 */
6839 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6840 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6841 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6842 		if (mp == NULL) {
6843 			CONN_DEC_REF(connp);
6844 			if (mctl_present)
6845 				freeb(first_mp);
6846 			return;
6847 		} else if (mctl_present) {
6848 			ASSERT(first_mp != mp);
6849 			first_mp->b_cont = mp;
6850 		} else {
6851 			first_mp = mp;
6852 		}
6853 	}
6854 
6855 
6856 
6857 	/* Handle socket options. */
6858 	if (!syn_present &&
6859 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6860 		/* Add header */
6861 		ASSERT(recv_ill != NULL);
6862 		/*
6863 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6864 		 * IPF_RECVIF.
6865 		 */
6866 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6867 		    ipst);
6868 		if (mp == NULL) {
6869 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6870 			CONN_DEC_REF(connp);
6871 			if (mctl_present)
6872 				freeb(first_mp);
6873 			return;
6874 		} else if (mctl_present) {
6875 			/*
6876 			 * ip_add_info might return a new mp.
6877 			 */
6878 			ASSERT(first_mp != mp);
6879 			first_mp->b_cont = mp;
6880 		} else {
6881 			first_mp = mp;
6882 		}
6883 	}
6884 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6885 	if (IPCL_IS_TCP(connp)) {
6886 		/* do not drain, certain use cases can blow the stack */
6887 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, connp->conn_recv,
6888 		    connp, ip_squeue_flag, SQTAG_IP_FANOUT_TCP);
6889 	} else {
6890 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6891 		(connp->conn_recv)(connp, first_mp, NULL);
6892 		CONN_DEC_REF(connp);
6893 	}
6894 }
6895 
6896 /*
6897  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6898  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6899  * is not consumed.
6900  *
6901  * One of four things can happen, all of which affect the passed-in mblk:
6902  *
6903  * 1.) ICMP messages that go through here just get returned TRUE.
6904  *
6905  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6906  *
6907  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6908  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6909  *
6910  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6911  */
6912 static boolean_t
6913 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6914     ipsec_stack_t *ipss)
6915 {
6916 	int shift, plen, iph_len;
6917 	ipha_t *ipha;
6918 	udpha_t *udpha;
6919 	uint32_t *spi;
6920 	uint32_t esp_ports;
6921 	uint8_t *orptr;
6922 	boolean_t free_ire;
6923 
6924 	if (DB_TYPE(mp) == M_CTL) {
6925 		/*
6926 		 * ICMP message with UDP inside.  Don't bother stripping, just
6927 		 * send it up.
6928 		 *
6929 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6930 		 * to ignore errors set by ICMP anyway ('cause they might be
6931 		 * forged), but that's the app's decision, not ours.
6932 		 */
6933 
6934 		/* Bunch of reality checks for DEBUG kernels... */
6935 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6936 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6937 
6938 		return (B_TRUE);
6939 	}
6940 
6941 	ipha = (ipha_t *)mp->b_rptr;
6942 	iph_len = IPH_HDR_LENGTH(ipha);
6943 	plen = ntohs(ipha->ipha_length);
6944 
6945 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6946 		/*
6947 		 * Most likely a keepalive for the benefit of an intervening
6948 		 * NAT.  These aren't for us, per se, so drop it.
6949 		 *
6950 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6951 		 * byte packets (keepalives are 1-byte), but we'll drop them
6952 		 * also.
6953 		 */
6954 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6955 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6956 		return (B_FALSE);
6957 	}
6958 
6959 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6960 		/* might as well pull it all up - it might be ESP. */
6961 		if (!pullupmsg(mp, -1)) {
6962 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6963 			    DROPPER(ipss, ipds_esp_nomem),
6964 			    &ipss->ipsec_dropper);
6965 			return (B_FALSE);
6966 		}
6967 
6968 		ipha = (ipha_t *)mp->b_rptr;
6969 	}
6970 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6971 	if (*spi == 0) {
6972 		/* UDP packet - remove 0-spi. */
6973 		shift = sizeof (uint32_t);
6974 	} else {
6975 		/* ESP-in-UDP packet - reduce to ESP. */
6976 		ipha->ipha_protocol = IPPROTO_ESP;
6977 		shift = sizeof (udpha_t);
6978 	}
6979 
6980 	/* Fix IP header */
6981 	ipha->ipha_length = htons(plen - shift);
6982 	ipha->ipha_hdr_checksum = 0;
6983 
6984 	orptr = mp->b_rptr;
6985 	mp->b_rptr += shift;
6986 
6987 	udpha = (udpha_t *)(orptr + iph_len);
6988 	if (*spi == 0) {
6989 		ASSERT((uint8_t *)ipha == orptr);
6990 		udpha->uha_length = htons(plen - shift - iph_len);
6991 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
6992 		esp_ports = 0;
6993 	} else {
6994 		esp_ports = *((uint32_t *)udpha);
6995 		ASSERT(esp_ports != 0);
6996 	}
6997 	ovbcopy(orptr, orptr + shift, iph_len);
6998 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
6999 		ipha = (ipha_t *)(orptr + shift);
7000 
7001 		free_ire = (ire == NULL);
7002 		if (free_ire) {
7003 			/* Re-acquire ire. */
7004 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
7005 			    ipss->ipsec_netstack->netstack_ip);
7006 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
7007 				if (ire != NULL)
7008 					ire_refrele(ire);
7009 				/*
7010 				 * Do a regular freemsg(), as this is an IP
7011 				 * error (no local route) not an IPsec one.
7012 				 */
7013 				freemsg(mp);
7014 			}
7015 		}
7016 
7017 		ip_proto_input(q, mp, ipha, ire, recv_ill, esp_ports);
7018 		if (free_ire)
7019 			ire_refrele(ire);
7020 	}
7021 
7022 	return (esp_ports == 0);
7023 }
7024 
7025 /*
7026  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
7027  * We are responsible for disposing of mp, such as by freemsg() or putnext()
7028  * Caller is responsible for dropping references to the conn, and freeing
7029  * first_mp.
7030  *
7031  * IPQoS Notes
7032  * Before sending it to the client, invoke IPPF processing. Policy processing
7033  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
7034  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
7035  * ip_wput_local, ip_policy is false.
7036  */
7037 static void
7038 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7039     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7040     boolean_t ip_policy)
7041 {
7042 	boolean_t	mctl_present = (first_mp != NULL);
7043 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7044 	uint32_t	ill_index;
7045 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7046 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7047 
7048 	ASSERT(ill != NULL);
7049 
7050 	if (mctl_present)
7051 		first_mp->b_cont = mp;
7052 	else
7053 		first_mp = mp;
7054 
7055 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
7056 	    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
7057 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7058 		freemsg(first_mp);
7059 		return;
7060 	}
7061 
7062 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7063 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7064 		    NULL, mctl_present);
7065 		/* Freed by ipsec_check_inbound_policy(). */
7066 		if (first_mp == NULL) {
7067 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7068 			return;
7069 		}
7070 	}
7071 	if (mctl_present)
7072 		freeb(first_mp);
7073 
7074 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7075 	if (connp->conn_udp->udp_nat_t_endpoint) {
7076 		if (mctl_present) {
7077 			/* mctl_present *shouldn't* happen. */
7078 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7079 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7080 			    &ipss->ipsec_dropper);
7081 			return;
7082 		}
7083 
7084 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7085 			return;
7086 	}
7087 
7088 	/* Handle options. */
7089 	if (connp->conn_recvif)
7090 		in_flags = IPF_RECVIF;
7091 	/*
7092 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7093 	 * passed to ip_add_info is based on IP version of connp.
7094 	 */
7095 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7096 		if (connp->conn_af_isv6) {
7097 			/*
7098 			 * V6 only needs index
7099 			 */
7100 			in_flags |= IPF_RECVIF;
7101 		} else {
7102 			/*
7103 			 * V4 needs index + matching address.
7104 			 */
7105 			in_flags |= IPF_RECVADDR;
7106 		}
7107 	}
7108 
7109 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7110 		in_flags |= IPF_RECVSLLA;
7111 
7112 	/*
7113 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7114 	 * freed if the packet is dropped. The caller will do so.
7115 	 */
7116 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7117 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7118 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7119 		if (mp == NULL) {
7120 			return;
7121 		}
7122 	}
7123 	if ((in_flags != 0) &&
7124 	    (mp->b_datap->db_type != M_CTL)) {
7125 		/*
7126 		 * The actual data will be contained in b_cont
7127 		 * upon successful return of the following call
7128 		 * else original mblk is returned
7129 		 */
7130 		ASSERT(recv_ill != NULL);
7131 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7132 		    ipst);
7133 	}
7134 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7135 	/* Send it upstream */
7136 	(connp->conn_recv)(connp, mp, NULL);
7137 }
7138 
7139 /*
7140  * Fanout for UDP packets.
7141  * The caller puts <fport, lport> in the ports parameter.
7142  *
7143  * If SO_REUSEADDR is set all multicast and broadcast packets
7144  * will be delivered to all streams bound to the same port.
7145  *
7146  * Zones notes:
7147  * Multicast and broadcast packets will be distributed to streams in all zones.
7148  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7149  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7150  * packets. To maintain this behavior with multiple zones, the conns are grouped
7151  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7152  * each zone. If unset, all the following conns in the same zone are skipped.
7153  */
7154 static void
7155 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7156     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7157     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7158 {
7159 	uint32_t	dstport, srcport;
7160 	ipaddr_t	dst;
7161 	mblk_t		*first_mp;
7162 	boolean_t	secure;
7163 	in6_addr_t	v6src;
7164 	conn_t		*connp;
7165 	connf_t		*connfp;
7166 	conn_t		*first_connp;
7167 	conn_t		*next_connp;
7168 	mblk_t		*mp1, *first_mp1;
7169 	ipaddr_t	src;
7170 	zoneid_t	last_zoneid;
7171 	boolean_t	reuseaddr;
7172 	boolean_t	shared_addr;
7173 	boolean_t	unlabeled;
7174 	ip_stack_t	*ipst;
7175 
7176 	ASSERT(recv_ill != NULL);
7177 	ipst = recv_ill->ill_ipst;
7178 
7179 	first_mp = mp;
7180 	if (mctl_present) {
7181 		mp = first_mp->b_cont;
7182 		first_mp->b_cont = NULL;
7183 		secure = ipsec_in_is_secure(first_mp);
7184 		ASSERT(mp != NULL);
7185 	} else {
7186 		first_mp = NULL;
7187 		secure = B_FALSE;
7188 	}
7189 
7190 	/* Extract ports in net byte order */
7191 	dstport = htons(ntohl(ports) & 0xFFFF);
7192 	srcport = htons(ntohl(ports) >> 16);
7193 	dst = ipha->ipha_dst;
7194 	src = ipha->ipha_src;
7195 
7196 	unlabeled = B_FALSE;
7197 	if (is_system_labeled())
7198 		/* Cred cannot be null on IPv4 */
7199 		unlabeled = (crgetlabel(DB_CRED(mp))->tsl_flags &
7200 		    TSLF_UNLABELED) != 0;
7201 	shared_addr = (zoneid == ALL_ZONES);
7202 	if (shared_addr) {
7203 		/*
7204 		 * No need to handle exclusive-stack zones since ALL_ZONES
7205 		 * only applies to the shared stack.
7206 		 */
7207 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7208 		/*
7209 		 * If no shared MLP is found, tsol_mlp_findzone returns
7210 		 * ALL_ZONES.  In that case, we assume it's SLP, and
7211 		 * search for the zone based on the packet label.
7212 		 *
7213 		 * If there is such a zone, we prefer to find a
7214 		 * connection in it.  Otherwise, we look for a
7215 		 * MAC-exempt connection in any zone whose label
7216 		 * dominates the default label on the packet.
7217 		 */
7218 		if (zoneid == ALL_ZONES)
7219 			zoneid = tsol_packet_to_zoneid(mp);
7220 		else
7221 			unlabeled = B_FALSE;
7222 	}
7223 
7224 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7225 	mutex_enter(&connfp->connf_lock);
7226 	connp = connfp->connf_head;
7227 	if (!broadcast && !CLASSD(dst)) {
7228 		/*
7229 		 * Not broadcast or multicast. Send to the one (first)
7230 		 * client we find. No need to check conn_wantpacket()
7231 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7232 		 * IPv4 unicast packets.
7233 		 */
7234 		while ((connp != NULL) &&
7235 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7236 		    (!IPCL_ZONE_MATCH(connp, zoneid) &&
7237 		    !(unlabeled && connp->conn_mac_exempt)))) {
7238 			/*
7239 			 * We keep searching since the conn did not match,
7240 			 * or its zone did not match and it is not either
7241 			 * an allzones conn or a mac exempt conn (if the
7242 			 * sender is unlabeled.)
7243 			 */
7244 			connp = connp->conn_next;
7245 		}
7246 
7247 		if (connp == NULL ||
7248 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7249 			goto notfound;
7250 
7251 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7252 
7253 		if (is_system_labeled() &&
7254 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7255 		    connp))
7256 			goto notfound;
7257 
7258 		CONN_INC_REF(connp);
7259 		mutex_exit(&connfp->connf_lock);
7260 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7261 		    flags, recv_ill, ip_policy);
7262 		IP_STAT(ipst, ip_udp_fannorm);
7263 		CONN_DEC_REF(connp);
7264 		return;
7265 	}
7266 
7267 	/*
7268 	 * Broadcast and multicast case
7269 	 *
7270 	 * Need to check conn_wantpacket().
7271 	 * If SO_REUSEADDR has been set on the first we send the
7272 	 * packet to all clients that have joined the group and
7273 	 * match the port.
7274 	 */
7275 
7276 	while (connp != NULL) {
7277 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7278 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7279 		    (!is_system_labeled() ||
7280 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7281 		    connp)))
7282 			break;
7283 		connp = connp->conn_next;
7284 	}
7285 
7286 	if (connp == NULL ||
7287 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7288 		goto notfound;
7289 
7290 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7291 
7292 	first_connp = connp;
7293 	/*
7294 	 * When SO_REUSEADDR is not set, send the packet only to the first
7295 	 * matching connection in its zone by keeping track of the zoneid.
7296 	 */
7297 	reuseaddr = first_connp->conn_reuseaddr;
7298 	last_zoneid = first_connp->conn_zoneid;
7299 
7300 	CONN_INC_REF(connp);
7301 	connp = connp->conn_next;
7302 	for (;;) {
7303 		while (connp != NULL) {
7304 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7305 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7306 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7307 			    (!is_system_labeled() ||
7308 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7309 			    shared_addr, connp)))
7310 				break;
7311 			connp = connp->conn_next;
7312 		}
7313 		/*
7314 		 * Just copy the data part alone. The mctl part is
7315 		 * needed just for verifying policy and it is never
7316 		 * sent up.
7317 		 */
7318 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7319 		    ((mp1 = copymsg(mp)) == NULL))) {
7320 			/*
7321 			 * No more interested clients or memory
7322 			 * allocation failed
7323 			 */
7324 			connp = first_connp;
7325 			break;
7326 		}
7327 		if (connp->conn_zoneid != last_zoneid) {
7328 			/*
7329 			 * Update the zoneid so that the packet isn't sent to
7330 			 * any more conns in the same zone unless SO_REUSEADDR
7331 			 * is set.
7332 			 */
7333 			reuseaddr = connp->conn_reuseaddr;
7334 			last_zoneid = connp->conn_zoneid;
7335 		}
7336 		if (first_mp != NULL) {
7337 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7338 			    ipsec_info_type == IPSEC_IN);
7339 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7340 			    ipst->ips_netstack);
7341 			if (first_mp1 == NULL) {
7342 				freemsg(mp1);
7343 				connp = first_connp;
7344 				break;
7345 			}
7346 		} else {
7347 			first_mp1 = NULL;
7348 		}
7349 		CONN_INC_REF(connp);
7350 		mutex_exit(&connfp->connf_lock);
7351 		/*
7352 		 * IPQoS notes: We don't send the packet for policy
7353 		 * processing here, will do it for the last one (below).
7354 		 * i.e. we do it per-packet now, but if we do policy
7355 		 * processing per-conn, then we would need to do it
7356 		 * here too.
7357 		 */
7358 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7359 		    ipha, flags, recv_ill, B_FALSE);
7360 		mutex_enter(&connfp->connf_lock);
7361 		/* Follow the next pointer before releasing the conn. */
7362 		next_connp = connp->conn_next;
7363 		IP_STAT(ipst, ip_udp_fanmb);
7364 		CONN_DEC_REF(connp);
7365 		connp = next_connp;
7366 	}
7367 
7368 	/* Last one.  Send it upstream. */
7369 	mutex_exit(&connfp->connf_lock);
7370 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7371 	    recv_ill, ip_policy);
7372 	IP_STAT(ipst, ip_udp_fanmb);
7373 	CONN_DEC_REF(connp);
7374 	return;
7375 
7376 notfound:
7377 
7378 	mutex_exit(&connfp->connf_lock);
7379 	IP_STAT(ipst, ip_udp_fanothers);
7380 	/*
7381 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7382 	 * have already been matched above, since they live in the IPv4
7383 	 * fanout tables. This implies we only need to
7384 	 * check for IPv6 in6addr_any endpoints here.
7385 	 * Thus we compare using ipv6_all_zeros instead of the destination
7386 	 * address, except for the multicast group membership lookup which
7387 	 * uses the IPv4 destination.
7388 	 */
7389 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7390 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7391 	mutex_enter(&connfp->connf_lock);
7392 	connp = connfp->connf_head;
7393 	if (!broadcast && !CLASSD(dst)) {
7394 		while (connp != NULL) {
7395 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7396 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7397 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7398 			    !connp->conn_ipv6_v6only)
7399 				break;
7400 			connp = connp->conn_next;
7401 		}
7402 
7403 		if (connp != NULL && is_system_labeled() &&
7404 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7405 		    connp))
7406 			connp = NULL;
7407 
7408 		if (connp == NULL ||
7409 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7410 			/*
7411 			 * No one bound to this port.  Is
7412 			 * there a client that wants all
7413 			 * unclaimed datagrams?
7414 			 */
7415 			mutex_exit(&connfp->connf_lock);
7416 
7417 			if (mctl_present)
7418 				first_mp->b_cont = mp;
7419 			else
7420 				first_mp = mp;
7421 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7422 			    connf_head != NULL) {
7423 				ip_fanout_proto(q, first_mp, ill, ipha,
7424 				    flags | IP_FF_RAWIP, mctl_present,
7425 				    ip_policy, recv_ill, zoneid);
7426 			} else {
7427 				if (ip_fanout_send_icmp(q, first_mp, flags,
7428 				    ICMP_DEST_UNREACHABLE,
7429 				    ICMP_PORT_UNREACHABLE,
7430 				    mctl_present, zoneid, ipst)) {
7431 					BUMP_MIB(ill->ill_ip_mib,
7432 					    udpIfStatsNoPorts);
7433 				}
7434 			}
7435 			return;
7436 		}
7437 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7438 
7439 		CONN_INC_REF(connp);
7440 		mutex_exit(&connfp->connf_lock);
7441 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7442 		    flags, recv_ill, ip_policy);
7443 		CONN_DEC_REF(connp);
7444 		return;
7445 	}
7446 	/*
7447 	 * IPv4 multicast packet being delivered to an AF_INET6
7448 	 * in6addr_any endpoint.
7449 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7450 	 * and not conn_wantpacket_v6() since any multicast membership is
7451 	 * for an IPv4-mapped multicast address.
7452 	 * The packet is sent to all clients in all zones that have joined the
7453 	 * group and match the port.
7454 	 */
7455 	while (connp != NULL) {
7456 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7457 		    srcport, v6src) &&
7458 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7459 		    (!is_system_labeled() ||
7460 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7461 		    connp)))
7462 			break;
7463 		connp = connp->conn_next;
7464 	}
7465 
7466 	if (connp == NULL ||
7467 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7468 		/*
7469 		 * No one bound to this port.  Is
7470 		 * there a client that wants all
7471 		 * unclaimed datagrams?
7472 		 */
7473 		mutex_exit(&connfp->connf_lock);
7474 
7475 		if (mctl_present)
7476 			first_mp->b_cont = mp;
7477 		else
7478 			first_mp = mp;
7479 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7480 		    NULL) {
7481 			ip_fanout_proto(q, first_mp, ill, ipha,
7482 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7483 			    recv_ill, zoneid);
7484 		} else {
7485 			/*
7486 			 * We used to attempt to send an icmp error here, but
7487 			 * since this is known to be a multicast packet
7488 			 * and we don't send icmp errors in response to
7489 			 * multicast, just drop the packet and give up sooner.
7490 			 */
7491 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7492 			freemsg(first_mp);
7493 		}
7494 		return;
7495 	}
7496 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7497 
7498 	first_connp = connp;
7499 
7500 	CONN_INC_REF(connp);
7501 	connp = connp->conn_next;
7502 	for (;;) {
7503 		while (connp != NULL) {
7504 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7505 			    ipv6_all_zeros, srcport, v6src) &&
7506 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7507 			    (!is_system_labeled() ||
7508 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7509 			    shared_addr, connp)))
7510 				break;
7511 			connp = connp->conn_next;
7512 		}
7513 		/*
7514 		 * Just copy the data part alone. The mctl part is
7515 		 * needed just for verifying policy and it is never
7516 		 * sent up.
7517 		 */
7518 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7519 		    ((mp1 = copymsg(mp)) == NULL))) {
7520 			/*
7521 			 * No more intested clients or memory
7522 			 * allocation failed
7523 			 */
7524 			connp = first_connp;
7525 			break;
7526 		}
7527 		if (first_mp != NULL) {
7528 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7529 			    ipsec_info_type == IPSEC_IN);
7530 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7531 			    ipst->ips_netstack);
7532 			if (first_mp1 == NULL) {
7533 				freemsg(mp1);
7534 				connp = first_connp;
7535 				break;
7536 			}
7537 		} else {
7538 			first_mp1 = NULL;
7539 		}
7540 		CONN_INC_REF(connp);
7541 		mutex_exit(&connfp->connf_lock);
7542 		/*
7543 		 * IPQoS notes: We don't send the packet for policy
7544 		 * processing here, will do it for the last one (below).
7545 		 * i.e. we do it per-packet now, but if we do policy
7546 		 * processing per-conn, then we would need to do it
7547 		 * here too.
7548 		 */
7549 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7550 		    ipha, flags, recv_ill, B_FALSE);
7551 		mutex_enter(&connfp->connf_lock);
7552 		/* Follow the next pointer before releasing the conn. */
7553 		next_connp = connp->conn_next;
7554 		CONN_DEC_REF(connp);
7555 		connp = next_connp;
7556 	}
7557 
7558 	/* Last one.  Send it upstream. */
7559 	mutex_exit(&connfp->connf_lock);
7560 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7561 	    recv_ill, ip_policy);
7562 	CONN_DEC_REF(connp);
7563 }
7564 
7565 /*
7566  * Complete the ip_wput header so that it
7567  * is possible to generate ICMP
7568  * errors.
7569  */
7570 int
7571 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7572 {
7573 	ire_t *ire;
7574 
7575 	if (ipha->ipha_src == INADDR_ANY) {
7576 		ire = ire_lookup_local(zoneid, ipst);
7577 		if (ire == NULL) {
7578 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7579 			return (1);
7580 		}
7581 		ipha->ipha_src = ire->ire_addr;
7582 		ire_refrele(ire);
7583 	}
7584 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7585 	ipha->ipha_hdr_checksum = 0;
7586 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7587 	return (0);
7588 }
7589 
7590 /*
7591  * Nobody should be sending
7592  * packets up this stream
7593  */
7594 static void
7595 ip_lrput(queue_t *q, mblk_t *mp)
7596 {
7597 	mblk_t *mp1;
7598 
7599 	switch (mp->b_datap->db_type) {
7600 	case M_FLUSH:
7601 		/* Turn around */
7602 		if (*mp->b_rptr & FLUSHW) {
7603 			*mp->b_rptr &= ~FLUSHR;
7604 			qreply(q, mp);
7605 			return;
7606 		}
7607 		break;
7608 	}
7609 	/* Could receive messages that passed through ar_rput */
7610 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7611 		mp1->b_prev = mp1->b_next = NULL;
7612 	freemsg(mp);
7613 }
7614 
7615 /* Nobody should be sending packets down this stream */
7616 /* ARGSUSED */
7617 void
7618 ip_lwput(queue_t *q, mblk_t *mp)
7619 {
7620 	freemsg(mp);
7621 }
7622 
7623 /*
7624  * Move the first hop in any source route to ipha_dst and remove that part of
7625  * the source route.  Called by other protocols.  Errors in option formatting
7626  * are ignored - will be handled by ip_wput_options Return the final
7627  * destination (either ipha_dst or the last entry in a source route.)
7628  */
7629 ipaddr_t
7630 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7631 {
7632 	ipoptp_t	opts;
7633 	uchar_t		*opt;
7634 	uint8_t		optval;
7635 	uint8_t		optlen;
7636 	ipaddr_t	dst;
7637 	int		i;
7638 	ire_t		*ire;
7639 	ip_stack_t	*ipst = ns->netstack_ip;
7640 
7641 	ip2dbg(("ip_massage_options\n"));
7642 	dst = ipha->ipha_dst;
7643 	for (optval = ipoptp_first(&opts, ipha);
7644 	    optval != IPOPT_EOL;
7645 	    optval = ipoptp_next(&opts)) {
7646 		opt = opts.ipoptp_cur;
7647 		switch (optval) {
7648 			uint8_t off;
7649 		case IPOPT_SSRR:
7650 		case IPOPT_LSRR:
7651 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7652 				ip1dbg(("ip_massage_options: bad src route\n"));
7653 				break;
7654 			}
7655 			optlen = opts.ipoptp_len;
7656 			off = opt[IPOPT_OFFSET];
7657 			off--;
7658 		redo_srr:
7659 			if (optlen < IP_ADDR_LEN ||
7660 			    off > optlen - IP_ADDR_LEN) {
7661 				/* End of source route */
7662 				ip1dbg(("ip_massage_options: end of SR\n"));
7663 				break;
7664 			}
7665 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7666 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7667 			    ntohl(dst)));
7668 			/*
7669 			 * Check if our address is present more than
7670 			 * once as consecutive hops in source route.
7671 			 * XXX verify per-interface ip_forwarding
7672 			 * for source route?
7673 			 */
7674 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7675 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7676 			if (ire != NULL) {
7677 				ire_refrele(ire);
7678 				off += IP_ADDR_LEN;
7679 				goto redo_srr;
7680 			}
7681 			if (dst == htonl(INADDR_LOOPBACK)) {
7682 				ip1dbg(("ip_massage_options: loopback addr in "
7683 				    "source route!\n"));
7684 				break;
7685 			}
7686 			/*
7687 			 * Update ipha_dst to be the first hop and remove the
7688 			 * first hop from the source route (by overwriting
7689 			 * part of the option with NOP options).
7690 			 */
7691 			ipha->ipha_dst = dst;
7692 			/* Put the last entry in dst */
7693 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7694 			    3;
7695 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7696 
7697 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7698 			    ntohl(dst)));
7699 			/* Move down and overwrite */
7700 			opt[IP_ADDR_LEN] = opt[0];
7701 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7702 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7703 			for (i = 0; i < IP_ADDR_LEN; i++)
7704 				opt[i] = IPOPT_NOP;
7705 			break;
7706 		}
7707 	}
7708 	return (dst);
7709 }
7710 
7711 /*
7712  * Return the network mask
7713  * associated with the specified address.
7714  */
7715 ipaddr_t
7716 ip_net_mask(ipaddr_t addr)
7717 {
7718 	uchar_t	*up = (uchar_t *)&addr;
7719 	ipaddr_t mask = 0;
7720 	uchar_t	*maskp = (uchar_t *)&mask;
7721 
7722 #if defined(__i386) || defined(__amd64)
7723 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7724 #endif
7725 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7726 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7727 #endif
7728 	if (CLASSD(addr)) {
7729 		maskp[0] = 0xF0;
7730 		return (mask);
7731 	}
7732 
7733 	/* We assume Class E default netmask to be 32 */
7734 	if (CLASSE(addr))
7735 		return (0xffffffffU);
7736 
7737 	if (addr == 0)
7738 		return (0);
7739 	maskp[0] = 0xFF;
7740 	if ((up[0] & 0x80) == 0)
7741 		return (mask);
7742 
7743 	maskp[1] = 0xFF;
7744 	if ((up[0] & 0xC0) == 0x80)
7745 		return (mask);
7746 
7747 	maskp[2] = 0xFF;
7748 	if ((up[0] & 0xE0) == 0xC0)
7749 		return (mask);
7750 
7751 	/* Otherwise return no mask */
7752 	return ((ipaddr_t)0);
7753 }
7754 
7755 /*
7756  * Select an ill for the packet by considering load spreading across
7757  * a different ill in the group if dst_ill is part of some group.
7758  */
7759 ill_t *
7760 ip_newroute_get_dst_ill(ill_t *dst_ill)
7761 {
7762 	ill_t *ill;
7763 
7764 	/*
7765 	 * We schedule irrespective of whether the source address is
7766 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7767 	 */
7768 	ill = illgrp_scheduler(dst_ill);
7769 	if (ill == NULL)
7770 		return (NULL);
7771 
7772 	/*
7773 	 * For groups with names ip_sioctl_groupname ensures that all
7774 	 * ills are of same type. For groups without names, ifgrp_insert
7775 	 * ensures this.
7776 	 */
7777 	ASSERT(dst_ill->ill_type == ill->ill_type);
7778 
7779 	return (ill);
7780 }
7781 
7782 /*
7783  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7784  */
7785 ill_t *
7786 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7787     ip_stack_t *ipst)
7788 {
7789 	ill_t *ret_ill;
7790 
7791 	ASSERT(ifindex != 0);
7792 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7793 	    ipst);
7794 	if (ret_ill == NULL ||
7795 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7796 		if (isv6) {
7797 			if (ill != NULL) {
7798 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7799 			} else {
7800 				BUMP_MIB(&ipst->ips_ip6_mib,
7801 				    ipIfStatsOutDiscards);
7802 			}
7803 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7804 			    "bad ifindex %d.\n", ifindex));
7805 		} else {
7806 			if (ill != NULL) {
7807 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7808 			} else {
7809 				BUMP_MIB(&ipst->ips_ip_mib,
7810 				    ipIfStatsOutDiscards);
7811 			}
7812 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7813 			    "bad ifindex %d.\n", ifindex));
7814 		}
7815 		if (ret_ill != NULL)
7816 			ill_refrele(ret_ill);
7817 		freemsg(first_mp);
7818 		return (NULL);
7819 	}
7820 
7821 	return (ret_ill);
7822 }
7823 
7824 /*
7825  * IPv4 -
7826  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7827  * out a packet to a destination address for which we do not have specific
7828  * (or sufficient) routing information.
7829  *
7830  * NOTE : These are the scopes of some of the variables that point at IRE,
7831  *	  which needs to be followed while making any future modifications
7832  *	  to avoid memory leaks.
7833  *
7834  *	- ire and sire are the entries looked up initially by
7835  *	  ire_ftable_lookup.
7836  *	- ipif_ire is used to hold the interface ire associated with
7837  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7838  *	  it before branching out to error paths.
7839  *	- save_ire is initialized before ire_create, so that ire returned
7840  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7841  *	  before breaking out of the switch.
7842  *
7843  *	Thus on failures, we have to REFRELE only ire and sire, if they
7844  *	are not NULL.
7845  */
7846 void
7847 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7848     zoneid_t zoneid, ip_stack_t *ipst)
7849 {
7850 	areq_t	*areq;
7851 	ipaddr_t gw = 0;
7852 	ire_t	*ire = NULL;
7853 	mblk_t	*res_mp;
7854 	ipaddr_t *addrp;
7855 	ipaddr_t nexthop_addr;
7856 	ipif_t  *src_ipif = NULL;
7857 	ill_t	*dst_ill = NULL;
7858 	ipha_t  *ipha;
7859 	ire_t	*sire = NULL;
7860 	mblk_t	*first_mp;
7861 	ire_t	*save_ire;
7862 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7863 	ushort_t ire_marks = 0;
7864 	boolean_t mctl_present;
7865 	ipsec_out_t *io;
7866 	mblk_t	*saved_mp;
7867 	ire_t	*first_sire = NULL;
7868 	mblk_t	*copy_mp = NULL;
7869 	mblk_t	*xmit_mp = NULL;
7870 	ipaddr_t save_dst;
7871 	uint32_t multirt_flags =
7872 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7873 	boolean_t multirt_is_resolvable;
7874 	boolean_t multirt_resolve_next;
7875 	boolean_t unspec_src;
7876 	boolean_t do_attach_ill = B_FALSE;
7877 	boolean_t ip_nexthop = B_FALSE;
7878 	tsol_ire_gw_secattr_t *attrp = NULL;
7879 	tsol_gcgrp_t *gcgrp = NULL;
7880 	tsol_gcgrp_addr_t ga;
7881 
7882 	if (ip_debug > 2) {
7883 		/* ip1dbg */
7884 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7885 	}
7886 
7887 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7888 	if (mctl_present) {
7889 		io = (ipsec_out_t *)first_mp->b_rptr;
7890 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7891 		ASSERT(zoneid == io->ipsec_out_zoneid);
7892 		ASSERT(zoneid != ALL_ZONES);
7893 	}
7894 
7895 	ipha = (ipha_t *)mp->b_rptr;
7896 
7897 	/* All multicast lookups come through ip_newroute_ipif() */
7898 	if (CLASSD(dst)) {
7899 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7900 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7901 		freemsg(first_mp);
7902 		return;
7903 	}
7904 
7905 	if (mctl_present && io->ipsec_out_attach_if) {
7906 		/* ip_grab_attach_ill returns a held ill */
7907 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7908 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7909 
7910 		/* Failure case frees things for us. */
7911 		if (attach_ill == NULL)
7912 			return;
7913 
7914 		/*
7915 		 * Check if we need an ire that will not be
7916 		 * looked up by anybody else i.e. HIDDEN.
7917 		 */
7918 		if (ill_is_probeonly(attach_ill))
7919 			ire_marks = IRE_MARK_HIDDEN;
7920 	}
7921 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7922 		ip_nexthop = B_TRUE;
7923 		nexthop_addr = io->ipsec_out_nexthop_addr;
7924 	}
7925 	/*
7926 	 * If this IRE is created for forwarding or it is not for
7927 	 * traffic for congestion controlled protocols, mark it as temporary.
7928 	 */
7929 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7930 		ire_marks |= IRE_MARK_TEMPORARY;
7931 
7932 	/*
7933 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7934 	 * chain until it gets the most specific information available.
7935 	 * For example, we know that there is no IRE_CACHE for this dest,
7936 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7937 	 * ire_ftable_lookup will look up the gateway, etc.
7938 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7939 	 * to the destination, of equal netmask length in the forward table,
7940 	 * will be recursively explored. If no information is available
7941 	 * for the final gateway of that route, we force the returned ire
7942 	 * to be equal to sire using MATCH_IRE_PARENT.
7943 	 * At least, in this case we have a starting point (in the buckets)
7944 	 * to look for other routes to the destination in the forward table.
7945 	 * This is actually used only for multirouting, where a list
7946 	 * of routes has to be processed in sequence.
7947 	 *
7948 	 * In the process of coming up with the most specific information,
7949 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7950 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7951 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7952 	 * Two caveats when handling incomplete ire's in ip_newroute:
7953 	 * - we should be careful when accessing its ire_nce (specifically
7954 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7955 	 * - not all legacy code path callers are prepared to handle
7956 	 *   incomplete ire's, so we should not create/add incomplete
7957 	 *   ire_cache entries here. (See discussion about temporary solution
7958 	 *   further below).
7959 	 *
7960 	 * In order to minimize packet dropping, and to preserve existing
7961 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7962 	 * gateway, and instead use the IF_RESOLVER ire to send out
7963 	 * another request to ARP (this is achieved by passing the
7964 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7965 	 * arp response comes back in ip_wput_nondata, we will create
7966 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7967 	 *
7968 	 * Note that this is a temporary solution; the correct solution is
7969 	 * to create an incomplete  per-dst ire_cache entry, and send the
7970 	 * packet out when the gw's nce is resolved. In order to achieve this,
7971 	 * all packet processing must have been completed prior to calling
7972 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7973 	 * to be modified to accomodate this solution.
7974 	 */
7975 	if (ip_nexthop) {
7976 		/*
7977 		 * The first time we come here, we look for an IRE_INTERFACE
7978 		 * entry for the specified nexthop, set the dst to be the
7979 		 * nexthop address and create an IRE_CACHE entry for the
7980 		 * nexthop. The next time around, we are able to find an
7981 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7982 		 * nexthop address and create an IRE_CACHE entry for the
7983 		 * destination address via the specified nexthop.
7984 		 */
7985 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7986 		    MBLK_GETLABEL(mp), ipst);
7987 		if (ire != NULL) {
7988 			gw = nexthop_addr;
7989 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7990 		} else {
7991 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7992 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7993 			    MBLK_GETLABEL(mp),
7994 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7995 			    ipst);
7996 			if (ire != NULL) {
7997 				dst = nexthop_addr;
7998 			}
7999 		}
8000 	} else if (attach_ill == NULL) {
8001 		ire = ire_ftable_lookup(dst, 0, 0, 0,
8002 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
8003 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
8004 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
8005 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
8006 		    ipst);
8007 	} else {
8008 		/*
8009 		 * attach_ill is set only for communicating with
8010 		 * on-link hosts. So, don't look for DEFAULT.
8011 		 */
8012 		ipif_t	*attach_ipif;
8013 
8014 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
8015 		if (attach_ipif == NULL) {
8016 			ill_refrele(attach_ill);
8017 			goto icmp_err_ret;
8018 		}
8019 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
8020 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
8021 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
8022 		    MATCH_IRE_SECATTR, ipst);
8023 		ipif_refrele(attach_ipif);
8024 	}
8025 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
8026 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
8027 
8028 	/*
8029 	 * This loop is run only once in most cases.
8030 	 * We loop to resolve further routes only when the destination
8031 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8032 	 */
8033 	do {
8034 		/* Clear the previous iteration's values */
8035 		if (src_ipif != NULL) {
8036 			ipif_refrele(src_ipif);
8037 			src_ipif = NULL;
8038 		}
8039 		if (dst_ill != NULL) {
8040 			ill_refrele(dst_ill);
8041 			dst_ill = NULL;
8042 		}
8043 
8044 		multirt_resolve_next = B_FALSE;
8045 		/*
8046 		 * We check if packets have to be multirouted.
8047 		 * In this case, given the current <ire, sire> couple,
8048 		 * we look for the next suitable <ire, sire>.
8049 		 * This check is done in ire_multirt_lookup(),
8050 		 * which applies various criteria to find the next route
8051 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
8052 		 * unchanged if it detects it has not been tried yet.
8053 		 */
8054 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8055 			ip3dbg(("ip_newroute: starting next_resolution "
8056 			    "with first_mp %p, tag %d\n",
8057 			    (void *)first_mp,
8058 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8059 
8060 			ASSERT(sire != NULL);
8061 			multirt_is_resolvable =
8062 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8063 			    MBLK_GETLABEL(mp), ipst);
8064 
8065 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8066 			    "ire %p, sire %p\n",
8067 			    multirt_is_resolvable,
8068 			    (void *)ire, (void *)sire));
8069 
8070 			if (!multirt_is_resolvable) {
8071 				/*
8072 				 * No more multirt route to resolve; give up
8073 				 * (all routes resolved or no more
8074 				 * resolvable routes).
8075 				 */
8076 				if (ire != NULL) {
8077 					ire_refrele(ire);
8078 					ire = NULL;
8079 				}
8080 			} else {
8081 				ASSERT(sire != NULL);
8082 				ASSERT(ire != NULL);
8083 				/*
8084 				 * We simply use first_sire as a flag that
8085 				 * indicates if a resolvable multirt route
8086 				 * has already been found.
8087 				 * If it is not the case, we may have to send
8088 				 * an ICMP error to report that the
8089 				 * destination is unreachable.
8090 				 * We do not IRE_REFHOLD first_sire.
8091 				 */
8092 				if (first_sire == NULL) {
8093 					first_sire = sire;
8094 				}
8095 			}
8096 		}
8097 		if (ire == NULL) {
8098 			if (ip_debug > 3) {
8099 				/* ip2dbg */
8100 				pr_addr_dbg("ip_newroute: "
8101 				    "can't resolve %s\n", AF_INET, &dst);
8102 			}
8103 			ip3dbg(("ip_newroute: "
8104 			    "ire %p, sire %p, first_sire %p\n",
8105 			    (void *)ire, (void *)sire, (void *)first_sire));
8106 
8107 			if (sire != NULL) {
8108 				ire_refrele(sire);
8109 				sire = NULL;
8110 			}
8111 
8112 			if (first_sire != NULL) {
8113 				/*
8114 				 * At least one multirt route has been found
8115 				 * in the same call to ip_newroute();
8116 				 * there is no need to report an ICMP error.
8117 				 * first_sire was not IRE_REFHOLDed.
8118 				 */
8119 				MULTIRT_DEBUG_UNTAG(first_mp);
8120 				freemsg(first_mp);
8121 				return;
8122 			}
8123 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8124 			    RTA_DST, ipst);
8125 			if (attach_ill != NULL)
8126 				ill_refrele(attach_ill);
8127 			goto icmp_err_ret;
8128 		}
8129 
8130 		/*
8131 		 * Verify that the returned IRE does not have either
8132 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8133 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8134 		 */
8135 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8136 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8137 			if (attach_ill != NULL)
8138 				ill_refrele(attach_ill);
8139 			goto icmp_err_ret;
8140 		}
8141 		/*
8142 		 * Increment the ire_ob_pkt_count field for ire if it is an
8143 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8144 		 * increment the same for the parent IRE, sire, if it is some
8145 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8146 		 */
8147 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8148 			UPDATE_OB_PKT_COUNT(ire);
8149 			ire->ire_last_used_time = lbolt;
8150 		}
8151 
8152 		if (sire != NULL) {
8153 			gw = sire->ire_gateway_addr;
8154 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8155 			    IRE_INTERFACE)) == 0);
8156 			UPDATE_OB_PKT_COUNT(sire);
8157 			sire->ire_last_used_time = lbolt;
8158 		}
8159 		/*
8160 		 * We have a route to reach the destination.
8161 		 *
8162 		 * 1) If the interface is part of ill group, try to get a new
8163 		 *    ill taking load spreading into account.
8164 		 *
8165 		 * 2) After selecting the ill, get a source address that
8166 		 *    might create good inbound load spreading.
8167 		 *    ipif_select_source does this for us.
8168 		 *
8169 		 * If the application specified the ill (ifindex), we still
8170 		 * load spread. Only if the packets needs to go out
8171 		 * specifically on a given ill e.g. binding to
8172 		 * IPIF_NOFAILOVER address, then we don't try to use a
8173 		 * different ill for load spreading.
8174 		 */
8175 		if (attach_ill == NULL) {
8176 			/*
8177 			 * Don't perform outbound load spreading in the
8178 			 * case of an RTF_MULTIRT route, as we actually
8179 			 * typically want to replicate outgoing packets
8180 			 * through particular interfaces.
8181 			 */
8182 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8183 				dst_ill = ire->ire_ipif->ipif_ill;
8184 				/* for uniformity */
8185 				ill_refhold(dst_ill);
8186 			} else {
8187 				/*
8188 				 * If we are here trying to create an IRE_CACHE
8189 				 * for an offlink destination and have the
8190 				 * IRE_CACHE for the next hop and the latter is
8191 				 * using virtual IP source address selection i.e
8192 				 * it's ire->ire_ipif is pointing to a virtual
8193 				 * network interface (vni) then
8194 				 * ip_newroute_get_dst_ll() will return the vni
8195 				 * interface as the dst_ill. Since the vni is
8196 				 * virtual i.e not associated with any physical
8197 				 * interface, it cannot be the dst_ill, hence
8198 				 * in such a case call ip_newroute_get_dst_ll()
8199 				 * with the stq_ill instead of the ire_ipif ILL.
8200 				 * The function returns a refheld ill.
8201 				 */
8202 				if ((ire->ire_type == IRE_CACHE) &&
8203 				    IS_VNI(ire->ire_ipif->ipif_ill))
8204 					dst_ill = ip_newroute_get_dst_ill(
8205 					    ire->ire_stq->q_ptr);
8206 				else
8207 					dst_ill = ip_newroute_get_dst_ill(
8208 					    ire->ire_ipif->ipif_ill);
8209 			}
8210 			if (dst_ill == NULL) {
8211 				if (ip_debug > 2) {
8212 					pr_addr_dbg("ip_newroute: "
8213 					    "no dst ill for dst"
8214 					    " %s\n", AF_INET, &dst);
8215 				}
8216 				goto icmp_err_ret;
8217 			}
8218 		} else {
8219 			dst_ill = ire->ire_ipif->ipif_ill;
8220 			/* for uniformity */
8221 			ill_refhold(dst_ill);
8222 			/*
8223 			 * We should have found a route matching ill as we
8224 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8225 			 * Rather than asserting, when there is a mismatch,
8226 			 * we just drop the packet.
8227 			 */
8228 			if (dst_ill != attach_ill) {
8229 				ip0dbg(("ip_newroute: Packet dropped as "
8230 				    "IPIF_NOFAILOVER ill is %s, "
8231 				    "ire->ire_ipif->ipif_ill is %s\n",
8232 				    attach_ill->ill_name,
8233 				    dst_ill->ill_name));
8234 				ill_refrele(attach_ill);
8235 				goto icmp_err_ret;
8236 			}
8237 		}
8238 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8239 		if (attach_ill != NULL) {
8240 			ill_refrele(attach_ill);
8241 			attach_ill = NULL;
8242 			do_attach_ill = B_TRUE;
8243 		}
8244 		ASSERT(dst_ill != NULL);
8245 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8246 
8247 		/*
8248 		 * Pick the best source address from dst_ill.
8249 		 *
8250 		 * 1) If it is part of a multipathing group, we would
8251 		 *    like to spread the inbound packets across different
8252 		 *    interfaces. ipif_select_source picks a random source
8253 		 *    across the different ills in the group.
8254 		 *
8255 		 * 2) If it is not part of a multipathing group, we try
8256 		 *    to pick the source address from the destination
8257 		 *    route. Clustering assumes that when we have multiple
8258 		 *    prefixes hosted on an interface, the prefix of the
8259 		 *    source address matches the prefix of the destination
8260 		 *    route. We do this only if the address is not
8261 		 *    DEPRECATED.
8262 		 *
8263 		 * 3) If the conn is in a different zone than the ire, we
8264 		 *    need to pick a source address from the right zone.
8265 		 *
8266 		 * NOTE : If we hit case (1) above, the prefix of the source
8267 		 *	  address picked may not match the prefix of the
8268 		 *	  destination routes prefix as ipif_select_source
8269 		 *	  does not look at "dst" while picking a source
8270 		 *	  address.
8271 		 *	  If we want the same behavior as (2), we will need
8272 		 *	  to change the behavior of ipif_select_source.
8273 		 */
8274 		ASSERT(src_ipif == NULL);
8275 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8276 			/*
8277 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8278 			 * Check that the ipif matching the requested source
8279 			 * address still exists.
8280 			 */
8281 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8282 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8283 		}
8284 
8285 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8286 
8287 		if (src_ipif == NULL &&
8288 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8289 			ire_marks |= IRE_MARK_USESRC_CHECK;
8290 			if ((dst_ill->ill_group != NULL) ||
8291 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8292 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8293 			    ire->ire_zoneid != ALL_ZONES) ||
8294 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8295 				/*
8296 				 * If the destination is reachable via a
8297 				 * given gateway, the selected source address
8298 				 * should be in the same subnet as the gateway.
8299 				 * Otherwise, the destination is not reachable.
8300 				 *
8301 				 * If there are no interfaces on the same subnet
8302 				 * as the destination, ipif_select_source gives
8303 				 * first non-deprecated interface which might be
8304 				 * on a different subnet than the gateway.
8305 				 * This is not desirable. Hence pass the dst_ire
8306 				 * source address to ipif_select_source.
8307 				 * It is sure that the destination is reachable
8308 				 * with the dst_ire source address subnet.
8309 				 * So passing dst_ire source address to
8310 				 * ipif_select_source will make sure that the
8311 				 * selected source will be on the same subnet
8312 				 * as dst_ire source address.
8313 				 */
8314 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8315 				src_ipif = ipif_select_source(dst_ill, saddr,
8316 				    zoneid);
8317 				if (src_ipif == NULL) {
8318 					if (ip_debug > 2) {
8319 						pr_addr_dbg("ip_newroute: "
8320 						    "no src for dst %s ",
8321 						    AF_INET, &dst);
8322 						printf("through interface %s\n",
8323 						    dst_ill->ill_name);
8324 					}
8325 					goto icmp_err_ret;
8326 				}
8327 			} else {
8328 				src_ipif = ire->ire_ipif;
8329 				ASSERT(src_ipif != NULL);
8330 				/* hold src_ipif for uniformity */
8331 				ipif_refhold(src_ipif);
8332 			}
8333 		}
8334 
8335 		/*
8336 		 * Assign a source address while we have the conn.
8337 		 * We can't have ip_wput_ire pick a source address when the
8338 		 * packet returns from arp since we need to look at
8339 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8340 		 * going through arp.
8341 		 *
8342 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8343 		 *	  it uses ip6i to store this information.
8344 		 */
8345 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8346 			ipha->ipha_src = src_ipif->ipif_src_addr;
8347 
8348 		if (ip_debug > 3) {
8349 			/* ip2dbg */
8350 			pr_addr_dbg("ip_newroute: first hop %s\n",
8351 			    AF_INET, &gw);
8352 		}
8353 		ip2dbg(("\tire type %s (%d)\n",
8354 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8355 
8356 		/*
8357 		 * The TTL of multirouted packets is bounded by the
8358 		 * ip_multirt_ttl ndd variable.
8359 		 */
8360 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8361 			/* Force TTL of multirouted packets */
8362 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8363 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8364 				ip2dbg(("ip_newroute: forcing multirt TTL "
8365 				    "to %d (was %d), dst 0x%08x\n",
8366 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8367 				    ntohl(sire->ire_addr)));
8368 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8369 			}
8370 		}
8371 		/*
8372 		 * At this point in ip_newroute(), ire is either the
8373 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8374 		 * destination or an IRE_INTERFACE type that should be used
8375 		 * to resolve an on-subnet destination or an on-subnet
8376 		 * next-hop gateway.
8377 		 *
8378 		 * In the IRE_CACHE case, we have the following :
8379 		 *
8380 		 * 1) src_ipif - used for getting a source address.
8381 		 *
8382 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8383 		 *    means packets using this IRE_CACHE will go out on
8384 		 *    dst_ill.
8385 		 *
8386 		 * 3) The IRE sire will point to the prefix that is the
8387 		 *    longest  matching route for the destination. These
8388 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8389 		 *
8390 		 *    The newly created IRE_CACHE entry for the off-subnet
8391 		 *    destination is tied to both the prefix route and the
8392 		 *    interface route used to resolve the next-hop gateway
8393 		 *    via the ire_phandle and ire_ihandle fields,
8394 		 *    respectively.
8395 		 *
8396 		 * In the IRE_INTERFACE case, we have the following :
8397 		 *
8398 		 * 1) src_ipif - used for getting a source address.
8399 		 *
8400 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8401 		 *    means packets using the IRE_CACHE that we will build
8402 		 *    here will go out on dst_ill.
8403 		 *
8404 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8405 		 *    to be created will only be tied to the IRE_INTERFACE
8406 		 *    that was derived from the ire_ihandle field.
8407 		 *
8408 		 *    If sire is non-NULL, it means the destination is
8409 		 *    off-link and we will first create the IRE_CACHE for the
8410 		 *    gateway. Next time through ip_newroute, we will create
8411 		 *    the IRE_CACHE for the final destination as described
8412 		 *    above.
8413 		 *
8414 		 * In both cases, after the current resolution has been
8415 		 * completed (or possibly initialised, in the IRE_INTERFACE
8416 		 * case), the loop may be re-entered to attempt the resolution
8417 		 * of another RTF_MULTIRT route.
8418 		 *
8419 		 * When an IRE_CACHE entry for the off-subnet destination is
8420 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8421 		 * for further processing in emission loops.
8422 		 */
8423 		save_ire = ire;
8424 		switch (ire->ire_type) {
8425 		case IRE_CACHE: {
8426 			ire_t	*ipif_ire;
8427 
8428 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8429 			if (gw == 0)
8430 				gw = ire->ire_gateway_addr;
8431 			/*
8432 			 * We need 3 ire's to create a new cache ire for an
8433 			 * off-link destination from the cache ire of the
8434 			 * gateway.
8435 			 *
8436 			 *	1. The prefix ire 'sire' (Note that this does
8437 			 *	   not apply to the conn_nexthop_set case)
8438 			 *	2. The cache ire of the gateway 'ire'
8439 			 *	3. The interface ire 'ipif_ire'
8440 			 *
8441 			 * We have (1) and (2). We lookup (3) below.
8442 			 *
8443 			 * If there is no interface route to the gateway,
8444 			 * it is a race condition, where we found the cache
8445 			 * but the interface route has been deleted.
8446 			 */
8447 			if (ip_nexthop) {
8448 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8449 			} else {
8450 				ipif_ire =
8451 				    ire_ihandle_lookup_offlink(ire, sire);
8452 			}
8453 			if (ipif_ire == NULL) {
8454 				ip1dbg(("ip_newroute: "
8455 				    "ire_ihandle_lookup_offlink failed\n"));
8456 				goto icmp_err_ret;
8457 			}
8458 
8459 			/*
8460 			 * Check cached gateway IRE for any security
8461 			 * attributes; if found, associate the gateway
8462 			 * credentials group to the destination IRE.
8463 			 */
8464 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8465 				mutex_enter(&attrp->igsa_lock);
8466 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8467 					GCGRP_REFHOLD(gcgrp);
8468 				mutex_exit(&attrp->igsa_lock);
8469 			}
8470 
8471 			/*
8472 			 * XXX For the source of the resolver mp,
8473 			 * we are using the same DL_UNITDATA_REQ
8474 			 * (from save_ire->ire_nce->nce_res_mp)
8475 			 * though the save_ire is not pointing at the same ill.
8476 			 * This is incorrect. We need to send it up to the
8477 			 * resolver to get the right res_mp. For ethernets
8478 			 * this may be okay (ill_type == DL_ETHER).
8479 			 */
8480 
8481 			ire = ire_create(
8482 			    (uchar_t *)&dst,		/* dest address */
8483 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8484 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8485 			    (uchar_t *)&gw,		/* gateway address */
8486 			    &save_ire->ire_max_frag,
8487 			    save_ire->ire_nce,		/* src nce */
8488 			    dst_ill->ill_rq,		/* recv-from queue */
8489 			    dst_ill->ill_wq,		/* send-to queue */
8490 			    IRE_CACHE,			/* IRE type */
8491 			    src_ipif,
8492 			    (sire != NULL) ?
8493 			    sire->ire_mask : 0, 	/* Parent mask */
8494 			    (sire != NULL) ?
8495 			    sire->ire_phandle : 0,	/* Parent handle */
8496 			    ipif_ire->ire_ihandle,	/* Interface handle */
8497 			    (sire != NULL) ? (sire->ire_flags &
8498 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8499 			    (sire != NULL) ?
8500 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8501 			    NULL,
8502 			    gcgrp,
8503 			    ipst);
8504 
8505 			if (ire == NULL) {
8506 				if (gcgrp != NULL) {
8507 					GCGRP_REFRELE(gcgrp);
8508 					gcgrp = NULL;
8509 				}
8510 				ire_refrele(ipif_ire);
8511 				ire_refrele(save_ire);
8512 				break;
8513 			}
8514 
8515 			/* reference now held by IRE */
8516 			gcgrp = NULL;
8517 
8518 			ire->ire_marks |= ire_marks;
8519 
8520 			/*
8521 			 * Prevent sire and ipif_ire from getting deleted.
8522 			 * The newly created ire is tied to both of them via
8523 			 * the phandle and ihandle respectively.
8524 			 */
8525 			if (sire != NULL) {
8526 				IRB_REFHOLD(sire->ire_bucket);
8527 				/* Has it been removed already ? */
8528 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8529 					IRB_REFRELE(sire->ire_bucket);
8530 					ire_refrele(ipif_ire);
8531 					ire_refrele(save_ire);
8532 					break;
8533 				}
8534 			}
8535 
8536 			IRB_REFHOLD(ipif_ire->ire_bucket);
8537 			/* Has it been removed already ? */
8538 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8539 				IRB_REFRELE(ipif_ire->ire_bucket);
8540 				if (sire != NULL)
8541 					IRB_REFRELE(sire->ire_bucket);
8542 				ire_refrele(ipif_ire);
8543 				ire_refrele(save_ire);
8544 				break;
8545 			}
8546 
8547 			xmit_mp = first_mp;
8548 			/*
8549 			 * In the case of multirouting, a copy
8550 			 * of the packet is done before its sending.
8551 			 * The copy is used to attempt another
8552 			 * route resolution, in a next loop.
8553 			 */
8554 			if (ire->ire_flags & RTF_MULTIRT) {
8555 				copy_mp = copymsg(first_mp);
8556 				if (copy_mp != NULL) {
8557 					xmit_mp = copy_mp;
8558 					MULTIRT_DEBUG_TAG(first_mp);
8559 				}
8560 			}
8561 			ire_add_then_send(q, ire, xmit_mp);
8562 			ire_refrele(save_ire);
8563 
8564 			/* Assert that sire is not deleted yet. */
8565 			if (sire != NULL) {
8566 				ASSERT(sire->ire_ptpn != NULL);
8567 				IRB_REFRELE(sire->ire_bucket);
8568 			}
8569 
8570 			/* Assert that ipif_ire is not deleted yet. */
8571 			ASSERT(ipif_ire->ire_ptpn != NULL);
8572 			IRB_REFRELE(ipif_ire->ire_bucket);
8573 			ire_refrele(ipif_ire);
8574 
8575 			/*
8576 			 * If copy_mp is not NULL, multirouting was
8577 			 * requested. We loop to initiate a next
8578 			 * route resolution attempt, starting from sire.
8579 			 */
8580 			if (copy_mp != NULL) {
8581 				/*
8582 				 * Search for the next unresolved
8583 				 * multirt route.
8584 				 */
8585 				copy_mp = NULL;
8586 				ipif_ire = NULL;
8587 				ire = NULL;
8588 				multirt_resolve_next = B_TRUE;
8589 				continue;
8590 			}
8591 			if (sire != NULL)
8592 				ire_refrele(sire);
8593 			ipif_refrele(src_ipif);
8594 			ill_refrele(dst_ill);
8595 			return;
8596 		}
8597 		case IRE_IF_NORESOLVER: {
8598 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8599 			    dst_ill->ill_resolver_mp == NULL) {
8600 				ip1dbg(("ip_newroute: dst_ill %p "
8601 				    "for IRE_IF_NORESOLVER ire %p has "
8602 				    "no ill_resolver_mp\n",
8603 				    (void *)dst_ill, (void *)ire));
8604 				break;
8605 			}
8606 
8607 			/*
8608 			 * TSol note: We are creating the ire cache for the
8609 			 * destination 'dst'. If 'dst' is offlink, going
8610 			 * through the first hop 'gw', the security attributes
8611 			 * of 'dst' must be set to point to the gateway
8612 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8613 			 * is possible that 'dst' is a potential gateway that is
8614 			 * referenced by some route that has some security
8615 			 * attributes. Thus in the former case, we need to do a
8616 			 * gcgrp_lookup of 'gw' while in the latter case we
8617 			 * need to do gcgrp_lookup of 'dst' itself.
8618 			 */
8619 			ga.ga_af = AF_INET;
8620 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8621 			    &ga.ga_addr);
8622 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8623 
8624 			ire = ire_create(
8625 			    (uchar_t *)&dst,		/* dest address */
8626 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8627 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8628 			    (uchar_t *)&gw,		/* gateway address */
8629 			    &save_ire->ire_max_frag,
8630 			    NULL,			/* no src nce */
8631 			    dst_ill->ill_rq,		/* recv-from queue */
8632 			    dst_ill->ill_wq,		/* send-to queue */
8633 			    IRE_CACHE,
8634 			    src_ipif,
8635 			    save_ire->ire_mask,		/* Parent mask */
8636 			    (sire != NULL) ?		/* Parent handle */
8637 			    sire->ire_phandle : 0,
8638 			    save_ire->ire_ihandle,	/* Interface handle */
8639 			    (sire != NULL) ? sire->ire_flags &
8640 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8641 			    &(save_ire->ire_uinfo),
8642 			    NULL,
8643 			    gcgrp,
8644 			    ipst);
8645 
8646 			if (ire == NULL) {
8647 				if (gcgrp != NULL) {
8648 					GCGRP_REFRELE(gcgrp);
8649 					gcgrp = NULL;
8650 				}
8651 				ire_refrele(save_ire);
8652 				break;
8653 			}
8654 
8655 			/* reference now held by IRE */
8656 			gcgrp = NULL;
8657 
8658 			ire->ire_marks |= ire_marks;
8659 
8660 			/* Prevent save_ire from getting deleted */
8661 			IRB_REFHOLD(save_ire->ire_bucket);
8662 			/* Has it been removed already ? */
8663 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8664 				IRB_REFRELE(save_ire->ire_bucket);
8665 				ire_refrele(save_ire);
8666 				break;
8667 			}
8668 
8669 			/*
8670 			 * In the case of multirouting, a copy
8671 			 * of the packet is made before it is sent.
8672 			 * The copy is used in the next
8673 			 * loop to attempt another resolution.
8674 			 */
8675 			xmit_mp = first_mp;
8676 			if ((sire != NULL) &&
8677 			    (sire->ire_flags & RTF_MULTIRT)) {
8678 				copy_mp = copymsg(first_mp);
8679 				if (copy_mp != NULL) {
8680 					xmit_mp = copy_mp;
8681 					MULTIRT_DEBUG_TAG(first_mp);
8682 				}
8683 			}
8684 			ire_add_then_send(q, ire, xmit_mp);
8685 
8686 			/* Assert that it is not deleted yet. */
8687 			ASSERT(save_ire->ire_ptpn != NULL);
8688 			IRB_REFRELE(save_ire->ire_bucket);
8689 			ire_refrele(save_ire);
8690 
8691 			if (copy_mp != NULL) {
8692 				/*
8693 				 * If we found a (no)resolver, we ignore any
8694 				 * trailing top priority IRE_CACHE in further
8695 				 * loops. This ensures that we do not omit any
8696 				 * (no)resolver.
8697 				 * This IRE_CACHE, if any, will be processed
8698 				 * by another thread entering ip_newroute().
8699 				 * IRE_CACHE entries, if any, will be processed
8700 				 * by another thread entering ip_newroute(),
8701 				 * (upon resolver response, for instance).
8702 				 * This aims to force parallel multirt
8703 				 * resolutions as soon as a packet must be sent.
8704 				 * In the best case, after the tx of only one
8705 				 * packet, all reachable routes are resolved.
8706 				 * Otherwise, the resolution of all RTF_MULTIRT
8707 				 * routes would require several emissions.
8708 				 */
8709 				multirt_flags &= ~MULTIRT_CACHEGW;
8710 
8711 				/*
8712 				 * Search for the next unresolved multirt
8713 				 * route.
8714 				 */
8715 				copy_mp = NULL;
8716 				save_ire = NULL;
8717 				ire = NULL;
8718 				multirt_resolve_next = B_TRUE;
8719 				continue;
8720 			}
8721 
8722 			/*
8723 			 * Don't need sire anymore
8724 			 */
8725 			if (sire != NULL)
8726 				ire_refrele(sire);
8727 
8728 			ipif_refrele(src_ipif);
8729 			ill_refrele(dst_ill);
8730 			return;
8731 		}
8732 		case IRE_IF_RESOLVER:
8733 			/*
8734 			 * We can't build an IRE_CACHE yet, but at least we
8735 			 * found a resolver that can help.
8736 			 */
8737 			res_mp = dst_ill->ill_resolver_mp;
8738 			if (!OK_RESOLVER_MP(res_mp))
8739 				break;
8740 
8741 			/*
8742 			 * To be at this point in the code with a non-zero gw
8743 			 * means that dst is reachable through a gateway that
8744 			 * we have never resolved.  By changing dst to the gw
8745 			 * addr we resolve the gateway first.
8746 			 * When ire_add_then_send() tries to put the IP dg
8747 			 * to dst, it will reenter ip_newroute() at which
8748 			 * time we will find the IRE_CACHE for the gw and
8749 			 * create another IRE_CACHE in case IRE_CACHE above.
8750 			 */
8751 			if (gw != INADDR_ANY) {
8752 				/*
8753 				 * The source ipif that was determined above was
8754 				 * relative to the destination address, not the
8755 				 * gateway's. If src_ipif was not taken out of
8756 				 * the IRE_IF_RESOLVER entry, we'll need to call
8757 				 * ipif_select_source() again.
8758 				 */
8759 				if (src_ipif != ire->ire_ipif) {
8760 					ipif_refrele(src_ipif);
8761 					src_ipif = ipif_select_source(dst_ill,
8762 					    gw, zoneid);
8763 					if (src_ipif == NULL) {
8764 						if (ip_debug > 2) {
8765 							pr_addr_dbg(
8766 							    "ip_newroute: no "
8767 							    "src for gw %s ",
8768 							    AF_INET, &gw);
8769 							printf("through "
8770 							    "interface %s\n",
8771 							    dst_ill->ill_name);
8772 						}
8773 						goto icmp_err_ret;
8774 					}
8775 				}
8776 				save_dst = dst;
8777 				dst = gw;
8778 				gw = INADDR_ANY;
8779 			}
8780 
8781 			/*
8782 			 * We obtain a partial IRE_CACHE which we will pass
8783 			 * along with the resolver query.  When the response
8784 			 * comes back it will be there ready for us to add.
8785 			 * The ire_max_frag is atomically set under the
8786 			 * irebucket lock in ire_add_v[46].
8787 			 */
8788 
8789 			ire = ire_create_mp(
8790 			    (uchar_t *)&dst,		/* dest address */
8791 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8792 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8793 			    (uchar_t *)&gw,		/* gateway address */
8794 			    NULL,			/* ire_max_frag */
8795 			    NULL,			/* no src nce */
8796 			    dst_ill->ill_rq,		/* recv-from queue */
8797 			    dst_ill->ill_wq,		/* send-to queue */
8798 			    IRE_CACHE,
8799 			    src_ipif,			/* Interface ipif */
8800 			    save_ire->ire_mask,		/* Parent mask */
8801 			    0,
8802 			    save_ire->ire_ihandle,	/* Interface handle */
8803 			    0,				/* flags if any */
8804 			    &(save_ire->ire_uinfo),
8805 			    NULL,
8806 			    NULL,
8807 			    ipst);
8808 
8809 			if (ire == NULL) {
8810 				ire_refrele(save_ire);
8811 				break;
8812 			}
8813 
8814 			if ((sire != NULL) &&
8815 			    (sire->ire_flags & RTF_MULTIRT)) {
8816 				copy_mp = copymsg(first_mp);
8817 				if (copy_mp != NULL)
8818 					MULTIRT_DEBUG_TAG(copy_mp);
8819 			}
8820 
8821 			ire->ire_marks |= ire_marks;
8822 
8823 			/*
8824 			 * Construct message chain for the resolver
8825 			 * of the form:
8826 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8827 			 * Packet could contain a IPSEC_OUT mp.
8828 			 *
8829 			 * NOTE : ire will be added later when the response
8830 			 * comes back from ARP. If the response does not
8831 			 * come back, ARP frees the packet. For this reason,
8832 			 * we can't REFHOLD the bucket of save_ire to prevent
8833 			 * deletions. We may not be able to REFRELE the bucket
8834 			 * if the response never comes back. Thus, before
8835 			 * adding the ire, ire_add_v4 will make sure that the
8836 			 * interface route does not get deleted. This is the
8837 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8838 			 * where we can always prevent deletions because of
8839 			 * the synchronous nature of adding IRES i.e
8840 			 * ire_add_then_send is called after creating the IRE.
8841 			 */
8842 			ASSERT(ire->ire_mp != NULL);
8843 			ire->ire_mp->b_cont = first_mp;
8844 			/* Have saved_mp handy, for cleanup if canput fails */
8845 			saved_mp = mp;
8846 			mp = copyb(res_mp);
8847 			if (mp == NULL) {
8848 				/* Prepare for cleanup */
8849 				mp = saved_mp; /* pkt */
8850 				ire_delete(ire); /* ire_mp */
8851 				ire = NULL;
8852 				ire_refrele(save_ire);
8853 				if (copy_mp != NULL) {
8854 					MULTIRT_DEBUG_UNTAG(copy_mp);
8855 					freemsg(copy_mp);
8856 					copy_mp = NULL;
8857 				}
8858 				break;
8859 			}
8860 			linkb(mp, ire->ire_mp);
8861 
8862 			/*
8863 			 * Fill in the source and dest addrs for the resolver.
8864 			 * NOTE: this depends on memory layouts imposed by
8865 			 * ill_init().
8866 			 */
8867 			areq = (areq_t *)mp->b_rptr;
8868 			addrp = (ipaddr_t *)((char *)areq +
8869 			    areq->areq_sender_addr_offset);
8870 			if (do_attach_ill) {
8871 				/*
8872 				 * This is bind to no failover case.
8873 				 * arp packet also must go out on attach_ill.
8874 				 */
8875 				ASSERT(ipha->ipha_src != NULL);
8876 				*addrp = ipha->ipha_src;
8877 			} else {
8878 				*addrp = save_ire->ire_src_addr;
8879 			}
8880 
8881 			ire_refrele(save_ire);
8882 			addrp = (ipaddr_t *)((char *)areq +
8883 			    areq->areq_target_addr_offset);
8884 			*addrp = dst;
8885 			/* Up to the resolver. */
8886 			if (canputnext(dst_ill->ill_rq) &&
8887 			    !(dst_ill->ill_arp_closing)) {
8888 				putnext(dst_ill->ill_rq, mp);
8889 				ire = NULL;
8890 				if (copy_mp != NULL) {
8891 					/*
8892 					 * If we found a resolver, we ignore
8893 					 * any trailing top priority IRE_CACHE
8894 					 * in the further loops. This ensures
8895 					 * that we do not omit any resolver.
8896 					 * IRE_CACHE entries, if any, will be
8897 					 * processed next time we enter
8898 					 * ip_newroute().
8899 					 */
8900 					multirt_flags &= ~MULTIRT_CACHEGW;
8901 					/*
8902 					 * Search for the next unresolved
8903 					 * multirt route.
8904 					 */
8905 					first_mp = copy_mp;
8906 					copy_mp = NULL;
8907 					/* Prepare the next resolution loop. */
8908 					mp = first_mp;
8909 					EXTRACT_PKT_MP(mp, first_mp,
8910 					    mctl_present);
8911 					if (mctl_present)
8912 						io = (ipsec_out_t *)
8913 						    first_mp->b_rptr;
8914 					ipha = (ipha_t *)mp->b_rptr;
8915 
8916 					ASSERT(sire != NULL);
8917 
8918 					dst = save_dst;
8919 					multirt_resolve_next = B_TRUE;
8920 					continue;
8921 				}
8922 
8923 				if (sire != NULL)
8924 					ire_refrele(sire);
8925 
8926 				/*
8927 				 * The response will come back in ip_wput
8928 				 * with db_type IRE_DB_TYPE.
8929 				 */
8930 				ipif_refrele(src_ipif);
8931 				ill_refrele(dst_ill);
8932 				return;
8933 			} else {
8934 				/* Prepare for cleanup */
8935 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8936 				    mp);
8937 				mp->b_cont = NULL;
8938 				freeb(mp); /* areq */
8939 				/*
8940 				 * this is an ire that is not added to the
8941 				 * cache. ire_freemblk will handle the release
8942 				 * of any resources associated with the ire.
8943 				 */
8944 				ire_delete(ire); /* ire_mp */
8945 				mp = saved_mp; /* pkt */
8946 				ire = NULL;
8947 				if (copy_mp != NULL) {
8948 					MULTIRT_DEBUG_UNTAG(copy_mp);
8949 					freemsg(copy_mp);
8950 					copy_mp = NULL;
8951 				}
8952 				break;
8953 			}
8954 		default:
8955 			break;
8956 		}
8957 	} while (multirt_resolve_next);
8958 
8959 	ip1dbg(("ip_newroute: dropped\n"));
8960 	/* Did this packet originate externally? */
8961 	if (mp->b_prev) {
8962 		mp->b_next = NULL;
8963 		mp->b_prev = NULL;
8964 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8965 	} else {
8966 		if (dst_ill != NULL) {
8967 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8968 		} else {
8969 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8970 		}
8971 	}
8972 	ASSERT(copy_mp == NULL);
8973 	MULTIRT_DEBUG_UNTAG(first_mp);
8974 	freemsg(first_mp);
8975 	if (ire != NULL)
8976 		ire_refrele(ire);
8977 	if (sire != NULL)
8978 		ire_refrele(sire);
8979 	if (src_ipif != NULL)
8980 		ipif_refrele(src_ipif);
8981 	if (dst_ill != NULL)
8982 		ill_refrele(dst_ill);
8983 	return;
8984 
8985 icmp_err_ret:
8986 	ip1dbg(("ip_newroute: no route\n"));
8987 	if (src_ipif != NULL)
8988 		ipif_refrele(src_ipif);
8989 	if (dst_ill != NULL)
8990 		ill_refrele(dst_ill);
8991 	if (sire != NULL)
8992 		ire_refrele(sire);
8993 	/* Did this packet originate externally? */
8994 	if (mp->b_prev) {
8995 		mp->b_next = NULL;
8996 		mp->b_prev = NULL;
8997 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8998 		q = WR(q);
8999 	} else {
9000 		/*
9001 		 * There is no outgoing ill, so just increment the
9002 		 * system MIB.
9003 		 */
9004 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
9005 		/*
9006 		 * Since ip_wput() isn't close to finished, we fill
9007 		 * in enough of the header for credible error reporting.
9008 		 */
9009 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
9010 			/* Failed */
9011 			MULTIRT_DEBUG_UNTAG(first_mp);
9012 			freemsg(first_mp);
9013 			if (ire != NULL)
9014 				ire_refrele(ire);
9015 			return;
9016 		}
9017 	}
9018 
9019 	/*
9020 	 * At this point we will have ire only if RTF_BLACKHOLE
9021 	 * or RTF_REJECT flags are set on the IRE. It will not
9022 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9023 	 */
9024 	if (ire != NULL) {
9025 		if (ire->ire_flags & RTF_BLACKHOLE) {
9026 			ire_refrele(ire);
9027 			MULTIRT_DEBUG_UNTAG(first_mp);
9028 			freemsg(first_mp);
9029 			return;
9030 		}
9031 		ire_refrele(ire);
9032 	}
9033 	if (ip_source_routed(ipha, ipst)) {
9034 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
9035 		    zoneid, ipst);
9036 		return;
9037 	}
9038 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9039 }
9040 
9041 ip_opt_info_t zero_info;
9042 
9043 /*
9044  * IPv4 -
9045  * ip_newroute_ipif is called by ip_wput_multicast and
9046  * ip_rput_forward_multicast whenever we need to send
9047  * out a packet to a destination address for which we do not have specific
9048  * routing information. It is used when the packet will be sent out
9049  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
9050  * socket option is set or icmp error message wants to go out on a particular
9051  * interface for a unicast packet.
9052  *
9053  * In most cases, the destination address is resolved thanks to the ipif
9054  * intrinsic resolver. However, there are some cases where the call to
9055  * ip_newroute_ipif must take into account the potential presence of
9056  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
9057  * that uses the interface. This is specified through flags,
9058  * which can be a combination of:
9059  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9060  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9061  *   and flags. Additionally, the packet source address has to be set to
9062  *   the specified address. The caller is thus expected to set this flag
9063  *   if the packet has no specific source address yet.
9064  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9065  *   flag, the resulting ire will inherit the flag. All unresolved routes
9066  *   to the destination must be explored in the same call to
9067  *   ip_newroute_ipif().
9068  */
9069 static void
9070 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9071     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9072 {
9073 	areq_t	*areq;
9074 	ire_t	*ire = NULL;
9075 	mblk_t	*res_mp;
9076 	ipaddr_t *addrp;
9077 	mblk_t *first_mp;
9078 	ire_t	*save_ire = NULL;
9079 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
9080 	ipif_t	*src_ipif = NULL;
9081 	ushort_t ire_marks = 0;
9082 	ill_t	*dst_ill = NULL;
9083 	boolean_t mctl_present;
9084 	ipsec_out_t *io;
9085 	ipha_t *ipha;
9086 	int	ihandle = 0;
9087 	mblk_t	*saved_mp;
9088 	ire_t   *fire = NULL;
9089 	mblk_t  *copy_mp = NULL;
9090 	boolean_t multirt_resolve_next;
9091 	boolean_t unspec_src;
9092 	ipaddr_t ipha_dst;
9093 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9094 
9095 	/*
9096 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9097 	 * here for uniformity
9098 	 */
9099 	ipif_refhold(ipif);
9100 
9101 	/*
9102 	 * This loop is run only once in most cases.
9103 	 * We loop to resolve further routes only when the destination
9104 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9105 	 */
9106 	do {
9107 		if (dst_ill != NULL) {
9108 			ill_refrele(dst_ill);
9109 			dst_ill = NULL;
9110 		}
9111 		if (src_ipif != NULL) {
9112 			ipif_refrele(src_ipif);
9113 			src_ipif = NULL;
9114 		}
9115 		multirt_resolve_next = B_FALSE;
9116 
9117 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9118 		    ipif->ipif_ill->ill_name));
9119 
9120 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9121 		if (mctl_present)
9122 			io = (ipsec_out_t *)first_mp->b_rptr;
9123 
9124 		ipha = (ipha_t *)mp->b_rptr;
9125 
9126 		/*
9127 		 * Save the packet destination address, we may need it after
9128 		 * the packet has been consumed.
9129 		 */
9130 		ipha_dst = ipha->ipha_dst;
9131 
9132 		/*
9133 		 * If the interface is a pt-pt interface we look for an
9134 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9135 		 * local_address and the pt-pt destination address. Otherwise
9136 		 * we just match the local address.
9137 		 * NOTE: dst could be different than ipha->ipha_dst in case
9138 		 * of sending igmp multicast packets over a point-to-point
9139 		 * connection.
9140 		 * Thus we must be careful enough to check ipha_dst to be a
9141 		 * multicast address, otherwise it will take xmit_if path for
9142 		 * multicast packets resulting into kernel stack overflow by
9143 		 * repeated calls to ip_newroute_ipif from ire_send().
9144 		 */
9145 		if (CLASSD(ipha_dst) &&
9146 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9147 			goto err_ret;
9148 		}
9149 
9150 		/*
9151 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9152 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9153 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9154 		 * propagate its flags to the new ire.
9155 		 */
9156 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9157 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9158 			ip2dbg(("ip_newroute_ipif: "
9159 			    "ipif_lookup_multi_ire("
9160 			    "ipif %p, dst %08x) = fire %p\n",
9161 			    (void *)ipif, ntohl(dst), (void *)fire));
9162 		}
9163 
9164 		if (mctl_present && io->ipsec_out_attach_if) {
9165 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9166 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9167 
9168 			/* Failure case frees things for us. */
9169 			if (attach_ill == NULL) {
9170 				ipif_refrele(ipif);
9171 				if (fire != NULL)
9172 					ire_refrele(fire);
9173 				return;
9174 			}
9175 
9176 			/*
9177 			 * Check if we need an ire that will not be
9178 			 * looked up by anybody else i.e. HIDDEN.
9179 			 */
9180 			if (ill_is_probeonly(attach_ill)) {
9181 				ire_marks = IRE_MARK_HIDDEN;
9182 			}
9183 			/*
9184 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9185 			 * case.
9186 			 */
9187 			dst_ill = ipif->ipif_ill;
9188 			/* attach_ill has been refheld by ip_grab_attach_ill */
9189 			ASSERT(dst_ill == attach_ill);
9190 		} else {
9191 			/*
9192 			 * If the interface belongs to an interface group,
9193 			 * make sure the next possible interface in the group
9194 			 * is used.  This encourages load spreading among
9195 			 * peers in an interface group.
9196 			 * Note: load spreading is disabled for RTF_MULTIRT
9197 			 * routes.
9198 			 */
9199 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9200 			    (fire->ire_flags & RTF_MULTIRT)) {
9201 				/*
9202 				 * Don't perform outbound load spreading
9203 				 * in the case of an RTF_MULTIRT issued route,
9204 				 * we actually typically want to replicate
9205 				 * outgoing packets through particular
9206 				 * interfaces.
9207 				 */
9208 				dst_ill = ipif->ipif_ill;
9209 				ill_refhold(dst_ill);
9210 			} else {
9211 				dst_ill = ip_newroute_get_dst_ill(
9212 				    ipif->ipif_ill);
9213 			}
9214 			if (dst_ill == NULL) {
9215 				if (ip_debug > 2) {
9216 					pr_addr_dbg("ip_newroute_ipif: "
9217 					    "no dst ill for dst %s\n",
9218 					    AF_INET, &dst);
9219 				}
9220 				goto err_ret;
9221 			}
9222 		}
9223 
9224 		/*
9225 		 * Pick a source address preferring non-deprecated ones.
9226 		 * Unlike ip_newroute, we don't do any source address
9227 		 * selection here since for multicast it really does not help
9228 		 * in inbound load spreading as in the unicast case.
9229 		 */
9230 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9231 		    (fire->ire_flags & RTF_SETSRC)) {
9232 			/*
9233 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9234 			 * on that interface. This ire has RTF_SETSRC flag, so
9235 			 * the source address of the packet must be changed.
9236 			 * Check that the ipif matching the requested source
9237 			 * address still exists.
9238 			 */
9239 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9240 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9241 		}
9242 
9243 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9244 
9245 		if (((!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9246 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9247 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9248 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9249 		    (src_ipif == NULL) &&
9250 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9251 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9252 			if (src_ipif == NULL) {
9253 				if (ip_debug > 2) {
9254 					/* ip1dbg */
9255 					pr_addr_dbg("ip_newroute_ipif: "
9256 					    "no src for dst %s",
9257 					    AF_INET, &dst);
9258 				}
9259 				ip1dbg((" through interface %s\n",
9260 				    dst_ill->ill_name));
9261 				goto err_ret;
9262 			}
9263 			ipif_refrele(ipif);
9264 			ipif = src_ipif;
9265 			ipif_refhold(ipif);
9266 		}
9267 		if (src_ipif == NULL) {
9268 			src_ipif = ipif;
9269 			ipif_refhold(src_ipif);
9270 		}
9271 
9272 		/*
9273 		 * Assign a source address while we have the conn.
9274 		 * We can't have ip_wput_ire pick a source address when the
9275 		 * packet returns from arp since conn_unspec_src might be set
9276 		 * and we lose the conn when going through arp.
9277 		 */
9278 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9279 			ipha->ipha_src = src_ipif->ipif_src_addr;
9280 
9281 		/*
9282 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9283 		 * that the outgoing interface does not have an interface ire.
9284 		 */
9285 		if (CLASSD(ipha_dst) && (connp == NULL ||
9286 		    connp->conn_outgoing_ill == NULL) &&
9287 		    infop->ip_opt_ill_index == 0) {
9288 			/* ipif_to_ire returns an held ire */
9289 			ire = ipif_to_ire(ipif);
9290 			if (ire == NULL)
9291 				goto err_ret;
9292 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9293 				goto err_ret;
9294 			/*
9295 			 * ihandle is needed when the ire is added to
9296 			 * cache table.
9297 			 */
9298 			save_ire = ire;
9299 			ihandle = save_ire->ire_ihandle;
9300 
9301 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9302 			    "flags %04x\n",
9303 			    (void *)ire, (void *)ipif, flags));
9304 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9305 			    (fire->ire_flags & RTF_MULTIRT)) {
9306 				/*
9307 				 * As requested by flags, an IRE_OFFSUBNET was
9308 				 * looked up on that interface. This ire has
9309 				 * RTF_MULTIRT flag, so the resolution loop will
9310 				 * be re-entered to resolve additional routes on
9311 				 * other interfaces. For that purpose, a copy of
9312 				 * the packet is performed at this point.
9313 				 */
9314 				fire->ire_last_used_time = lbolt;
9315 				copy_mp = copymsg(first_mp);
9316 				if (copy_mp) {
9317 					MULTIRT_DEBUG_TAG(copy_mp);
9318 				}
9319 			}
9320 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9321 			    (fire->ire_flags & RTF_SETSRC)) {
9322 				/*
9323 				 * As requested by flags, an IRE_OFFSUBET was
9324 				 * looked up on that interface. This ire has
9325 				 * RTF_SETSRC flag, so the source address of the
9326 				 * packet must be changed.
9327 				 */
9328 				ipha->ipha_src = fire->ire_src_addr;
9329 			}
9330 		} else {
9331 			ASSERT((connp == NULL) ||
9332 			    (connp->conn_outgoing_ill != NULL) ||
9333 			    (connp->conn_dontroute) ||
9334 			    infop->ip_opt_ill_index != 0);
9335 			/*
9336 			 * The only ways we can come here are:
9337 			 * 1) IP_BOUND_IF socket option is set
9338 			 * 2) SO_DONTROUTE socket option is set
9339 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9340 			 * In all cases, the new ire will not be added
9341 			 * into cache table.
9342 			 */
9343 			ire_marks |= IRE_MARK_NOADD;
9344 		}
9345 
9346 		switch (ipif->ipif_net_type) {
9347 		case IRE_IF_NORESOLVER: {
9348 			/* We have what we need to build an IRE_CACHE. */
9349 
9350 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9351 			    (dst_ill->ill_resolver_mp == NULL)) {
9352 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9353 				    "for IRE_IF_NORESOLVER ire %p has "
9354 				    "no ill_resolver_mp\n",
9355 				    (void *)dst_ill, (void *)ire));
9356 				break;
9357 			}
9358 
9359 			/*
9360 			 * The new ire inherits the IRE_OFFSUBNET flags
9361 			 * and source address, if this was requested.
9362 			 */
9363 			ire = ire_create(
9364 			    (uchar_t *)&dst,		/* dest address */
9365 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9366 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9367 			    NULL,			/* gateway address */
9368 			    &ipif->ipif_mtu,
9369 			    NULL,			/* no src nce */
9370 			    dst_ill->ill_rq,		/* recv-from queue */
9371 			    dst_ill->ill_wq,		/* send-to queue */
9372 			    IRE_CACHE,
9373 			    src_ipif,
9374 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9375 			    (fire != NULL) ?		/* Parent handle */
9376 			    fire->ire_phandle : 0,
9377 			    ihandle,			/* Interface handle */
9378 			    (fire != NULL) ?
9379 			    (fire->ire_flags &
9380 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9381 			    (save_ire == NULL ? &ire_uinfo_null :
9382 			    &save_ire->ire_uinfo),
9383 			    NULL,
9384 			    NULL,
9385 			    ipst);
9386 
9387 			if (ire == NULL) {
9388 				if (save_ire != NULL)
9389 					ire_refrele(save_ire);
9390 				break;
9391 			}
9392 
9393 			ire->ire_marks |= ire_marks;
9394 
9395 			/*
9396 			 * If IRE_MARK_NOADD is set then we need to convert
9397 			 * the max_fragp to a useable value now. This is
9398 			 * normally done in ire_add_v[46]. We also need to
9399 			 * associate the ire with an nce (normally would be
9400 			 * done in ip_wput_nondata()).
9401 			 *
9402 			 * Note that IRE_MARK_NOADD packets created here
9403 			 * do not have a non-null ire_mp pointer. The null
9404 			 * value of ire_bucket indicates that they were
9405 			 * never added.
9406 			 */
9407 			if (ire->ire_marks & IRE_MARK_NOADD) {
9408 				uint_t  max_frag;
9409 
9410 				max_frag = *ire->ire_max_fragp;
9411 				ire->ire_max_fragp = NULL;
9412 				ire->ire_max_frag = max_frag;
9413 
9414 				if ((ire->ire_nce = ndp_lookup_v4(
9415 				    ire_to_ill(ire),
9416 				    (ire->ire_gateway_addr != INADDR_ANY ?
9417 				    &ire->ire_gateway_addr : &ire->ire_addr),
9418 				    B_FALSE)) == NULL) {
9419 					if (save_ire != NULL)
9420 						ire_refrele(save_ire);
9421 					break;
9422 				}
9423 				ASSERT(ire->ire_nce->nce_state ==
9424 				    ND_REACHABLE);
9425 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9426 			}
9427 
9428 			/* Prevent save_ire from getting deleted */
9429 			if (save_ire != NULL) {
9430 				IRB_REFHOLD(save_ire->ire_bucket);
9431 				/* Has it been removed already ? */
9432 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9433 					IRB_REFRELE(save_ire->ire_bucket);
9434 					ire_refrele(save_ire);
9435 					break;
9436 				}
9437 			}
9438 
9439 			ire_add_then_send(q, ire, first_mp);
9440 
9441 			/* Assert that save_ire is not deleted yet. */
9442 			if (save_ire != NULL) {
9443 				ASSERT(save_ire->ire_ptpn != NULL);
9444 				IRB_REFRELE(save_ire->ire_bucket);
9445 				ire_refrele(save_ire);
9446 				save_ire = NULL;
9447 			}
9448 			if (fire != NULL) {
9449 				ire_refrele(fire);
9450 				fire = NULL;
9451 			}
9452 
9453 			/*
9454 			 * the resolution loop is re-entered if this
9455 			 * was requested through flags and if we
9456 			 * actually are in a multirouting case.
9457 			 */
9458 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9459 				boolean_t need_resolve =
9460 				    ire_multirt_need_resolve(ipha_dst,
9461 				    MBLK_GETLABEL(copy_mp), ipst);
9462 				if (!need_resolve) {
9463 					MULTIRT_DEBUG_UNTAG(copy_mp);
9464 					freemsg(copy_mp);
9465 					copy_mp = NULL;
9466 				} else {
9467 					/*
9468 					 * ipif_lookup_group() calls
9469 					 * ire_lookup_multi() that uses
9470 					 * ire_ftable_lookup() to find
9471 					 * an IRE_INTERFACE for the group.
9472 					 * In the multirt case,
9473 					 * ire_lookup_multi() then invokes
9474 					 * ire_multirt_lookup() to find
9475 					 * the next resolvable ire.
9476 					 * As a result, we obtain an new
9477 					 * interface, derived from the
9478 					 * next ire.
9479 					 */
9480 					ipif_refrele(ipif);
9481 					ipif = ipif_lookup_group(ipha_dst,
9482 					    zoneid, ipst);
9483 					ip2dbg(("ip_newroute_ipif: "
9484 					    "multirt dst %08x, ipif %p\n",
9485 					    htonl(dst), (void *)ipif));
9486 					if (ipif != NULL) {
9487 						mp = copy_mp;
9488 						copy_mp = NULL;
9489 						multirt_resolve_next = B_TRUE;
9490 						continue;
9491 					} else {
9492 						freemsg(copy_mp);
9493 					}
9494 				}
9495 			}
9496 			if (ipif != NULL)
9497 				ipif_refrele(ipif);
9498 			ill_refrele(dst_ill);
9499 			ipif_refrele(src_ipif);
9500 			return;
9501 		}
9502 		case IRE_IF_RESOLVER:
9503 			/*
9504 			 * We can't build an IRE_CACHE yet, but at least
9505 			 * we found a resolver that can help.
9506 			 */
9507 			res_mp = dst_ill->ill_resolver_mp;
9508 			if (!OK_RESOLVER_MP(res_mp))
9509 				break;
9510 
9511 			/*
9512 			 * We obtain a partial IRE_CACHE which we will pass
9513 			 * along with the resolver query.  When the response
9514 			 * comes back it will be there ready for us to add.
9515 			 * The new ire inherits the IRE_OFFSUBNET flags
9516 			 * and source address, if this was requested.
9517 			 * The ire_max_frag is atomically set under the
9518 			 * irebucket lock in ire_add_v[46]. Only in the
9519 			 * case of IRE_MARK_NOADD, we set it here itself.
9520 			 */
9521 			ire = ire_create_mp(
9522 			    (uchar_t *)&dst,		/* dest address */
9523 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9524 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9525 			    NULL,			/* gateway address */
9526 			    (ire_marks & IRE_MARK_NOADD) ?
9527 			    ipif->ipif_mtu : 0,		/* max_frag */
9528 			    NULL,			/* no src nce */
9529 			    dst_ill->ill_rq,		/* recv-from queue */
9530 			    dst_ill->ill_wq,		/* send-to queue */
9531 			    IRE_CACHE,
9532 			    src_ipif,
9533 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9534 			    (fire != NULL) ?		/* Parent handle */
9535 			    fire->ire_phandle : 0,
9536 			    ihandle,			/* Interface handle */
9537 			    (fire != NULL) ?		/* flags if any */
9538 			    (fire->ire_flags &
9539 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9540 			    (save_ire == NULL ? &ire_uinfo_null :
9541 			    &save_ire->ire_uinfo),
9542 			    NULL,
9543 			    NULL,
9544 			    ipst);
9545 
9546 			if (save_ire != NULL) {
9547 				ire_refrele(save_ire);
9548 				save_ire = NULL;
9549 			}
9550 			if (ire == NULL)
9551 				break;
9552 
9553 			ire->ire_marks |= ire_marks;
9554 			/*
9555 			 * Construct message chain for the resolver of the
9556 			 * form:
9557 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9558 			 *
9559 			 * NOTE : ire will be added later when the response
9560 			 * comes back from ARP. If the response does not
9561 			 * come back, ARP frees the packet. For this reason,
9562 			 * we can't REFHOLD the bucket of save_ire to prevent
9563 			 * deletions. We may not be able to REFRELE the
9564 			 * bucket if the response never comes back.
9565 			 * Thus, before adding the ire, ire_add_v4 will make
9566 			 * sure that the interface route does not get deleted.
9567 			 * This is the only case unlike ip_newroute_v6,
9568 			 * ip_newroute_ipif_v6 where we can always prevent
9569 			 * deletions because ire_add_then_send is called after
9570 			 * creating the IRE.
9571 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9572 			 * does not add this IRE into the IRE CACHE.
9573 			 */
9574 			ASSERT(ire->ire_mp != NULL);
9575 			ire->ire_mp->b_cont = first_mp;
9576 			/* Have saved_mp handy, for cleanup if canput fails */
9577 			saved_mp = mp;
9578 			mp = copyb(res_mp);
9579 			if (mp == NULL) {
9580 				/* Prepare for cleanup */
9581 				mp = saved_mp; /* pkt */
9582 				ire_delete(ire); /* ire_mp */
9583 				ire = NULL;
9584 				if (copy_mp != NULL) {
9585 					MULTIRT_DEBUG_UNTAG(copy_mp);
9586 					freemsg(copy_mp);
9587 					copy_mp = NULL;
9588 				}
9589 				break;
9590 			}
9591 			linkb(mp, ire->ire_mp);
9592 
9593 			/*
9594 			 * Fill in the source and dest addrs for the resolver.
9595 			 * NOTE: this depends on memory layouts imposed by
9596 			 * ill_init().
9597 			 */
9598 			areq = (areq_t *)mp->b_rptr;
9599 			addrp = (ipaddr_t *)((char *)areq +
9600 			    areq->areq_sender_addr_offset);
9601 			*addrp = ire->ire_src_addr;
9602 			addrp = (ipaddr_t *)((char *)areq +
9603 			    areq->areq_target_addr_offset);
9604 			*addrp = dst;
9605 			/* Up to the resolver. */
9606 			if (canputnext(dst_ill->ill_rq) &&
9607 			    !(dst_ill->ill_arp_closing)) {
9608 				putnext(dst_ill->ill_rq, mp);
9609 				/*
9610 				 * The response will come back in ip_wput
9611 				 * with db_type IRE_DB_TYPE.
9612 				 */
9613 			} else {
9614 				mp->b_cont = NULL;
9615 				freeb(mp); /* areq */
9616 				ire_delete(ire); /* ire_mp */
9617 				saved_mp->b_next = NULL;
9618 				saved_mp->b_prev = NULL;
9619 				freemsg(first_mp); /* pkt */
9620 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9621 			}
9622 
9623 			if (fire != NULL) {
9624 				ire_refrele(fire);
9625 				fire = NULL;
9626 			}
9627 
9628 
9629 			/*
9630 			 * The resolution loop is re-entered if this was
9631 			 * requested through flags and we actually are
9632 			 * in a multirouting case.
9633 			 */
9634 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9635 				boolean_t need_resolve =
9636 				    ire_multirt_need_resolve(ipha_dst,
9637 				    MBLK_GETLABEL(copy_mp), ipst);
9638 				if (!need_resolve) {
9639 					MULTIRT_DEBUG_UNTAG(copy_mp);
9640 					freemsg(copy_mp);
9641 					copy_mp = NULL;
9642 				} else {
9643 					/*
9644 					 * ipif_lookup_group() calls
9645 					 * ire_lookup_multi() that uses
9646 					 * ire_ftable_lookup() to find
9647 					 * an IRE_INTERFACE for the group.
9648 					 * In the multirt case,
9649 					 * ire_lookup_multi() then invokes
9650 					 * ire_multirt_lookup() to find
9651 					 * the next resolvable ire.
9652 					 * As a result, we obtain an new
9653 					 * interface, derived from the
9654 					 * next ire.
9655 					 */
9656 					ipif_refrele(ipif);
9657 					ipif = ipif_lookup_group(ipha_dst,
9658 					    zoneid, ipst);
9659 					if (ipif != NULL) {
9660 						mp = copy_mp;
9661 						copy_mp = NULL;
9662 						multirt_resolve_next = B_TRUE;
9663 						continue;
9664 					} else {
9665 						freemsg(copy_mp);
9666 					}
9667 				}
9668 			}
9669 			if (ipif != NULL)
9670 				ipif_refrele(ipif);
9671 			ill_refrele(dst_ill);
9672 			ipif_refrele(src_ipif);
9673 			return;
9674 		default:
9675 			break;
9676 		}
9677 	} while (multirt_resolve_next);
9678 
9679 err_ret:
9680 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9681 	if (fire != NULL)
9682 		ire_refrele(fire);
9683 	ipif_refrele(ipif);
9684 	/* Did this packet originate externally? */
9685 	if (dst_ill != NULL)
9686 		ill_refrele(dst_ill);
9687 	if (src_ipif != NULL)
9688 		ipif_refrele(src_ipif);
9689 	if (mp->b_prev || mp->b_next) {
9690 		mp->b_next = NULL;
9691 		mp->b_prev = NULL;
9692 	} else {
9693 		/*
9694 		 * Since ip_wput() isn't close to finished, we fill
9695 		 * in enough of the header for credible error reporting.
9696 		 */
9697 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9698 			/* Failed */
9699 			freemsg(first_mp);
9700 			if (ire != NULL)
9701 				ire_refrele(ire);
9702 			return;
9703 		}
9704 	}
9705 	/*
9706 	 * At this point we will have ire only if RTF_BLACKHOLE
9707 	 * or RTF_REJECT flags are set on the IRE. It will not
9708 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9709 	 */
9710 	if (ire != NULL) {
9711 		if (ire->ire_flags & RTF_BLACKHOLE) {
9712 			ire_refrele(ire);
9713 			freemsg(first_mp);
9714 			return;
9715 		}
9716 		ire_refrele(ire);
9717 	}
9718 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9719 }
9720 
9721 /* Name/Value Table Lookup Routine */
9722 char *
9723 ip_nv_lookup(nv_t *nv, int value)
9724 {
9725 	if (!nv)
9726 		return (NULL);
9727 	for (; nv->nv_name; nv++) {
9728 		if (nv->nv_value == value)
9729 			return (nv->nv_name);
9730 	}
9731 	return ("unknown");
9732 }
9733 
9734 /*
9735  * This is a module open, i.e. this is a control stream for access
9736  * to a DLPI device.  We allocate an ill_t as the instance data in
9737  * this case.
9738  */
9739 int
9740 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9741 {
9742 	ill_t	*ill;
9743 	int	err;
9744 	zoneid_t zoneid;
9745 	netstack_t *ns;
9746 	ip_stack_t *ipst;
9747 
9748 	/*
9749 	 * Prevent unprivileged processes from pushing IP so that
9750 	 * they can't send raw IP.
9751 	 */
9752 	if (secpolicy_net_rawaccess(credp) != 0)
9753 		return (EPERM);
9754 
9755 	ns = netstack_find_by_cred(credp);
9756 	ASSERT(ns != NULL);
9757 	ipst = ns->netstack_ip;
9758 	ASSERT(ipst != NULL);
9759 
9760 	/*
9761 	 * For exclusive stacks we set the zoneid to zero
9762 	 * to make IP operate as if in the global zone.
9763 	 */
9764 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9765 		zoneid = GLOBAL_ZONEID;
9766 	else
9767 		zoneid = crgetzoneid(credp);
9768 
9769 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9770 	q->q_ptr = WR(q)->q_ptr = ill;
9771 	ill->ill_ipst = ipst;
9772 	ill->ill_zoneid = zoneid;
9773 
9774 	/*
9775 	 * ill_init initializes the ill fields and then sends down
9776 	 * down a DL_INFO_REQ after calling qprocson.
9777 	 */
9778 	err = ill_init(q, ill);
9779 	if (err != 0) {
9780 		mi_free(ill);
9781 		netstack_rele(ipst->ips_netstack);
9782 		q->q_ptr = NULL;
9783 		WR(q)->q_ptr = NULL;
9784 		return (err);
9785 	}
9786 
9787 	/* ill_init initializes the ipsq marking this thread as writer */
9788 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
9789 	/* Wait for the DL_INFO_ACK */
9790 	mutex_enter(&ill->ill_lock);
9791 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9792 		/*
9793 		 * Return value of 0 indicates a pending signal.
9794 		 */
9795 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9796 		if (err == 0) {
9797 			mutex_exit(&ill->ill_lock);
9798 			(void) ip_close(q, 0);
9799 			return (EINTR);
9800 		}
9801 	}
9802 	mutex_exit(&ill->ill_lock);
9803 
9804 	/*
9805 	 * ip_rput_other could have set an error  in ill_error on
9806 	 * receipt of M_ERROR.
9807 	 */
9808 
9809 	err = ill->ill_error;
9810 	if (err != 0) {
9811 		(void) ip_close(q, 0);
9812 		return (err);
9813 	}
9814 
9815 	ill->ill_credp = credp;
9816 	crhold(credp);
9817 
9818 	mutex_enter(&ipst->ips_ip_mi_lock);
9819 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9820 	    credp);
9821 	mutex_exit(&ipst->ips_ip_mi_lock);
9822 	if (err) {
9823 		(void) ip_close(q, 0);
9824 		return (err);
9825 	}
9826 	return (0);
9827 }
9828 
9829 /* For /dev/ip aka AF_INET open */
9830 int
9831 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9832 {
9833 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9834 }
9835 
9836 /* For /dev/ip6 aka AF_INET6 open */
9837 int
9838 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9839 {
9840 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9841 }
9842 
9843 /* IP open routine. */
9844 int
9845 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9846     boolean_t isv6)
9847 {
9848 	conn_t 		*connp;
9849 	major_t		maj;
9850 	zoneid_t	zoneid;
9851 	netstack_t	*ns;
9852 	ip_stack_t	*ipst;
9853 
9854 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9855 
9856 	/* Allow reopen. */
9857 	if (q->q_ptr != NULL)
9858 		return (0);
9859 
9860 	if (sflag & MODOPEN) {
9861 		/* This is a module open */
9862 		return (ip_modopen(q, devp, flag, sflag, credp));
9863 	}
9864 
9865 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
9866 		/*
9867 		 * Non streams based socket looking for a stream
9868 		 * to access IP
9869 		 */
9870 		return (ip_helper_stream_setup(q, devp, flag, sflag,
9871 		    credp, isv6));
9872 	}
9873 
9874 	ns = netstack_find_by_cred(credp);
9875 	ASSERT(ns != NULL);
9876 	ipst = ns->netstack_ip;
9877 	ASSERT(ipst != NULL);
9878 
9879 	/*
9880 	 * For exclusive stacks we set the zoneid to zero
9881 	 * to make IP operate as if in the global zone.
9882 	 */
9883 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9884 		zoneid = GLOBAL_ZONEID;
9885 	else
9886 		zoneid = crgetzoneid(credp);
9887 
9888 	/*
9889 	 * We are opening as a device. This is an IP client stream, and we
9890 	 * allocate an conn_t as the instance data.
9891 	 */
9892 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9893 
9894 	/*
9895 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9896 	 * done by netstack_find_by_cred()
9897 	 */
9898 	netstack_rele(ipst->ips_netstack);
9899 
9900 	connp->conn_zoneid = zoneid;
9901 	connp->conn_sqp = NULL;
9902 	connp->conn_initial_sqp = NULL;
9903 	connp->conn_final_sqp = NULL;
9904 
9905 	connp->conn_upq = q;
9906 	q->q_ptr = WR(q)->q_ptr = connp;
9907 
9908 	if (flag & SO_SOCKSTR)
9909 		connp->conn_flags |= IPCL_SOCKET;
9910 
9911 	/* Minor tells us which /dev entry was opened */
9912 	if (isv6) {
9913 		connp->conn_flags |= IPCL_ISV6;
9914 		connp->conn_af_isv6 = B_TRUE;
9915 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9916 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9917 	} else {
9918 		connp->conn_af_isv6 = B_FALSE;
9919 		connp->conn_pkt_isv6 = B_FALSE;
9920 	}
9921 
9922 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9923 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9924 		connp->conn_minor_arena = ip_minor_arena_la;
9925 	} else {
9926 		/*
9927 		 * Either minor numbers in the large arena were exhausted
9928 		 * or a non socket application is doing the open.
9929 		 * Try to allocate from the small arena.
9930 		 */
9931 		if ((connp->conn_dev =
9932 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9933 			/* CONN_DEC_REF takes care of netstack_rele() */
9934 			q->q_ptr = WR(q)->q_ptr = NULL;
9935 			CONN_DEC_REF(connp);
9936 			return (EBUSY);
9937 		}
9938 		connp->conn_minor_arena = ip_minor_arena_sa;
9939 	}
9940 
9941 	maj = getemajor(*devp);
9942 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9943 
9944 	/*
9945 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9946 	 */
9947 	connp->conn_cred = credp;
9948 
9949 	/*
9950 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9951 	 */
9952 	connp->conn_recv = ip_conn_input;
9953 
9954 	crhold(connp->conn_cred);
9955 
9956 	/*
9957 	 * If the caller has the process-wide flag set, then default to MAC
9958 	 * exempt mode.  This allows read-down to unlabeled hosts.
9959 	 */
9960 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9961 		connp->conn_mac_exempt = B_TRUE;
9962 
9963 	connp->conn_rq = q;
9964 	connp->conn_wq = WR(q);
9965 
9966 	/* Non-zero default values */
9967 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9968 
9969 	/*
9970 	 * Make the conn globally visible to walkers
9971 	 */
9972 	ASSERT(connp->conn_ref == 1);
9973 	mutex_enter(&connp->conn_lock);
9974 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9975 	mutex_exit(&connp->conn_lock);
9976 
9977 	qprocson(q);
9978 
9979 	return (0);
9980 }
9981 
9982 /*
9983  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9984  * Note that there is no race since either ip_output function works - it
9985  * is just an optimization to enter the best ip_output routine directly.
9986  */
9987 void
9988 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9989     ip_stack_t *ipst)
9990 {
9991 	if (isv6)  {
9992 		if (bump_mib) {
9993 			BUMP_MIB(&ipst->ips_ip6_mib,
9994 			    ipIfStatsOutSwitchIPVersion);
9995 		}
9996 		connp->conn_send = ip_output_v6;
9997 		connp->conn_pkt_isv6 = B_TRUE;
9998 	} else {
9999 		if (bump_mib) {
10000 			BUMP_MIB(&ipst->ips_ip_mib,
10001 			    ipIfStatsOutSwitchIPVersion);
10002 		}
10003 		connp->conn_send = ip_output;
10004 		connp->conn_pkt_isv6 = B_FALSE;
10005 	}
10006 
10007 }
10008 
10009 /*
10010  * See if IPsec needs loading because of the options in mp.
10011  */
10012 static boolean_t
10013 ipsec_opt_present(mblk_t *mp)
10014 {
10015 	uint8_t *optcp, *next_optcp, *opt_endcp;
10016 	struct opthdr *opt;
10017 	struct T_opthdr *topt;
10018 	int opthdr_len;
10019 	t_uscalar_t optname, optlevel;
10020 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
10021 	ipsec_req_t *ipsr;
10022 
10023 	/*
10024 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
10025 	 * return TRUE.
10026 	 */
10027 
10028 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
10029 	opt_endcp = optcp + tor->OPT_length;
10030 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
10031 		opthdr_len = sizeof (struct T_opthdr);
10032 	} else {		/* O_OPTMGMT_REQ */
10033 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
10034 		opthdr_len = sizeof (struct opthdr);
10035 	}
10036 	for (; optcp < opt_endcp; optcp = next_optcp) {
10037 		if (optcp + opthdr_len > opt_endcp)
10038 			return (B_FALSE);	/* Not enough option header. */
10039 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
10040 			topt = (struct T_opthdr *)optcp;
10041 			optlevel = topt->level;
10042 			optname = topt->name;
10043 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
10044 		} else {
10045 			opt = (struct opthdr *)optcp;
10046 			optlevel = opt->level;
10047 			optname = opt->name;
10048 			next_optcp = optcp + opthdr_len +
10049 			    _TPI_ALIGN_OPT(opt->len);
10050 		}
10051 		if ((next_optcp < optcp) || /* wraparound pointer space */
10052 		    ((next_optcp >= opt_endcp) && /* last option bad len */
10053 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
10054 			return (B_FALSE); /* bad option buffer */
10055 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
10056 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
10057 			/*
10058 			 * Check to see if it's an all-bypass or all-zeroes
10059 			 * IPsec request.  Don't bother loading IPsec if
10060 			 * the socket doesn't want to use it.  (A good example
10061 			 * is a bypass request.)
10062 			 *
10063 			 * Basically, if any of the non-NEVER bits are set,
10064 			 * load IPsec.
10065 			 */
10066 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
10067 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
10068 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
10069 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
10070 			    != 0)
10071 				return (B_TRUE);
10072 		}
10073 	}
10074 	return (B_FALSE);
10075 }
10076 
10077 /*
10078  * If conn is is waiting for ipsec to finish loading, kick it.
10079  */
10080 /* ARGSUSED */
10081 static void
10082 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
10083 {
10084 	t_scalar_t	optreq_prim;
10085 	mblk_t		*mp;
10086 	cred_t		*cr;
10087 	int		err = 0;
10088 
10089 	/*
10090 	 * This function is called, after ipsec loading is complete.
10091 	 * Since IP checks exclusively and atomically (i.e it prevents
10092 	 * ipsec load from completing until ip_optcom_req completes)
10093 	 * whether ipsec load is complete, there cannot be a race with IP
10094 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10095 	 */
10096 	mutex_enter(&connp->conn_lock);
10097 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10098 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10099 		mp = connp->conn_ipsec_opt_mp;
10100 		connp->conn_ipsec_opt_mp = NULL;
10101 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10102 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10103 		mutex_exit(&connp->conn_lock);
10104 
10105 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10106 
10107 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10108 		if (optreq_prim == T_OPTMGMT_REQ) {
10109 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10110 			    &ip_opt_obj, B_FALSE);
10111 		} else {
10112 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10113 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10114 			    &ip_opt_obj, B_FALSE);
10115 		}
10116 		if (err != EINPROGRESS)
10117 			CONN_OPER_PENDING_DONE(connp);
10118 		return;
10119 	}
10120 	mutex_exit(&connp->conn_lock);
10121 }
10122 
10123 /*
10124  * Called from the ipsec_loader thread, outside any perimeter, to tell
10125  * ip qenable any of the queues waiting for the ipsec loader to
10126  * complete.
10127  */
10128 void
10129 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10130 {
10131 	netstack_t *ns = ipss->ipsec_netstack;
10132 
10133 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10134 }
10135 
10136 /*
10137  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10138  * determines the grp on which it has to become exclusive, queues the mp
10139  * and sq draining restarts the optmgmt
10140  */
10141 static boolean_t
10142 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10143 {
10144 	conn_t *connp = Q_TO_CONN(q);
10145 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10146 
10147 	/*
10148 	 * Take IPsec requests and treat them special.
10149 	 */
10150 	if (ipsec_opt_present(mp)) {
10151 		/* First check if IPsec is loaded. */
10152 		mutex_enter(&ipss->ipsec_loader_lock);
10153 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10154 			mutex_exit(&ipss->ipsec_loader_lock);
10155 			return (B_FALSE);
10156 		}
10157 		mutex_enter(&connp->conn_lock);
10158 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10159 
10160 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10161 		connp->conn_ipsec_opt_mp = mp;
10162 		mutex_exit(&connp->conn_lock);
10163 		mutex_exit(&ipss->ipsec_loader_lock);
10164 
10165 		ipsec_loader_loadnow(ipss);
10166 		return (B_TRUE);
10167 	}
10168 	return (B_FALSE);
10169 }
10170 
10171 /*
10172  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10173  * all of them are copied to the conn_t. If the req is "zero", the policy is
10174  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10175  * fields.
10176  * We keep only the latest setting of the policy and thus policy setting
10177  * is not incremental/cumulative.
10178  *
10179  * Requests to set policies with multiple alternative actions will
10180  * go through a different API.
10181  */
10182 int
10183 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10184 {
10185 	uint_t ah_req = 0;
10186 	uint_t esp_req = 0;
10187 	uint_t se_req = 0;
10188 	ipsec_selkey_t sel;
10189 	ipsec_act_t *actp = NULL;
10190 	uint_t nact;
10191 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10192 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10193 	ipsec_policy_root_t *pr;
10194 	ipsec_policy_head_t *ph;
10195 	int fam;
10196 	boolean_t is_pol_reset;
10197 	int error = 0;
10198 	netstack_t	*ns = connp->conn_netstack;
10199 	ip_stack_t	*ipst = ns->netstack_ip;
10200 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10201 
10202 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10203 
10204 	/*
10205 	 * The IP_SEC_OPT option does not allow variable length parameters,
10206 	 * hence a request cannot be NULL.
10207 	 */
10208 	if (req == NULL)
10209 		return (EINVAL);
10210 
10211 	ah_req = req->ipsr_ah_req;
10212 	esp_req = req->ipsr_esp_req;
10213 	se_req = req->ipsr_self_encap_req;
10214 
10215 	/* Don't allow setting self-encap without one or more of AH/ESP. */
10216 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
10217 		return (EINVAL);
10218 
10219 	/*
10220 	 * Are we dealing with a request to reset the policy (i.e.
10221 	 * zero requests).
10222 	 */
10223 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10224 	    (esp_req & REQ_MASK) == 0 &&
10225 	    (se_req & REQ_MASK) == 0);
10226 
10227 	if (!is_pol_reset) {
10228 		/*
10229 		 * If we couldn't load IPsec, fail with "protocol
10230 		 * not supported".
10231 		 * IPsec may not have been loaded for a request with zero
10232 		 * policies, so we don't fail in this case.
10233 		 */
10234 		mutex_enter(&ipss->ipsec_loader_lock);
10235 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10236 			mutex_exit(&ipss->ipsec_loader_lock);
10237 			return (EPROTONOSUPPORT);
10238 		}
10239 		mutex_exit(&ipss->ipsec_loader_lock);
10240 
10241 		/*
10242 		 * Test for valid requests. Invalid algorithms
10243 		 * need to be tested by IPsec code because new
10244 		 * algorithms can be added dynamically.
10245 		 */
10246 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10247 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10248 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10249 			return (EINVAL);
10250 		}
10251 
10252 		/*
10253 		 * Only privileged users can issue these
10254 		 * requests.
10255 		 */
10256 		if (((ah_req & IPSEC_PREF_NEVER) ||
10257 		    (esp_req & IPSEC_PREF_NEVER) ||
10258 		    (se_req & IPSEC_PREF_NEVER)) &&
10259 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10260 			return (EPERM);
10261 		}
10262 
10263 		/*
10264 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10265 		 * are mutually exclusive.
10266 		 */
10267 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10268 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10269 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10270 			/* Both of them are set */
10271 			return (EINVAL);
10272 		}
10273 	}
10274 
10275 	mutex_enter(&connp->conn_lock);
10276 
10277 	/*
10278 	 * If we have already cached policies in ip_bind_connected*(), don't
10279 	 * let them change now. We cache policies for connections
10280 	 * whose src,dst [addr, port] is known.
10281 	 */
10282 	if (connp->conn_policy_cached) {
10283 		mutex_exit(&connp->conn_lock);
10284 		return (EINVAL);
10285 	}
10286 
10287 	/*
10288 	 * We have a zero policies, reset the connection policy if already
10289 	 * set. This will cause the connection to inherit the
10290 	 * global policy, if any.
10291 	 */
10292 	if (is_pol_reset) {
10293 		if (connp->conn_policy != NULL) {
10294 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10295 			connp->conn_policy = NULL;
10296 		}
10297 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10298 		connp->conn_in_enforce_policy = B_FALSE;
10299 		connp->conn_out_enforce_policy = B_FALSE;
10300 		mutex_exit(&connp->conn_lock);
10301 		return (0);
10302 	}
10303 
10304 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10305 	    ipst->ips_netstack);
10306 	if (ph == NULL)
10307 		goto enomem;
10308 
10309 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10310 	if (actp == NULL)
10311 		goto enomem;
10312 
10313 	/*
10314 	 * Always allocate IPv4 policy entries, since they can also
10315 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10316 	 */
10317 	bzero(&sel, sizeof (sel));
10318 	sel.ipsl_valid = IPSL_IPV4;
10319 
10320 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10321 	    ipst->ips_netstack);
10322 	if (pin4 == NULL)
10323 		goto enomem;
10324 
10325 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10326 	    ipst->ips_netstack);
10327 	if (pout4 == NULL)
10328 		goto enomem;
10329 
10330 	if (connp->conn_af_isv6) {
10331 		/*
10332 		 * We're looking at a v6 socket, also allocate the
10333 		 * v6-specific entries...
10334 		 */
10335 		sel.ipsl_valid = IPSL_IPV6;
10336 		pin6 = ipsec_policy_create(&sel, actp, nact,
10337 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10338 		if (pin6 == NULL)
10339 			goto enomem;
10340 
10341 		pout6 = ipsec_policy_create(&sel, actp, nact,
10342 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10343 		if (pout6 == NULL)
10344 			goto enomem;
10345 
10346 		/*
10347 		 * .. and file them away in the right place.
10348 		 */
10349 		fam = IPSEC_AF_V6;
10350 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10351 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10352 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10353 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10354 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10355 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10356 	}
10357 
10358 	ipsec_actvec_free(actp, nact);
10359 
10360 	/*
10361 	 * File the v4 policies.
10362 	 */
10363 	fam = IPSEC_AF_V4;
10364 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10365 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10366 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10367 
10368 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10369 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10370 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10371 
10372 	/*
10373 	 * If the requests need security, set enforce_policy.
10374 	 * If the requests are IPSEC_PREF_NEVER, one should
10375 	 * still set conn_out_enforce_policy so that an ipsec_out
10376 	 * gets attached in ip_wput. This is needed so that
10377 	 * for connections that we don't cache policy in ip_bind,
10378 	 * if global policy matches in ip_wput_attach_policy, we
10379 	 * don't wrongly inherit global policy. Similarly, we need
10380 	 * to set conn_in_enforce_policy also so that we don't verify
10381 	 * policy wrongly.
10382 	 */
10383 	if ((ah_req & REQ_MASK) != 0 ||
10384 	    (esp_req & REQ_MASK) != 0 ||
10385 	    (se_req & REQ_MASK) != 0) {
10386 		connp->conn_in_enforce_policy = B_TRUE;
10387 		connp->conn_out_enforce_policy = B_TRUE;
10388 		connp->conn_flags |= IPCL_CHECK_POLICY;
10389 	}
10390 
10391 	mutex_exit(&connp->conn_lock);
10392 	return (error);
10393 #undef REQ_MASK
10394 
10395 	/*
10396 	 * Common memory-allocation-failure exit path.
10397 	 */
10398 enomem:
10399 	mutex_exit(&connp->conn_lock);
10400 	if (actp != NULL)
10401 		ipsec_actvec_free(actp, nact);
10402 	if (pin4 != NULL)
10403 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10404 	if (pout4 != NULL)
10405 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10406 	if (pin6 != NULL)
10407 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10408 	if (pout6 != NULL)
10409 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10410 	return (ENOMEM);
10411 }
10412 
10413 /*
10414  * Only for options that pass in an IP addr. Currently only V4 options
10415  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10416  * So this function assumes level is IPPROTO_IP
10417  */
10418 int
10419 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10420     mblk_t *first_mp)
10421 {
10422 	ipif_t *ipif = NULL;
10423 	int error;
10424 	ill_t *ill;
10425 	int zoneid;
10426 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10427 
10428 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10429 
10430 	if (addr != INADDR_ANY || checkonly) {
10431 		ASSERT(connp != NULL);
10432 		zoneid = IPCL_ZONEID(connp);
10433 		if (option == IP_NEXTHOP) {
10434 			ipif = ipif_lookup_onlink_addr(addr,
10435 			    connp->conn_zoneid, ipst);
10436 		} else {
10437 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10438 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10439 			    &error, ipst);
10440 		}
10441 		if (ipif == NULL) {
10442 			if (error == EINPROGRESS)
10443 				return (error);
10444 			if ((option == IP_MULTICAST_IF) ||
10445 			    (option == IP_NEXTHOP))
10446 				return (EHOSTUNREACH);
10447 			else
10448 				return (EINVAL);
10449 		} else if (checkonly) {
10450 			if (option == IP_MULTICAST_IF) {
10451 				ill = ipif->ipif_ill;
10452 				/* not supported by the virtual network iface */
10453 				if (IS_VNI(ill)) {
10454 					ipif_refrele(ipif);
10455 					return (EINVAL);
10456 				}
10457 			}
10458 			ipif_refrele(ipif);
10459 			return (0);
10460 		}
10461 		ill = ipif->ipif_ill;
10462 		mutex_enter(&connp->conn_lock);
10463 		mutex_enter(&ill->ill_lock);
10464 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10465 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10466 			mutex_exit(&ill->ill_lock);
10467 			mutex_exit(&connp->conn_lock);
10468 			ipif_refrele(ipif);
10469 			return (option == IP_MULTICAST_IF ?
10470 			    EHOSTUNREACH : EINVAL);
10471 		}
10472 	} else {
10473 		mutex_enter(&connp->conn_lock);
10474 	}
10475 
10476 	/* None of the options below are supported on the VNI */
10477 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10478 		mutex_exit(&ill->ill_lock);
10479 		mutex_exit(&connp->conn_lock);
10480 		ipif_refrele(ipif);
10481 		return (EINVAL);
10482 	}
10483 
10484 	switch (option) {
10485 	case IP_DONTFAILOVER_IF:
10486 		/*
10487 		 * This option is used by in.mpathd to ensure
10488 		 * that IPMP probe packets only go out on the
10489 		 * test interfaces. in.mpathd sets this option
10490 		 * on the non-failover interfaces.
10491 		 * For backward compatibility, this option
10492 		 * implicitly sets IP_MULTICAST_IF, as used
10493 		 * be done in bind(), so that ip_wput gets
10494 		 * this ipif to send mcast packets.
10495 		 */
10496 		if (ipif != NULL) {
10497 			ASSERT(addr != INADDR_ANY);
10498 			connp->conn_nofailover_ill = ipif->ipif_ill;
10499 			connp->conn_multicast_ipif = ipif;
10500 		} else {
10501 			ASSERT(addr == INADDR_ANY);
10502 			connp->conn_nofailover_ill = NULL;
10503 			connp->conn_multicast_ipif = NULL;
10504 		}
10505 		break;
10506 
10507 	case IP_MULTICAST_IF:
10508 		connp->conn_multicast_ipif = ipif;
10509 		break;
10510 	case IP_NEXTHOP:
10511 		connp->conn_nexthop_v4 = addr;
10512 		connp->conn_nexthop_set = B_TRUE;
10513 		break;
10514 	}
10515 
10516 	if (ipif != NULL) {
10517 		mutex_exit(&ill->ill_lock);
10518 		mutex_exit(&connp->conn_lock);
10519 		ipif_refrele(ipif);
10520 		return (0);
10521 	}
10522 	mutex_exit(&connp->conn_lock);
10523 	/* We succeded in cleared the option */
10524 	return (0);
10525 }
10526 
10527 /*
10528  * For options that pass in an ifindex specifying the ill. V6 options always
10529  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10530  */
10531 int
10532 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10533     int level, int option, mblk_t *first_mp)
10534 {
10535 	ill_t *ill = NULL;
10536 	int error = 0;
10537 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10538 
10539 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10540 	if (ifindex != 0) {
10541 		ASSERT(connp != NULL);
10542 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10543 		    first_mp, ip_restart_optmgmt, &error, ipst);
10544 		if (ill != NULL) {
10545 			if (checkonly) {
10546 				/* not supported by the virtual network iface */
10547 				if (IS_VNI(ill)) {
10548 					ill_refrele(ill);
10549 					return (EINVAL);
10550 				}
10551 				ill_refrele(ill);
10552 				return (0);
10553 			}
10554 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10555 			    0, NULL)) {
10556 				ill_refrele(ill);
10557 				ill = NULL;
10558 				mutex_enter(&connp->conn_lock);
10559 				goto setit;
10560 			}
10561 			mutex_enter(&connp->conn_lock);
10562 			mutex_enter(&ill->ill_lock);
10563 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10564 				mutex_exit(&ill->ill_lock);
10565 				mutex_exit(&connp->conn_lock);
10566 				ill_refrele(ill);
10567 				ill = NULL;
10568 				mutex_enter(&connp->conn_lock);
10569 			}
10570 			goto setit;
10571 		} else if (error == EINPROGRESS) {
10572 			return (error);
10573 		} else {
10574 			error = 0;
10575 		}
10576 	}
10577 	mutex_enter(&connp->conn_lock);
10578 setit:
10579 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10580 
10581 	/*
10582 	 * The options below assume that the ILL (if any) transmits and/or
10583 	 * receives traffic. Neither of which is true for the virtual network
10584 	 * interface, so fail setting these on a VNI.
10585 	 */
10586 	if (IS_VNI(ill)) {
10587 		ASSERT(ill != NULL);
10588 		mutex_exit(&ill->ill_lock);
10589 		mutex_exit(&connp->conn_lock);
10590 		ill_refrele(ill);
10591 		return (EINVAL);
10592 	}
10593 
10594 	if (level == IPPROTO_IP) {
10595 		switch (option) {
10596 		case IP_BOUND_IF:
10597 			connp->conn_incoming_ill = ill;
10598 			connp->conn_outgoing_ill = ill;
10599 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10600 			    0 : ifindex;
10601 			break;
10602 
10603 		case IP_MULTICAST_IF:
10604 			/*
10605 			 * This option is an internal special. The socket
10606 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10607 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10608 			 * specifies an ifindex and we try first on V6 ill's.
10609 			 * If we don't find one, we they try using on v4 ill's
10610 			 * intenally and we come here.
10611 			 */
10612 			if (!checkonly && ill != NULL) {
10613 				ipif_t	*ipif;
10614 				ipif = ill->ill_ipif;
10615 
10616 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10617 					mutex_exit(&ill->ill_lock);
10618 					mutex_exit(&connp->conn_lock);
10619 					ill_refrele(ill);
10620 					ill = NULL;
10621 					mutex_enter(&connp->conn_lock);
10622 				} else {
10623 					connp->conn_multicast_ipif = ipif;
10624 				}
10625 			}
10626 			break;
10627 
10628 		case IP_DHCPINIT_IF:
10629 			if (connp->conn_dhcpinit_ill != NULL) {
10630 				/*
10631 				 * We've locked the conn so conn_cleanup_ill()
10632 				 * cannot clear conn_dhcpinit_ill -- so it's
10633 				 * safe to access the ill.
10634 				 */
10635 				ill_t *oill = connp->conn_dhcpinit_ill;
10636 
10637 				ASSERT(oill->ill_dhcpinit != 0);
10638 				atomic_dec_32(&oill->ill_dhcpinit);
10639 				connp->conn_dhcpinit_ill = NULL;
10640 			}
10641 
10642 			if (ill != NULL) {
10643 				connp->conn_dhcpinit_ill = ill;
10644 				atomic_inc_32(&ill->ill_dhcpinit);
10645 			}
10646 			break;
10647 		}
10648 	} else {
10649 		switch (option) {
10650 		case IPV6_BOUND_IF:
10651 			connp->conn_incoming_ill = ill;
10652 			connp->conn_outgoing_ill = ill;
10653 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10654 			    0 : ifindex;
10655 			break;
10656 
10657 		case IPV6_BOUND_PIF:
10658 			/*
10659 			 * Limit all transmit to this ill.
10660 			 * Unlike IPV6_BOUND_IF, using this option
10661 			 * prevents load spreading and failover from
10662 			 * happening when the interface is part of the
10663 			 * group. That's why we don't need to remember
10664 			 * the ifindex in orig_bound_ifindex as in
10665 			 * IPV6_BOUND_IF.
10666 			 */
10667 			connp->conn_outgoing_pill = ill;
10668 			break;
10669 
10670 		case IPV6_DONTFAILOVER_IF:
10671 			/*
10672 			 * This option is used by in.mpathd to ensure
10673 			 * that IPMP probe packets only go out on the
10674 			 * test interfaces. in.mpathd sets this option
10675 			 * on the non-failover interfaces.
10676 			 */
10677 			connp->conn_nofailover_ill = ill;
10678 			/*
10679 			 * For backward compatibility, this option
10680 			 * implicitly sets ip_multicast_ill as used in
10681 			 * IPV6_MULTICAST_IF so that ip_wput gets
10682 			 * this ill to send mcast packets.
10683 			 */
10684 			connp->conn_multicast_ill = ill;
10685 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10686 			    0 : ifindex;
10687 			break;
10688 
10689 		case IPV6_MULTICAST_IF:
10690 			/*
10691 			 * Set conn_multicast_ill to be the IPv6 ill.
10692 			 * Set conn_multicast_ipif to be an IPv4 ipif
10693 			 * for ifindex to make IPv4 mapped addresses
10694 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10695 			 * Even if no IPv6 ill exists for the ifindex
10696 			 * we need to check for an IPv4 ifindex in order
10697 			 * for this to work with mapped addresses. In that
10698 			 * case only set conn_multicast_ipif.
10699 			 */
10700 			if (!checkonly) {
10701 				if (ifindex == 0) {
10702 					connp->conn_multicast_ill = NULL;
10703 					connp->conn_orig_multicast_ifindex = 0;
10704 					connp->conn_multicast_ipif = NULL;
10705 				} else if (ill != NULL) {
10706 					connp->conn_multicast_ill = ill;
10707 					connp->conn_orig_multicast_ifindex =
10708 					    ifindex;
10709 				}
10710 			}
10711 			break;
10712 		}
10713 	}
10714 
10715 	if (ill != NULL) {
10716 		mutex_exit(&ill->ill_lock);
10717 		mutex_exit(&connp->conn_lock);
10718 		ill_refrele(ill);
10719 		return (0);
10720 	}
10721 	mutex_exit(&connp->conn_lock);
10722 	/*
10723 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10724 	 * locate the ill and could not set the option (ifindex != 0)
10725 	 */
10726 	return (ifindex == 0 ? 0 : EINVAL);
10727 }
10728 
10729 /* This routine sets socket options. */
10730 /* ARGSUSED */
10731 int
10732 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10733     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10734     void *dummy, cred_t *cr, mblk_t *first_mp)
10735 {
10736 	int		*i1 = (int *)invalp;
10737 	conn_t		*connp = Q_TO_CONN(q);
10738 	int		error = 0;
10739 	boolean_t	checkonly;
10740 	ire_t		*ire;
10741 	boolean_t	found;
10742 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10743 
10744 	switch (optset_context) {
10745 
10746 	case SETFN_OPTCOM_CHECKONLY:
10747 		checkonly = B_TRUE;
10748 		/*
10749 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10750 		 * inlen != 0 implies value supplied and
10751 		 * 	we have to "pretend" to set it.
10752 		 * inlen == 0 implies that there is no
10753 		 * 	value part in T_CHECK request and just validation
10754 		 * done elsewhere should be enough, we just return here.
10755 		 */
10756 		if (inlen == 0) {
10757 			*outlenp = 0;
10758 			return (0);
10759 		}
10760 		break;
10761 	case SETFN_OPTCOM_NEGOTIATE:
10762 	case SETFN_UD_NEGOTIATE:
10763 	case SETFN_CONN_NEGOTIATE:
10764 		checkonly = B_FALSE;
10765 		break;
10766 	default:
10767 		/*
10768 		 * We should never get here
10769 		 */
10770 		*outlenp = 0;
10771 		return (EINVAL);
10772 	}
10773 
10774 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10775 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10776 
10777 	/*
10778 	 * For fixed length options, no sanity check
10779 	 * of passed in length is done. It is assumed *_optcom_req()
10780 	 * routines do the right thing.
10781 	 */
10782 
10783 	switch (level) {
10784 	case SOL_SOCKET:
10785 		/*
10786 		 * conn_lock protects the bitfields, and is used to
10787 		 * set the fields atomically.
10788 		 */
10789 		switch (name) {
10790 		case SO_BROADCAST:
10791 			if (!checkonly) {
10792 				/* TODO: use value someplace? */
10793 				mutex_enter(&connp->conn_lock);
10794 				connp->conn_broadcast = *i1 ? 1 : 0;
10795 				mutex_exit(&connp->conn_lock);
10796 			}
10797 			break;	/* goto sizeof (int) option return */
10798 		case SO_USELOOPBACK:
10799 			if (!checkonly) {
10800 				/* TODO: use value someplace? */
10801 				mutex_enter(&connp->conn_lock);
10802 				connp->conn_loopback = *i1 ? 1 : 0;
10803 				mutex_exit(&connp->conn_lock);
10804 			}
10805 			break;	/* goto sizeof (int) option return */
10806 		case SO_DONTROUTE:
10807 			if (!checkonly) {
10808 				mutex_enter(&connp->conn_lock);
10809 				connp->conn_dontroute = *i1 ? 1 : 0;
10810 				mutex_exit(&connp->conn_lock);
10811 			}
10812 			break;	/* goto sizeof (int) option return */
10813 		case SO_REUSEADDR:
10814 			if (!checkonly) {
10815 				mutex_enter(&connp->conn_lock);
10816 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10817 				mutex_exit(&connp->conn_lock);
10818 			}
10819 			break;	/* goto sizeof (int) option return */
10820 		case SO_PROTOTYPE:
10821 			if (!checkonly) {
10822 				mutex_enter(&connp->conn_lock);
10823 				connp->conn_proto = *i1;
10824 				mutex_exit(&connp->conn_lock);
10825 			}
10826 			break;	/* goto sizeof (int) option return */
10827 		case SO_ALLZONES:
10828 			if (!checkonly) {
10829 				mutex_enter(&connp->conn_lock);
10830 				if (IPCL_IS_BOUND(connp)) {
10831 					mutex_exit(&connp->conn_lock);
10832 					return (EINVAL);
10833 				}
10834 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10835 				mutex_exit(&connp->conn_lock);
10836 			}
10837 			break;	/* goto sizeof (int) option return */
10838 		case SO_ANON_MLP:
10839 			if (!checkonly) {
10840 				mutex_enter(&connp->conn_lock);
10841 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10842 				mutex_exit(&connp->conn_lock);
10843 			}
10844 			break;	/* goto sizeof (int) option return */
10845 		case SO_MAC_EXEMPT:
10846 			if (secpolicy_net_mac_aware(cr) != 0 ||
10847 			    IPCL_IS_BOUND(connp))
10848 				return (EACCES);
10849 			if (!checkonly) {
10850 				mutex_enter(&connp->conn_lock);
10851 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10852 				mutex_exit(&connp->conn_lock);
10853 			}
10854 			break;	/* goto sizeof (int) option return */
10855 		default:
10856 			/*
10857 			 * "soft" error (negative)
10858 			 * option not handled at this level
10859 			 * Note: Do not modify *outlenp
10860 			 */
10861 			return (-EINVAL);
10862 		}
10863 		break;
10864 	case IPPROTO_IP:
10865 		switch (name) {
10866 		case IP_NEXTHOP:
10867 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10868 				return (EPERM);
10869 			/* FALLTHRU */
10870 		case IP_MULTICAST_IF:
10871 		case IP_DONTFAILOVER_IF: {
10872 			ipaddr_t addr = *i1;
10873 
10874 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10875 			    first_mp);
10876 			if (error != 0)
10877 				return (error);
10878 			break;	/* goto sizeof (int) option return */
10879 		}
10880 
10881 		case IP_MULTICAST_TTL:
10882 			/* Recorded in transport above IP */
10883 			*outvalp = *invalp;
10884 			*outlenp = sizeof (uchar_t);
10885 			return (0);
10886 		case IP_MULTICAST_LOOP:
10887 			if (!checkonly) {
10888 				mutex_enter(&connp->conn_lock);
10889 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10890 				mutex_exit(&connp->conn_lock);
10891 			}
10892 			*outvalp = *invalp;
10893 			*outlenp = sizeof (uchar_t);
10894 			return (0);
10895 		case IP_ADD_MEMBERSHIP:
10896 		case MCAST_JOIN_GROUP:
10897 		case IP_DROP_MEMBERSHIP:
10898 		case MCAST_LEAVE_GROUP: {
10899 			struct ip_mreq *mreqp;
10900 			struct group_req *greqp;
10901 			ire_t *ire;
10902 			boolean_t done = B_FALSE;
10903 			ipaddr_t group, ifaddr;
10904 			struct sockaddr_in *sin;
10905 			uint32_t *ifindexp;
10906 			boolean_t mcast_opt = B_TRUE;
10907 			mcast_record_t fmode;
10908 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10909 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10910 
10911 			switch (name) {
10912 			case IP_ADD_MEMBERSHIP:
10913 				mcast_opt = B_FALSE;
10914 				/* FALLTHRU */
10915 			case MCAST_JOIN_GROUP:
10916 				fmode = MODE_IS_EXCLUDE;
10917 				optfn = ip_opt_add_group;
10918 				break;
10919 
10920 			case IP_DROP_MEMBERSHIP:
10921 				mcast_opt = B_FALSE;
10922 				/* FALLTHRU */
10923 			case MCAST_LEAVE_GROUP:
10924 				fmode = MODE_IS_INCLUDE;
10925 				optfn = ip_opt_delete_group;
10926 				break;
10927 			}
10928 
10929 			if (mcast_opt) {
10930 				greqp = (struct group_req *)i1;
10931 				sin = (struct sockaddr_in *)&greqp->gr_group;
10932 				if (sin->sin_family != AF_INET) {
10933 					*outlenp = 0;
10934 					return (ENOPROTOOPT);
10935 				}
10936 				group = (ipaddr_t)sin->sin_addr.s_addr;
10937 				ifaddr = INADDR_ANY;
10938 				ifindexp = &greqp->gr_interface;
10939 			} else {
10940 				mreqp = (struct ip_mreq *)i1;
10941 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10942 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10943 				ifindexp = NULL;
10944 			}
10945 
10946 			/*
10947 			 * In the multirouting case, we need to replicate
10948 			 * the request on all interfaces that will take part
10949 			 * in replication.  We do so because multirouting is
10950 			 * reflective, thus we will probably receive multi-
10951 			 * casts on those interfaces.
10952 			 * The ip_multirt_apply_membership() succeeds if the
10953 			 * operation succeeds on at least one interface.
10954 			 */
10955 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10956 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10957 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10958 			if (ire != NULL) {
10959 				if (ire->ire_flags & RTF_MULTIRT) {
10960 					error = ip_multirt_apply_membership(
10961 					    optfn, ire, connp, checkonly, group,
10962 					    fmode, INADDR_ANY, first_mp);
10963 					done = B_TRUE;
10964 				}
10965 				ire_refrele(ire);
10966 			}
10967 			if (!done) {
10968 				error = optfn(connp, checkonly, group, ifaddr,
10969 				    ifindexp, fmode, INADDR_ANY, first_mp);
10970 			}
10971 			if (error) {
10972 				/*
10973 				 * EINPROGRESS is a soft error, needs retry
10974 				 * so don't make *outlenp zero.
10975 				 */
10976 				if (error != EINPROGRESS)
10977 					*outlenp = 0;
10978 				return (error);
10979 			}
10980 			/* OK return - copy input buffer into output buffer */
10981 			if (invalp != outvalp) {
10982 				/* don't trust bcopy for identical src/dst */
10983 				bcopy(invalp, outvalp, inlen);
10984 			}
10985 			*outlenp = inlen;
10986 			return (0);
10987 		}
10988 		case IP_BLOCK_SOURCE:
10989 		case IP_UNBLOCK_SOURCE:
10990 		case IP_ADD_SOURCE_MEMBERSHIP:
10991 		case IP_DROP_SOURCE_MEMBERSHIP:
10992 		case MCAST_BLOCK_SOURCE:
10993 		case MCAST_UNBLOCK_SOURCE:
10994 		case MCAST_JOIN_SOURCE_GROUP:
10995 		case MCAST_LEAVE_SOURCE_GROUP: {
10996 			struct ip_mreq_source *imreqp;
10997 			struct group_source_req *gsreqp;
10998 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10999 			uint32_t ifindex = 0;
11000 			mcast_record_t fmode;
11001 			struct sockaddr_in *sin;
11002 			ire_t *ire;
11003 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
11004 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
11005 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
11006 
11007 			switch (name) {
11008 			case IP_BLOCK_SOURCE:
11009 				mcast_opt = B_FALSE;
11010 				/* FALLTHRU */
11011 			case MCAST_BLOCK_SOURCE:
11012 				fmode = MODE_IS_EXCLUDE;
11013 				optfn = ip_opt_add_group;
11014 				break;
11015 
11016 			case IP_UNBLOCK_SOURCE:
11017 				mcast_opt = B_FALSE;
11018 				/* FALLTHRU */
11019 			case MCAST_UNBLOCK_SOURCE:
11020 				fmode = MODE_IS_EXCLUDE;
11021 				optfn = ip_opt_delete_group;
11022 				break;
11023 
11024 			case IP_ADD_SOURCE_MEMBERSHIP:
11025 				mcast_opt = B_FALSE;
11026 				/* FALLTHRU */
11027 			case MCAST_JOIN_SOURCE_GROUP:
11028 				fmode = MODE_IS_INCLUDE;
11029 				optfn = ip_opt_add_group;
11030 				break;
11031 
11032 			case IP_DROP_SOURCE_MEMBERSHIP:
11033 				mcast_opt = B_FALSE;
11034 				/* FALLTHRU */
11035 			case MCAST_LEAVE_SOURCE_GROUP:
11036 				fmode = MODE_IS_INCLUDE;
11037 				optfn = ip_opt_delete_group;
11038 				break;
11039 			}
11040 
11041 			if (mcast_opt) {
11042 				gsreqp = (struct group_source_req *)i1;
11043 				if (gsreqp->gsr_group.ss_family != AF_INET) {
11044 					*outlenp = 0;
11045 					return (ENOPROTOOPT);
11046 				}
11047 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
11048 				grp = (ipaddr_t)sin->sin_addr.s_addr;
11049 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
11050 				src = (ipaddr_t)sin->sin_addr.s_addr;
11051 				ifindex = gsreqp->gsr_interface;
11052 			} else {
11053 				imreqp = (struct ip_mreq_source *)i1;
11054 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
11055 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
11056 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
11057 			}
11058 
11059 			/*
11060 			 * In the multirouting case, we need to replicate
11061 			 * the request as noted in the mcast cases above.
11062 			 */
11063 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
11064 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11065 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11066 			if (ire != NULL) {
11067 				if (ire->ire_flags & RTF_MULTIRT) {
11068 					error = ip_multirt_apply_membership(
11069 					    optfn, ire, connp, checkonly, grp,
11070 					    fmode, src, first_mp);
11071 					done = B_TRUE;
11072 				}
11073 				ire_refrele(ire);
11074 			}
11075 			if (!done) {
11076 				error = optfn(connp, checkonly, grp, ifaddr,
11077 				    &ifindex, fmode, src, first_mp);
11078 			}
11079 			if (error != 0) {
11080 				/*
11081 				 * EINPROGRESS is a soft error, needs retry
11082 				 * so don't make *outlenp zero.
11083 				 */
11084 				if (error != EINPROGRESS)
11085 					*outlenp = 0;
11086 				return (error);
11087 			}
11088 			/* OK return - copy input buffer into output buffer */
11089 			if (invalp != outvalp) {
11090 				bcopy(invalp, outvalp, inlen);
11091 			}
11092 			*outlenp = inlen;
11093 			return (0);
11094 		}
11095 		case IP_SEC_OPT:
11096 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11097 			if (error != 0) {
11098 				*outlenp = 0;
11099 				return (error);
11100 			}
11101 			break;
11102 		case IP_HDRINCL:
11103 		case IP_OPTIONS:
11104 		case T_IP_OPTIONS:
11105 		case IP_TOS:
11106 		case T_IP_TOS:
11107 		case IP_TTL:
11108 		case IP_RECVDSTADDR:
11109 		case IP_RECVOPTS:
11110 			/* OK return - copy input buffer into output buffer */
11111 			if (invalp != outvalp) {
11112 				/* don't trust bcopy for identical src/dst */
11113 				bcopy(invalp, outvalp, inlen);
11114 			}
11115 			*outlenp = inlen;
11116 			return (0);
11117 		case IP_RECVIF:
11118 			/* Retrieve the inbound interface index */
11119 			if (!checkonly) {
11120 				mutex_enter(&connp->conn_lock);
11121 				connp->conn_recvif = *i1 ? 1 : 0;
11122 				mutex_exit(&connp->conn_lock);
11123 			}
11124 			break;	/* goto sizeof (int) option return */
11125 		case IP_RECVPKTINFO:
11126 			if (!checkonly) {
11127 				mutex_enter(&connp->conn_lock);
11128 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11129 				mutex_exit(&connp->conn_lock);
11130 			}
11131 			break;	/* goto sizeof (int) option return */
11132 		case IP_RECVSLLA:
11133 			/* Retrieve the source link layer address */
11134 			if (!checkonly) {
11135 				mutex_enter(&connp->conn_lock);
11136 				connp->conn_recvslla = *i1 ? 1 : 0;
11137 				mutex_exit(&connp->conn_lock);
11138 			}
11139 			break;	/* goto sizeof (int) option return */
11140 		case MRT_INIT:
11141 		case MRT_DONE:
11142 		case MRT_ADD_VIF:
11143 		case MRT_DEL_VIF:
11144 		case MRT_ADD_MFC:
11145 		case MRT_DEL_MFC:
11146 		case MRT_ASSERT:
11147 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11148 				*outlenp = 0;
11149 				return (error);
11150 			}
11151 			error = ip_mrouter_set((int)name, q, checkonly,
11152 			    (uchar_t *)invalp, inlen, first_mp);
11153 			if (error) {
11154 				*outlenp = 0;
11155 				return (error);
11156 			}
11157 			/* OK return - copy input buffer into output buffer */
11158 			if (invalp != outvalp) {
11159 				/* don't trust bcopy for identical src/dst */
11160 				bcopy(invalp, outvalp, inlen);
11161 			}
11162 			*outlenp = inlen;
11163 			return (0);
11164 		case IP_BOUND_IF:
11165 		case IP_DHCPINIT_IF:
11166 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11167 			    level, name, first_mp);
11168 			if (error != 0)
11169 				return (error);
11170 			break; 		/* goto sizeof (int) option return */
11171 
11172 		case IP_UNSPEC_SRC:
11173 			/* Allow sending with a zero source address */
11174 			if (!checkonly) {
11175 				mutex_enter(&connp->conn_lock);
11176 				connp->conn_unspec_src = *i1 ? 1 : 0;
11177 				mutex_exit(&connp->conn_lock);
11178 			}
11179 			break;	/* goto sizeof (int) option return */
11180 		default:
11181 			/*
11182 			 * "soft" error (negative)
11183 			 * option not handled at this level
11184 			 * Note: Do not modify *outlenp
11185 			 */
11186 			return (-EINVAL);
11187 		}
11188 		break;
11189 	case IPPROTO_IPV6:
11190 		switch (name) {
11191 		case IPV6_BOUND_IF:
11192 		case IPV6_BOUND_PIF:
11193 		case IPV6_DONTFAILOVER_IF:
11194 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11195 			    level, name, first_mp);
11196 			if (error != 0)
11197 				return (error);
11198 			break; 		/* goto sizeof (int) option return */
11199 
11200 		case IPV6_MULTICAST_IF:
11201 			/*
11202 			 * The only possible errors are EINPROGRESS and
11203 			 * EINVAL. EINPROGRESS will be restarted and is not
11204 			 * a hard error. We call this option on both V4 and V6
11205 			 * If both return EINVAL, then this call returns
11206 			 * EINVAL. If at least one of them succeeds we
11207 			 * return success.
11208 			 */
11209 			found = B_FALSE;
11210 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11211 			    level, name, first_mp);
11212 			if (error == EINPROGRESS)
11213 				return (error);
11214 			if (error == 0)
11215 				found = B_TRUE;
11216 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11217 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11218 			if (error == 0)
11219 				found = B_TRUE;
11220 			if (!found)
11221 				return (error);
11222 			break; 		/* goto sizeof (int) option return */
11223 
11224 		case IPV6_MULTICAST_HOPS:
11225 			/* Recorded in transport above IP */
11226 			break;	/* goto sizeof (int) option return */
11227 		case IPV6_MULTICAST_LOOP:
11228 			if (!checkonly) {
11229 				mutex_enter(&connp->conn_lock);
11230 				connp->conn_multicast_loop = *i1;
11231 				mutex_exit(&connp->conn_lock);
11232 			}
11233 			break;	/* goto sizeof (int) option return */
11234 		case IPV6_JOIN_GROUP:
11235 		case MCAST_JOIN_GROUP:
11236 		case IPV6_LEAVE_GROUP:
11237 		case MCAST_LEAVE_GROUP: {
11238 			struct ipv6_mreq *ip_mreqp;
11239 			struct group_req *greqp;
11240 			ire_t *ire;
11241 			boolean_t done = B_FALSE;
11242 			in6_addr_t groupv6;
11243 			uint32_t ifindex;
11244 			boolean_t mcast_opt = B_TRUE;
11245 			mcast_record_t fmode;
11246 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11247 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11248 
11249 			switch (name) {
11250 			case IPV6_JOIN_GROUP:
11251 				mcast_opt = B_FALSE;
11252 				/* FALLTHRU */
11253 			case MCAST_JOIN_GROUP:
11254 				fmode = MODE_IS_EXCLUDE;
11255 				optfn = ip_opt_add_group_v6;
11256 				break;
11257 
11258 			case IPV6_LEAVE_GROUP:
11259 				mcast_opt = B_FALSE;
11260 				/* FALLTHRU */
11261 			case MCAST_LEAVE_GROUP:
11262 				fmode = MODE_IS_INCLUDE;
11263 				optfn = ip_opt_delete_group_v6;
11264 				break;
11265 			}
11266 
11267 			if (mcast_opt) {
11268 				struct sockaddr_in *sin;
11269 				struct sockaddr_in6 *sin6;
11270 				greqp = (struct group_req *)i1;
11271 				if (greqp->gr_group.ss_family == AF_INET) {
11272 					sin = (struct sockaddr_in *)
11273 					    &(greqp->gr_group);
11274 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11275 					    &groupv6);
11276 				} else {
11277 					sin6 = (struct sockaddr_in6 *)
11278 					    &(greqp->gr_group);
11279 					groupv6 = sin6->sin6_addr;
11280 				}
11281 				ifindex = greqp->gr_interface;
11282 			} else {
11283 				ip_mreqp = (struct ipv6_mreq *)i1;
11284 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11285 				ifindex = ip_mreqp->ipv6mr_interface;
11286 			}
11287 			/*
11288 			 * In the multirouting case, we need to replicate
11289 			 * the request on all interfaces that will take part
11290 			 * in replication.  We do so because multirouting is
11291 			 * reflective, thus we will probably receive multi-
11292 			 * casts on those interfaces.
11293 			 * The ip_multirt_apply_membership_v6() succeeds if
11294 			 * the operation succeeds on at least one interface.
11295 			 */
11296 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11297 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11298 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11299 			if (ire != NULL) {
11300 				if (ire->ire_flags & RTF_MULTIRT) {
11301 					error = ip_multirt_apply_membership_v6(
11302 					    optfn, ire, connp, checkonly,
11303 					    &groupv6, fmode, &ipv6_all_zeros,
11304 					    first_mp);
11305 					done = B_TRUE;
11306 				}
11307 				ire_refrele(ire);
11308 			}
11309 			if (!done) {
11310 				error = optfn(connp, checkonly, &groupv6,
11311 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11312 			}
11313 			if (error) {
11314 				/*
11315 				 * EINPROGRESS is a soft error, needs retry
11316 				 * so don't make *outlenp zero.
11317 				 */
11318 				if (error != EINPROGRESS)
11319 					*outlenp = 0;
11320 				return (error);
11321 			}
11322 			/* OK return - copy input buffer into output buffer */
11323 			if (invalp != outvalp) {
11324 				/* don't trust bcopy for identical src/dst */
11325 				bcopy(invalp, outvalp, inlen);
11326 			}
11327 			*outlenp = inlen;
11328 			return (0);
11329 		}
11330 		case MCAST_BLOCK_SOURCE:
11331 		case MCAST_UNBLOCK_SOURCE:
11332 		case MCAST_JOIN_SOURCE_GROUP:
11333 		case MCAST_LEAVE_SOURCE_GROUP: {
11334 			struct group_source_req *gsreqp;
11335 			in6_addr_t v6grp, v6src;
11336 			uint32_t ifindex;
11337 			mcast_record_t fmode;
11338 			ire_t *ire;
11339 			boolean_t done = B_FALSE;
11340 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11341 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11342 
11343 			switch (name) {
11344 			case MCAST_BLOCK_SOURCE:
11345 				fmode = MODE_IS_EXCLUDE;
11346 				optfn = ip_opt_add_group_v6;
11347 				break;
11348 			case MCAST_UNBLOCK_SOURCE:
11349 				fmode = MODE_IS_EXCLUDE;
11350 				optfn = ip_opt_delete_group_v6;
11351 				break;
11352 			case MCAST_JOIN_SOURCE_GROUP:
11353 				fmode = MODE_IS_INCLUDE;
11354 				optfn = ip_opt_add_group_v6;
11355 				break;
11356 			case MCAST_LEAVE_SOURCE_GROUP:
11357 				fmode = MODE_IS_INCLUDE;
11358 				optfn = ip_opt_delete_group_v6;
11359 				break;
11360 			}
11361 
11362 			gsreqp = (struct group_source_req *)i1;
11363 			ifindex = gsreqp->gsr_interface;
11364 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11365 				struct sockaddr_in *s;
11366 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11367 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11368 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11369 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11370 			} else {
11371 				struct sockaddr_in6 *s6;
11372 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11373 				v6grp = s6->sin6_addr;
11374 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11375 				v6src = s6->sin6_addr;
11376 			}
11377 
11378 			/*
11379 			 * In the multirouting case, we need to replicate
11380 			 * the request as noted in the mcast cases above.
11381 			 */
11382 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11383 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11384 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11385 			if (ire != NULL) {
11386 				if (ire->ire_flags & RTF_MULTIRT) {
11387 					error = ip_multirt_apply_membership_v6(
11388 					    optfn, ire, connp, checkonly,
11389 					    &v6grp, fmode, &v6src, first_mp);
11390 					done = B_TRUE;
11391 				}
11392 				ire_refrele(ire);
11393 			}
11394 			if (!done) {
11395 				error = optfn(connp, checkonly, &v6grp,
11396 				    ifindex, fmode, &v6src, first_mp);
11397 			}
11398 			if (error != 0) {
11399 				/*
11400 				 * EINPROGRESS is a soft error, needs retry
11401 				 * so don't make *outlenp zero.
11402 				 */
11403 				if (error != EINPROGRESS)
11404 					*outlenp = 0;
11405 				return (error);
11406 			}
11407 			/* OK return - copy input buffer into output buffer */
11408 			if (invalp != outvalp) {
11409 				bcopy(invalp, outvalp, inlen);
11410 			}
11411 			*outlenp = inlen;
11412 			return (0);
11413 		}
11414 		case IPV6_UNICAST_HOPS:
11415 			/* Recorded in transport above IP */
11416 			break;	/* goto sizeof (int) option return */
11417 		case IPV6_UNSPEC_SRC:
11418 			/* Allow sending with a zero source address */
11419 			if (!checkonly) {
11420 				mutex_enter(&connp->conn_lock);
11421 				connp->conn_unspec_src = *i1 ? 1 : 0;
11422 				mutex_exit(&connp->conn_lock);
11423 			}
11424 			break;	/* goto sizeof (int) option return */
11425 		case IPV6_RECVPKTINFO:
11426 			if (!checkonly) {
11427 				mutex_enter(&connp->conn_lock);
11428 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11429 				mutex_exit(&connp->conn_lock);
11430 			}
11431 			break;	/* goto sizeof (int) option return */
11432 		case IPV6_RECVTCLASS:
11433 			if (!checkonly) {
11434 				if (*i1 < 0 || *i1 > 1) {
11435 					return (EINVAL);
11436 				}
11437 				mutex_enter(&connp->conn_lock);
11438 				connp->conn_ipv6_recvtclass = *i1;
11439 				mutex_exit(&connp->conn_lock);
11440 			}
11441 			break;
11442 		case IPV6_RECVPATHMTU:
11443 			if (!checkonly) {
11444 				if (*i1 < 0 || *i1 > 1) {
11445 					return (EINVAL);
11446 				}
11447 				mutex_enter(&connp->conn_lock);
11448 				connp->conn_ipv6_recvpathmtu = *i1;
11449 				mutex_exit(&connp->conn_lock);
11450 			}
11451 			break;
11452 		case IPV6_RECVHOPLIMIT:
11453 			if (!checkonly) {
11454 				mutex_enter(&connp->conn_lock);
11455 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11456 				mutex_exit(&connp->conn_lock);
11457 			}
11458 			break;	/* goto sizeof (int) option return */
11459 		case IPV6_RECVHOPOPTS:
11460 			if (!checkonly) {
11461 				mutex_enter(&connp->conn_lock);
11462 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11463 				mutex_exit(&connp->conn_lock);
11464 			}
11465 			break;	/* goto sizeof (int) option return */
11466 		case IPV6_RECVDSTOPTS:
11467 			if (!checkonly) {
11468 				mutex_enter(&connp->conn_lock);
11469 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11470 				mutex_exit(&connp->conn_lock);
11471 			}
11472 			break;	/* goto sizeof (int) option return */
11473 		case IPV6_RECVRTHDR:
11474 			if (!checkonly) {
11475 				mutex_enter(&connp->conn_lock);
11476 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11477 				mutex_exit(&connp->conn_lock);
11478 			}
11479 			break;	/* goto sizeof (int) option return */
11480 		case IPV6_RECVRTHDRDSTOPTS:
11481 			if (!checkonly) {
11482 				mutex_enter(&connp->conn_lock);
11483 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11484 				mutex_exit(&connp->conn_lock);
11485 			}
11486 			break;	/* goto sizeof (int) option return */
11487 		case IPV6_PKTINFO:
11488 			if (inlen == 0)
11489 				return (-EINVAL);	/* clearing option */
11490 			error = ip6_set_pktinfo(cr, connp,
11491 			    (struct in6_pktinfo *)invalp, first_mp);
11492 			if (error != 0)
11493 				*outlenp = 0;
11494 			else
11495 				*outlenp = inlen;
11496 			return (error);
11497 		case IPV6_NEXTHOP: {
11498 			struct sockaddr_in6 *sin6;
11499 
11500 			/* Verify that the nexthop is reachable */
11501 			if (inlen == 0)
11502 				return (-EINVAL);	/* clearing option */
11503 
11504 			sin6 = (struct sockaddr_in6 *)invalp;
11505 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11506 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11507 			    NULL, MATCH_IRE_DEFAULT, ipst);
11508 
11509 			if (ire == NULL) {
11510 				*outlenp = 0;
11511 				return (EHOSTUNREACH);
11512 			}
11513 			ire_refrele(ire);
11514 			return (-EINVAL);
11515 		}
11516 		case IPV6_SEC_OPT:
11517 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11518 			if (error != 0) {
11519 				*outlenp = 0;
11520 				return (error);
11521 			}
11522 			break;
11523 		case IPV6_SRC_PREFERENCES: {
11524 			/*
11525 			 * This is implemented strictly in the ip module
11526 			 * (here and in tcp_opt_*() to accomodate tcp
11527 			 * sockets).  Modules above ip pass this option
11528 			 * down here since ip is the only one that needs to
11529 			 * be aware of source address preferences.
11530 			 *
11531 			 * This socket option only affects connected
11532 			 * sockets that haven't already bound to a specific
11533 			 * IPv6 address.  In other words, sockets that
11534 			 * don't call bind() with an address other than the
11535 			 * unspecified address and that call connect().
11536 			 * ip_bind_connected_v6() passes these preferences
11537 			 * to the ipif_select_source_v6() function.
11538 			 */
11539 			if (inlen != sizeof (uint32_t))
11540 				return (EINVAL);
11541 			error = ip6_set_src_preferences(connp,
11542 			    *(uint32_t *)invalp);
11543 			if (error != 0) {
11544 				*outlenp = 0;
11545 				return (error);
11546 			} else {
11547 				*outlenp = sizeof (uint32_t);
11548 			}
11549 			break;
11550 		}
11551 		case IPV6_V6ONLY:
11552 			if (*i1 < 0 || *i1 > 1) {
11553 				return (EINVAL);
11554 			}
11555 			mutex_enter(&connp->conn_lock);
11556 			connp->conn_ipv6_v6only = *i1;
11557 			mutex_exit(&connp->conn_lock);
11558 			break;
11559 		default:
11560 			return (-EINVAL);
11561 		}
11562 		break;
11563 	default:
11564 		/*
11565 		 * "soft" error (negative)
11566 		 * option not handled at this level
11567 		 * Note: Do not modify *outlenp
11568 		 */
11569 		return (-EINVAL);
11570 	}
11571 	/*
11572 	 * Common case of return from an option that is sizeof (int)
11573 	 */
11574 	*(int *)outvalp = *i1;
11575 	*outlenp = sizeof (int);
11576 	return (0);
11577 }
11578 
11579 /*
11580  * This routine gets default values of certain options whose default
11581  * values are maintained by protocol specific code
11582  */
11583 /* ARGSUSED */
11584 int
11585 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11586 {
11587 	int *i1 = (int *)ptr;
11588 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11589 
11590 	switch (level) {
11591 	case IPPROTO_IP:
11592 		switch (name) {
11593 		case IP_MULTICAST_TTL:
11594 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11595 			return (sizeof (uchar_t));
11596 		case IP_MULTICAST_LOOP:
11597 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11598 			return (sizeof (uchar_t));
11599 		default:
11600 			return (-1);
11601 		}
11602 	case IPPROTO_IPV6:
11603 		switch (name) {
11604 		case IPV6_UNICAST_HOPS:
11605 			*i1 = ipst->ips_ipv6_def_hops;
11606 			return (sizeof (int));
11607 		case IPV6_MULTICAST_HOPS:
11608 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11609 			return (sizeof (int));
11610 		case IPV6_MULTICAST_LOOP:
11611 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11612 			return (sizeof (int));
11613 		case IPV6_V6ONLY:
11614 			*i1 = 1;
11615 			return (sizeof (int));
11616 		default:
11617 			return (-1);
11618 		}
11619 	default:
11620 		return (-1);
11621 	}
11622 	/* NOTREACHED */
11623 }
11624 
11625 /*
11626  * Given a destination address and a pointer to where to put the information
11627  * this routine fills in the mtuinfo.
11628  */
11629 int
11630 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11631     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11632 {
11633 	ire_t *ire;
11634 	ip_stack_t	*ipst = ns->netstack_ip;
11635 
11636 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11637 		return (-1);
11638 
11639 	bzero(mtuinfo, sizeof (*mtuinfo));
11640 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11641 	mtuinfo->ip6m_addr.sin6_port = port;
11642 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11643 
11644 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11645 	if (ire != NULL) {
11646 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11647 		ire_refrele(ire);
11648 	} else {
11649 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11650 	}
11651 	return (sizeof (struct ip6_mtuinfo));
11652 }
11653 
11654 /*
11655  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11656  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11657  * isn't.  This doesn't matter as the error checking is done properly for the
11658  * other MRT options coming in through ip_opt_set.
11659  */
11660 int
11661 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11662 {
11663 	conn_t		*connp = Q_TO_CONN(q);
11664 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11665 
11666 	switch (level) {
11667 	case IPPROTO_IP:
11668 		switch (name) {
11669 		case MRT_VERSION:
11670 		case MRT_ASSERT:
11671 			(void) ip_mrouter_get(name, q, ptr);
11672 			return (sizeof (int));
11673 		case IP_SEC_OPT:
11674 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11675 		case IP_NEXTHOP:
11676 			if (connp->conn_nexthop_set) {
11677 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11678 				return (sizeof (ipaddr_t));
11679 			} else
11680 				return (0);
11681 		case IP_RECVPKTINFO:
11682 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11683 			return (sizeof (int));
11684 		default:
11685 			break;
11686 		}
11687 		break;
11688 	case IPPROTO_IPV6:
11689 		switch (name) {
11690 		case IPV6_SEC_OPT:
11691 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11692 		case IPV6_SRC_PREFERENCES: {
11693 			return (ip6_get_src_preferences(connp,
11694 			    (uint32_t *)ptr));
11695 		}
11696 		case IPV6_V6ONLY:
11697 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11698 			return (sizeof (int));
11699 		case IPV6_PATHMTU:
11700 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11701 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11702 		default:
11703 			break;
11704 		}
11705 		break;
11706 	default:
11707 		break;
11708 	}
11709 	return (-1);
11710 }
11711 /* Named Dispatch routine to get a current value out of our parameter table. */
11712 /* ARGSUSED */
11713 static int
11714 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11715 {
11716 	ipparam_t *ippa = (ipparam_t *)cp;
11717 
11718 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11719 	return (0);
11720 }
11721 
11722 /* ARGSUSED */
11723 static int
11724 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11725 {
11726 
11727 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11728 	return (0);
11729 }
11730 
11731 /*
11732  * Set ip{,6}_forwarding values.  This means walking through all of the
11733  * ill's and toggling their forwarding values.
11734  */
11735 /* ARGSUSED */
11736 static int
11737 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11738 {
11739 	long new_value;
11740 	int *forwarding_value = (int *)cp;
11741 	ill_t *ill;
11742 	boolean_t isv6;
11743 	ill_walk_context_t ctx;
11744 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11745 
11746 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11747 
11748 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11749 	    new_value < 0 || new_value > 1) {
11750 		return (EINVAL);
11751 	}
11752 
11753 	*forwarding_value = new_value;
11754 
11755 	/*
11756 	 * Regardless of the current value of ip_forwarding, set all per-ill
11757 	 * values of ip_forwarding to the value being set.
11758 	 *
11759 	 * Bring all the ill's up to date with the new global value.
11760 	 */
11761 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11762 
11763 	if (isv6)
11764 		ill = ILL_START_WALK_V6(&ctx, ipst);
11765 	else
11766 		ill = ILL_START_WALK_V4(&ctx, ipst);
11767 
11768 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11769 		(void) ill_forward_set(ill, new_value != 0);
11770 
11771 	rw_exit(&ipst->ips_ill_g_lock);
11772 	return (0);
11773 }
11774 
11775 /*
11776  * Walk through the param array specified registering each element with the
11777  * Named Dispatch handler. This is called only during init. So it is ok
11778  * not to acquire any locks
11779  */
11780 static boolean_t
11781 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11782     ipndp_t *ipnd, size_t ipnd_cnt)
11783 {
11784 	for (; ippa_cnt-- > 0; ippa++) {
11785 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11786 			if (!nd_load(ndp, ippa->ip_param_name,
11787 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11788 				nd_free(ndp);
11789 				return (B_FALSE);
11790 			}
11791 		}
11792 	}
11793 
11794 	for (; ipnd_cnt-- > 0; ipnd++) {
11795 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11796 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11797 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11798 			    ipnd->ip_ndp_data)) {
11799 				nd_free(ndp);
11800 				return (B_FALSE);
11801 			}
11802 		}
11803 	}
11804 
11805 	return (B_TRUE);
11806 }
11807 
11808 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11809 /* ARGSUSED */
11810 static int
11811 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11812 {
11813 	long		new_value;
11814 	ipparam_t	*ippa = (ipparam_t *)cp;
11815 
11816 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11817 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11818 		return (EINVAL);
11819 	}
11820 	ippa->ip_param_value = new_value;
11821 	return (0);
11822 }
11823 
11824 /*
11825  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11826  * When an ipf is passed here for the first time, if
11827  * we already have in-order fragments on the queue, we convert from the fast-
11828  * path reassembly scheme to the hard-case scheme.  From then on, additional
11829  * fragments are reassembled here.  We keep track of the start and end offsets
11830  * of each piece, and the number of holes in the chain.  When the hole count
11831  * goes to zero, we are done!
11832  *
11833  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11834  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11835  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11836  * after the call to ip_reassemble().
11837  */
11838 int
11839 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11840     size_t msg_len)
11841 {
11842 	uint_t	end;
11843 	mblk_t	*next_mp;
11844 	mblk_t	*mp1;
11845 	uint_t	offset;
11846 	boolean_t incr_dups = B_TRUE;
11847 	boolean_t offset_zero_seen = B_FALSE;
11848 	boolean_t pkt_boundary_checked = B_FALSE;
11849 
11850 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11851 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11852 
11853 	/* Add in byte count */
11854 	ipf->ipf_count += msg_len;
11855 	if (ipf->ipf_end) {
11856 		/*
11857 		 * We were part way through in-order reassembly, but now there
11858 		 * is a hole.  We walk through messages already queued, and
11859 		 * mark them for hard case reassembly.  We know that up till
11860 		 * now they were in order starting from offset zero.
11861 		 */
11862 		offset = 0;
11863 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11864 			IP_REASS_SET_START(mp1, offset);
11865 			if (offset == 0) {
11866 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11867 				offset = -ipf->ipf_nf_hdr_len;
11868 			}
11869 			offset += mp1->b_wptr - mp1->b_rptr;
11870 			IP_REASS_SET_END(mp1, offset);
11871 		}
11872 		/* One hole at the end. */
11873 		ipf->ipf_hole_cnt = 1;
11874 		/* Brand it as a hard case, forever. */
11875 		ipf->ipf_end = 0;
11876 	}
11877 	/* Walk through all the new pieces. */
11878 	do {
11879 		end = start + (mp->b_wptr - mp->b_rptr);
11880 		/*
11881 		 * If start is 0, decrease 'end' only for the first mblk of
11882 		 * the fragment. Otherwise 'end' can get wrong value in the
11883 		 * second pass of the loop if first mblk is exactly the
11884 		 * size of ipf_nf_hdr_len.
11885 		 */
11886 		if (start == 0 && !offset_zero_seen) {
11887 			/* First segment */
11888 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11889 			end -= ipf->ipf_nf_hdr_len;
11890 			offset_zero_seen = B_TRUE;
11891 		}
11892 		next_mp = mp->b_cont;
11893 		/*
11894 		 * We are checking to see if there is any interesing data
11895 		 * to process.  If there isn't and the mblk isn't the
11896 		 * one which carries the unfragmentable header then we
11897 		 * drop it.  It's possible to have just the unfragmentable
11898 		 * header come through without any data.  That needs to be
11899 		 * saved.
11900 		 *
11901 		 * If the assert at the top of this function holds then the
11902 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11903 		 * is infrequently traveled enough that the test is left in
11904 		 * to protect against future code changes which break that
11905 		 * invariant.
11906 		 */
11907 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11908 			/* Empty.  Blast it. */
11909 			IP_REASS_SET_START(mp, 0);
11910 			IP_REASS_SET_END(mp, 0);
11911 			/*
11912 			 * If the ipf points to the mblk we are about to free,
11913 			 * update ipf to point to the next mblk (or NULL
11914 			 * if none).
11915 			 */
11916 			if (ipf->ipf_mp->b_cont == mp)
11917 				ipf->ipf_mp->b_cont = next_mp;
11918 			freeb(mp);
11919 			continue;
11920 		}
11921 		mp->b_cont = NULL;
11922 		IP_REASS_SET_START(mp, start);
11923 		IP_REASS_SET_END(mp, end);
11924 		if (!ipf->ipf_tail_mp) {
11925 			ipf->ipf_tail_mp = mp;
11926 			ipf->ipf_mp->b_cont = mp;
11927 			if (start == 0 || !more) {
11928 				ipf->ipf_hole_cnt = 1;
11929 				/*
11930 				 * if the first fragment comes in more than one
11931 				 * mblk, this loop will be executed for each
11932 				 * mblk. Need to adjust hole count so exiting
11933 				 * this routine will leave hole count at 1.
11934 				 */
11935 				if (next_mp)
11936 					ipf->ipf_hole_cnt++;
11937 			} else
11938 				ipf->ipf_hole_cnt = 2;
11939 			continue;
11940 		} else if (ipf->ipf_last_frag_seen && !more &&
11941 		    !pkt_boundary_checked) {
11942 			/*
11943 			 * We check datagram boundary only if this fragment
11944 			 * claims to be the last fragment and we have seen a
11945 			 * last fragment in the past too. We do this only
11946 			 * once for a given fragment.
11947 			 *
11948 			 * start cannot be 0 here as fragments with start=0
11949 			 * and MF=0 gets handled as a complete packet. These
11950 			 * fragments should not reach here.
11951 			 */
11952 
11953 			if (start + msgdsize(mp) !=
11954 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11955 				/*
11956 				 * We have two fragments both of which claim
11957 				 * to be the last fragment but gives conflicting
11958 				 * information about the whole datagram size.
11959 				 * Something fishy is going on. Drop the
11960 				 * fragment and free up the reassembly list.
11961 				 */
11962 				return (IP_REASS_FAILED);
11963 			}
11964 
11965 			/*
11966 			 * We shouldn't come to this code block again for this
11967 			 * particular fragment.
11968 			 */
11969 			pkt_boundary_checked = B_TRUE;
11970 		}
11971 
11972 		/* New stuff at or beyond tail? */
11973 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11974 		if (start >= offset) {
11975 			if (ipf->ipf_last_frag_seen) {
11976 				/* current fragment is beyond last fragment */
11977 				return (IP_REASS_FAILED);
11978 			}
11979 			/* Link it on end. */
11980 			ipf->ipf_tail_mp->b_cont = mp;
11981 			ipf->ipf_tail_mp = mp;
11982 			if (more) {
11983 				if (start != offset)
11984 					ipf->ipf_hole_cnt++;
11985 			} else if (start == offset && next_mp == NULL)
11986 					ipf->ipf_hole_cnt--;
11987 			continue;
11988 		}
11989 		mp1 = ipf->ipf_mp->b_cont;
11990 		offset = IP_REASS_START(mp1);
11991 		/* New stuff at the front? */
11992 		if (start < offset) {
11993 			if (start == 0) {
11994 				if (end >= offset) {
11995 					/* Nailed the hole at the begining. */
11996 					ipf->ipf_hole_cnt--;
11997 				}
11998 			} else if (end < offset) {
11999 				/*
12000 				 * A hole, stuff, and a hole where there used
12001 				 * to be just a hole.
12002 				 */
12003 				ipf->ipf_hole_cnt++;
12004 			}
12005 			mp->b_cont = mp1;
12006 			/* Check for overlap. */
12007 			while (end > offset) {
12008 				if (end < IP_REASS_END(mp1)) {
12009 					mp->b_wptr -= end - offset;
12010 					IP_REASS_SET_END(mp, offset);
12011 					BUMP_MIB(ill->ill_ip_mib,
12012 					    ipIfStatsReasmPartDups);
12013 					break;
12014 				}
12015 				/* Did we cover another hole? */
12016 				if ((mp1->b_cont &&
12017 				    IP_REASS_END(mp1) !=
12018 				    IP_REASS_START(mp1->b_cont) &&
12019 				    end >= IP_REASS_START(mp1->b_cont)) ||
12020 				    (!ipf->ipf_last_frag_seen && !more)) {
12021 					ipf->ipf_hole_cnt--;
12022 				}
12023 				/* Clip out mp1. */
12024 				if ((mp->b_cont = mp1->b_cont) == NULL) {
12025 					/*
12026 					 * After clipping out mp1, this guy
12027 					 * is now hanging off the end.
12028 					 */
12029 					ipf->ipf_tail_mp = mp;
12030 				}
12031 				IP_REASS_SET_START(mp1, 0);
12032 				IP_REASS_SET_END(mp1, 0);
12033 				/* Subtract byte count */
12034 				ipf->ipf_count -= mp1->b_datap->db_lim -
12035 				    mp1->b_datap->db_base;
12036 				freeb(mp1);
12037 				BUMP_MIB(ill->ill_ip_mib,
12038 				    ipIfStatsReasmPartDups);
12039 				mp1 = mp->b_cont;
12040 				if (!mp1)
12041 					break;
12042 				offset = IP_REASS_START(mp1);
12043 			}
12044 			ipf->ipf_mp->b_cont = mp;
12045 			continue;
12046 		}
12047 		/*
12048 		 * The new piece starts somewhere between the start of the head
12049 		 * and before the end of the tail.
12050 		 */
12051 		for (; mp1; mp1 = mp1->b_cont) {
12052 			offset = IP_REASS_END(mp1);
12053 			if (start < offset) {
12054 				if (end <= offset) {
12055 					/* Nothing new. */
12056 					IP_REASS_SET_START(mp, 0);
12057 					IP_REASS_SET_END(mp, 0);
12058 					/* Subtract byte count */
12059 					ipf->ipf_count -= mp->b_datap->db_lim -
12060 					    mp->b_datap->db_base;
12061 					if (incr_dups) {
12062 						ipf->ipf_num_dups++;
12063 						incr_dups = B_FALSE;
12064 					}
12065 					freeb(mp);
12066 					BUMP_MIB(ill->ill_ip_mib,
12067 					    ipIfStatsReasmDuplicates);
12068 					break;
12069 				}
12070 				/*
12071 				 * Trim redundant stuff off beginning of new
12072 				 * piece.
12073 				 */
12074 				IP_REASS_SET_START(mp, offset);
12075 				mp->b_rptr += offset - start;
12076 				BUMP_MIB(ill->ill_ip_mib,
12077 				    ipIfStatsReasmPartDups);
12078 				start = offset;
12079 				if (!mp1->b_cont) {
12080 					/*
12081 					 * After trimming, this guy is now
12082 					 * hanging off the end.
12083 					 */
12084 					mp1->b_cont = mp;
12085 					ipf->ipf_tail_mp = mp;
12086 					if (!more) {
12087 						ipf->ipf_hole_cnt--;
12088 					}
12089 					break;
12090 				}
12091 			}
12092 			if (start >= IP_REASS_START(mp1->b_cont))
12093 				continue;
12094 			/* Fill a hole */
12095 			if (start > offset)
12096 				ipf->ipf_hole_cnt++;
12097 			mp->b_cont = mp1->b_cont;
12098 			mp1->b_cont = mp;
12099 			mp1 = mp->b_cont;
12100 			offset = IP_REASS_START(mp1);
12101 			if (end >= offset) {
12102 				ipf->ipf_hole_cnt--;
12103 				/* Check for overlap. */
12104 				while (end > offset) {
12105 					if (end < IP_REASS_END(mp1)) {
12106 						mp->b_wptr -= end - offset;
12107 						IP_REASS_SET_END(mp, offset);
12108 						/*
12109 						 * TODO we might bump
12110 						 * this up twice if there is
12111 						 * overlap at both ends.
12112 						 */
12113 						BUMP_MIB(ill->ill_ip_mib,
12114 						    ipIfStatsReasmPartDups);
12115 						break;
12116 					}
12117 					/* Did we cover another hole? */
12118 					if ((mp1->b_cont &&
12119 					    IP_REASS_END(mp1)
12120 					    != IP_REASS_START(mp1->b_cont) &&
12121 					    end >=
12122 					    IP_REASS_START(mp1->b_cont)) ||
12123 					    (!ipf->ipf_last_frag_seen &&
12124 					    !more)) {
12125 						ipf->ipf_hole_cnt--;
12126 					}
12127 					/* Clip out mp1. */
12128 					if ((mp->b_cont = mp1->b_cont) ==
12129 					    NULL) {
12130 						/*
12131 						 * After clipping out mp1,
12132 						 * this guy is now hanging
12133 						 * off the end.
12134 						 */
12135 						ipf->ipf_tail_mp = mp;
12136 					}
12137 					IP_REASS_SET_START(mp1, 0);
12138 					IP_REASS_SET_END(mp1, 0);
12139 					/* Subtract byte count */
12140 					ipf->ipf_count -=
12141 					    mp1->b_datap->db_lim -
12142 					    mp1->b_datap->db_base;
12143 					freeb(mp1);
12144 					BUMP_MIB(ill->ill_ip_mib,
12145 					    ipIfStatsReasmPartDups);
12146 					mp1 = mp->b_cont;
12147 					if (!mp1)
12148 						break;
12149 					offset = IP_REASS_START(mp1);
12150 				}
12151 			}
12152 			break;
12153 		}
12154 	} while (start = end, mp = next_mp);
12155 
12156 	/* Fragment just processed could be the last one. Remember this fact */
12157 	if (!more)
12158 		ipf->ipf_last_frag_seen = B_TRUE;
12159 
12160 	/* Still got holes? */
12161 	if (ipf->ipf_hole_cnt)
12162 		return (IP_REASS_PARTIAL);
12163 	/* Clean up overloaded fields to avoid upstream disasters. */
12164 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12165 		IP_REASS_SET_START(mp1, 0);
12166 		IP_REASS_SET_END(mp1, 0);
12167 	}
12168 	return (IP_REASS_COMPLETE);
12169 }
12170 
12171 /*
12172  * ipsec processing for the fast path, used for input UDP Packets
12173  * Returns true if ready for passup to UDP.
12174  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12175  * was an ESP-in-UDP packet, etc.).
12176  */
12177 static boolean_t
12178 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12179     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12180 {
12181 	uint32_t	ill_index;
12182 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12183 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12184 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12185 	udp_t		*udp = connp->conn_udp;
12186 
12187 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12188 	/* The ill_index of the incoming ILL */
12189 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12190 
12191 	/* pass packet up to the transport */
12192 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12193 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12194 		    NULL, mctl_present);
12195 		if (*first_mpp == NULL) {
12196 			return (B_FALSE);
12197 		}
12198 	}
12199 
12200 	/* Initiate IPPF processing for fastpath UDP */
12201 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12202 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12203 		if (*mpp == NULL) {
12204 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12205 			    "deferred/dropped during IPPF processing\n"));
12206 			return (B_FALSE);
12207 		}
12208 	}
12209 	/*
12210 	 * Remove 0-spi if it's 0, or move everything behind
12211 	 * the UDP header over it and forward to ESP via
12212 	 * ip_proto_input().
12213 	 */
12214 	if (udp->udp_nat_t_endpoint) {
12215 		if (mctl_present) {
12216 			/* mctl_present *shouldn't* happen. */
12217 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12218 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12219 			    &ipss->ipsec_dropper);
12220 			*first_mpp = NULL;
12221 			return (B_FALSE);
12222 		}
12223 
12224 		/* "ill" is "recv_ill" in actuality. */
12225 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12226 			return (B_FALSE);
12227 
12228 		/* Else continue like a normal UDP packet. */
12229 	}
12230 
12231 	/*
12232 	 * We make the checks as below since we are in the fast path
12233 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12234 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12235 	 */
12236 	if (connp->conn_recvif || connp->conn_recvslla ||
12237 	    connp->conn_ip_recvpktinfo) {
12238 		if (connp->conn_recvif) {
12239 			in_flags = IPF_RECVIF;
12240 		}
12241 		/*
12242 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12243 		 * so the flag passed to ip_add_info is based on IP version
12244 		 * of connp.
12245 		 */
12246 		if (connp->conn_ip_recvpktinfo) {
12247 			if (connp->conn_af_isv6) {
12248 				/*
12249 				 * V6 only needs index
12250 				 */
12251 				in_flags |= IPF_RECVIF;
12252 			} else {
12253 				/*
12254 				 * V4 needs index + matching address.
12255 				 */
12256 				in_flags |= IPF_RECVADDR;
12257 			}
12258 		}
12259 		if (connp->conn_recvslla) {
12260 			in_flags |= IPF_RECVSLLA;
12261 		}
12262 		/*
12263 		 * since in_flags are being set ill will be
12264 		 * referenced in ip_add_info, so it better not
12265 		 * be NULL.
12266 		 */
12267 		/*
12268 		 * the actual data will be contained in b_cont
12269 		 * upon successful return of the following call.
12270 		 * If the call fails then the original mblk is
12271 		 * returned.
12272 		 */
12273 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12274 		    ipst);
12275 	}
12276 
12277 	return (B_TRUE);
12278 }
12279 
12280 /*
12281  * Fragmentation reassembly.  Each ILL has a hash table for
12282  * queuing packets undergoing reassembly for all IPIFs
12283  * associated with the ILL.  The hash is based on the packet
12284  * IP ident field.  The ILL frag hash table was allocated
12285  * as a timer block at the time the ILL was created.  Whenever
12286  * there is anything on the reassembly queue, the timer will
12287  * be running.  Returns B_TRUE if successful else B_FALSE;
12288  * frees mp on failure.
12289  */
12290 static boolean_t
12291 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12292     uint32_t *cksum_val, uint16_t *cksum_flags)
12293 {
12294 	uint32_t	frag_offset_flags;
12295 	ill_t		*ill = (ill_t *)q->q_ptr;
12296 	mblk_t		*mp = *mpp;
12297 	mblk_t		*t_mp;
12298 	ipaddr_t	dst;
12299 	uint8_t		proto = ipha->ipha_protocol;
12300 	uint32_t	sum_val;
12301 	uint16_t	sum_flags;
12302 	ipf_t		*ipf;
12303 	ipf_t		**ipfp;
12304 	ipfb_t		*ipfb;
12305 	uint16_t	ident;
12306 	uint32_t	offset;
12307 	ipaddr_t	src;
12308 	uint_t		hdr_length;
12309 	uint32_t	end;
12310 	mblk_t		*mp1;
12311 	mblk_t		*tail_mp;
12312 	size_t		count;
12313 	size_t		msg_len;
12314 	uint8_t		ecn_info = 0;
12315 	uint32_t	packet_size;
12316 	boolean_t	pruned = B_FALSE;
12317 	ip_stack_t *ipst = ill->ill_ipst;
12318 
12319 	if (cksum_val != NULL)
12320 		*cksum_val = 0;
12321 	if (cksum_flags != NULL)
12322 		*cksum_flags = 0;
12323 
12324 	/*
12325 	 * Drop the fragmented as early as possible, if
12326 	 * we don't have resource(s) to re-assemble.
12327 	 */
12328 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12329 		freemsg(mp);
12330 		return (B_FALSE);
12331 	}
12332 
12333 	/* Check for fragmentation offset; return if there's none */
12334 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12335 	    (IPH_MF | IPH_OFFSET)) == 0)
12336 		return (B_TRUE);
12337 
12338 	/*
12339 	 * We utilize hardware computed checksum info only for UDP since
12340 	 * IP fragmentation is a normal occurence for the protocol.  In
12341 	 * addition, checksum offload support for IP fragments carrying
12342 	 * UDP payload is commonly implemented across network adapters.
12343 	 */
12344 	ASSERT(ill != NULL);
12345 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12346 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12347 		mblk_t *mp1 = mp->b_cont;
12348 		int32_t len;
12349 
12350 		/* Record checksum information from the packet */
12351 		sum_val = (uint32_t)DB_CKSUM16(mp);
12352 		sum_flags = DB_CKSUMFLAGS(mp);
12353 
12354 		/* IP payload offset from beginning of mblk */
12355 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12356 
12357 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12358 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12359 		    offset >= DB_CKSUMSTART(mp) &&
12360 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12361 			uint32_t adj;
12362 			/*
12363 			 * Partial checksum has been calculated by hardware
12364 			 * and attached to the packet; in addition, any
12365 			 * prepended extraneous data is even byte aligned.
12366 			 * If any such data exists, we adjust the checksum;
12367 			 * this would also handle any postpended data.
12368 			 */
12369 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12370 			    mp, mp1, len, adj);
12371 
12372 			/* One's complement subtract extraneous checksum */
12373 			if (adj >= sum_val)
12374 				sum_val = ~(adj - sum_val) & 0xFFFF;
12375 			else
12376 				sum_val -= adj;
12377 		}
12378 	} else {
12379 		sum_val = 0;
12380 		sum_flags = 0;
12381 	}
12382 
12383 	/* Clear hardware checksumming flag */
12384 	DB_CKSUMFLAGS(mp) = 0;
12385 
12386 	ident = ipha->ipha_ident;
12387 	offset = (frag_offset_flags << 3) & 0xFFFF;
12388 	src = ipha->ipha_src;
12389 	dst = ipha->ipha_dst;
12390 	hdr_length = IPH_HDR_LENGTH(ipha);
12391 	end = ntohs(ipha->ipha_length) - hdr_length;
12392 
12393 	/* If end == 0 then we have a packet with no data, so just free it */
12394 	if (end == 0) {
12395 		freemsg(mp);
12396 		return (B_FALSE);
12397 	}
12398 
12399 	/* Record the ECN field info. */
12400 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12401 	if (offset != 0) {
12402 		/*
12403 		 * If this isn't the first piece, strip the header, and
12404 		 * add the offset to the end value.
12405 		 */
12406 		mp->b_rptr += hdr_length;
12407 		end += offset;
12408 	}
12409 
12410 	msg_len = MBLKSIZE(mp);
12411 	tail_mp = mp;
12412 	while (tail_mp->b_cont != NULL) {
12413 		tail_mp = tail_mp->b_cont;
12414 		msg_len += MBLKSIZE(tail_mp);
12415 	}
12416 
12417 	/* If the reassembly list for this ILL will get too big, prune it */
12418 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12419 	    ipst->ips_ip_reass_queue_bytes) {
12420 		ill_frag_prune(ill,
12421 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12422 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12423 		pruned = B_TRUE;
12424 	}
12425 
12426 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12427 	mutex_enter(&ipfb->ipfb_lock);
12428 
12429 	ipfp = &ipfb->ipfb_ipf;
12430 	/* Try to find an existing fragment queue for this packet. */
12431 	for (;;) {
12432 		ipf = ipfp[0];
12433 		if (ipf != NULL) {
12434 			/*
12435 			 * It has to match on ident and src/dst address.
12436 			 */
12437 			if (ipf->ipf_ident == ident &&
12438 			    ipf->ipf_src == src &&
12439 			    ipf->ipf_dst == dst &&
12440 			    ipf->ipf_protocol == proto) {
12441 				/*
12442 				 * If we have received too many
12443 				 * duplicate fragments for this packet
12444 				 * free it.
12445 				 */
12446 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12447 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12448 					freemsg(mp);
12449 					mutex_exit(&ipfb->ipfb_lock);
12450 					return (B_FALSE);
12451 				}
12452 				/* Found it. */
12453 				break;
12454 			}
12455 			ipfp = &ipf->ipf_hash_next;
12456 			continue;
12457 		}
12458 
12459 		/*
12460 		 * If we pruned the list, do we want to store this new
12461 		 * fragment?. We apply an optimization here based on the
12462 		 * fact that most fragments will be received in order.
12463 		 * So if the offset of this incoming fragment is zero,
12464 		 * it is the first fragment of a new packet. We will
12465 		 * keep it.  Otherwise drop the fragment, as we have
12466 		 * probably pruned the packet already (since the
12467 		 * packet cannot be found).
12468 		 */
12469 		if (pruned && offset != 0) {
12470 			mutex_exit(&ipfb->ipfb_lock);
12471 			freemsg(mp);
12472 			return (B_FALSE);
12473 		}
12474 
12475 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12476 			/*
12477 			 * Too many fragmented packets in this hash
12478 			 * bucket. Free the oldest.
12479 			 */
12480 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12481 		}
12482 
12483 		/* New guy.  Allocate a frag message. */
12484 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12485 		if (mp1 == NULL) {
12486 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12487 			freemsg(mp);
12488 reass_done:
12489 			mutex_exit(&ipfb->ipfb_lock);
12490 			return (B_FALSE);
12491 		}
12492 
12493 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12494 		mp1->b_cont = mp;
12495 
12496 		/* Initialize the fragment header. */
12497 		ipf = (ipf_t *)mp1->b_rptr;
12498 		ipf->ipf_mp = mp1;
12499 		ipf->ipf_ptphn = ipfp;
12500 		ipfp[0] = ipf;
12501 		ipf->ipf_hash_next = NULL;
12502 		ipf->ipf_ident = ident;
12503 		ipf->ipf_protocol = proto;
12504 		ipf->ipf_src = src;
12505 		ipf->ipf_dst = dst;
12506 		ipf->ipf_nf_hdr_len = 0;
12507 		/* Record reassembly start time. */
12508 		ipf->ipf_timestamp = gethrestime_sec();
12509 		/* Record ipf generation and account for frag header */
12510 		ipf->ipf_gen = ill->ill_ipf_gen++;
12511 		ipf->ipf_count = MBLKSIZE(mp1);
12512 		ipf->ipf_last_frag_seen = B_FALSE;
12513 		ipf->ipf_ecn = ecn_info;
12514 		ipf->ipf_num_dups = 0;
12515 		ipfb->ipfb_frag_pkts++;
12516 		ipf->ipf_checksum = 0;
12517 		ipf->ipf_checksum_flags = 0;
12518 
12519 		/* Store checksum value in fragment header */
12520 		if (sum_flags != 0) {
12521 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12522 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12523 			ipf->ipf_checksum = sum_val;
12524 			ipf->ipf_checksum_flags = sum_flags;
12525 		}
12526 
12527 		/*
12528 		 * We handle reassembly two ways.  In the easy case,
12529 		 * where all the fragments show up in order, we do
12530 		 * minimal bookkeeping, and just clip new pieces on
12531 		 * the end.  If we ever see a hole, then we go off
12532 		 * to ip_reassemble which has to mark the pieces and
12533 		 * keep track of the number of holes, etc.  Obviously,
12534 		 * the point of having both mechanisms is so we can
12535 		 * handle the easy case as efficiently as possible.
12536 		 */
12537 		if (offset == 0) {
12538 			/* Easy case, in-order reassembly so far. */
12539 			ipf->ipf_count += msg_len;
12540 			ipf->ipf_tail_mp = tail_mp;
12541 			/*
12542 			 * Keep track of next expected offset in
12543 			 * ipf_end.
12544 			 */
12545 			ipf->ipf_end = end;
12546 			ipf->ipf_nf_hdr_len = hdr_length;
12547 		} else {
12548 			/* Hard case, hole at the beginning. */
12549 			ipf->ipf_tail_mp = NULL;
12550 			/*
12551 			 * ipf_end == 0 means that we have given up
12552 			 * on easy reassembly.
12553 			 */
12554 			ipf->ipf_end = 0;
12555 
12556 			/* Forget checksum offload from now on */
12557 			ipf->ipf_checksum_flags = 0;
12558 
12559 			/*
12560 			 * ipf_hole_cnt is set by ip_reassemble.
12561 			 * ipf_count is updated by ip_reassemble.
12562 			 * No need to check for return value here
12563 			 * as we don't expect reassembly to complete
12564 			 * or fail for the first fragment itself.
12565 			 */
12566 			(void) ip_reassemble(mp, ipf,
12567 			    (frag_offset_flags & IPH_OFFSET) << 3,
12568 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12569 		}
12570 		/* Update per ipfb and ill byte counts */
12571 		ipfb->ipfb_count += ipf->ipf_count;
12572 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12573 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
12574 		/* If the frag timer wasn't already going, start it. */
12575 		mutex_enter(&ill->ill_lock);
12576 		ill_frag_timer_start(ill);
12577 		mutex_exit(&ill->ill_lock);
12578 		goto reass_done;
12579 	}
12580 
12581 	/*
12582 	 * If the packet's flag has changed (it could be coming up
12583 	 * from an interface different than the previous, therefore
12584 	 * possibly different checksum capability), then forget about
12585 	 * any stored checksum states.  Otherwise add the value to
12586 	 * the existing one stored in the fragment header.
12587 	 */
12588 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12589 		sum_val += ipf->ipf_checksum;
12590 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12591 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12592 		ipf->ipf_checksum = sum_val;
12593 	} else if (ipf->ipf_checksum_flags != 0) {
12594 		/* Forget checksum offload from now on */
12595 		ipf->ipf_checksum_flags = 0;
12596 	}
12597 
12598 	/*
12599 	 * We have a new piece of a datagram which is already being
12600 	 * reassembled.  Update the ECN info if all IP fragments
12601 	 * are ECN capable.  If there is one which is not, clear
12602 	 * all the info.  If there is at least one which has CE
12603 	 * code point, IP needs to report that up to transport.
12604 	 */
12605 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12606 		if (ecn_info == IPH_ECN_CE)
12607 			ipf->ipf_ecn = IPH_ECN_CE;
12608 	} else {
12609 		ipf->ipf_ecn = IPH_ECN_NECT;
12610 	}
12611 	if (offset && ipf->ipf_end == offset) {
12612 		/* The new fragment fits at the end */
12613 		ipf->ipf_tail_mp->b_cont = mp;
12614 		/* Update the byte count */
12615 		ipf->ipf_count += msg_len;
12616 		/* Update per ipfb and ill byte counts */
12617 		ipfb->ipfb_count += msg_len;
12618 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12619 		atomic_add_32(&ill->ill_frag_count, msg_len);
12620 		if (frag_offset_flags & IPH_MF) {
12621 			/* More to come. */
12622 			ipf->ipf_end = end;
12623 			ipf->ipf_tail_mp = tail_mp;
12624 			goto reass_done;
12625 		}
12626 	} else {
12627 		/* Go do the hard cases. */
12628 		int ret;
12629 
12630 		if (offset == 0)
12631 			ipf->ipf_nf_hdr_len = hdr_length;
12632 
12633 		/* Save current byte count */
12634 		count = ipf->ipf_count;
12635 		ret = ip_reassemble(mp, ipf,
12636 		    (frag_offset_flags & IPH_OFFSET) << 3,
12637 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12638 		/* Count of bytes added and subtracted (freeb()ed) */
12639 		count = ipf->ipf_count - count;
12640 		if (count) {
12641 			/* Update per ipfb and ill byte counts */
12642 			ipfb->ipfb_count += count;
12643 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12644 			atomic_add_32(&ill->ill_frag_count, count);
12645 		}
12646 		if (ret == IP_REASS_PARTIAL) {
12647 			goto reass_done;
12648 		} else if (ret == IP_REASS_FAILED) {
12649 			/* Reassembly failed. Free up all resources */
12650 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12651 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12652 				IP_REASS_SET_START(t_mp, 0);
12653 				IP_REASS_SET_END(t_mp, 0);
12654 			}
12655 			freemsg(mp);
12656 			goto reass_done;
12657 		}
12658 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12659 	}
12660 	/*
12661 	 * We have completed reassembly.  Unhook the frag header from
12662 	 * the reassembly list.
12663 	 *
12664 	 * Before we free the frag header, record the ECN info
12665 	 * to report back to the transport.
12666 	 */
12667 	ecn_info = ipf->ipf_ecn;
12668 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12669 	ipfp = ipf->ipf_ptphn;
12670 
12671 	/* We need to supply these to caller */
12672 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12673 		sum_val = ipf->ipf_checksum;
12674 	else
12675 		sum_val = 0;
12676 
12677 	mp1 = ipf->ipf_mp;
12678 	count = ipf->ipf_count;
12679 	ipf = ipf->ipf_hash_next;
12680 	if (ipf != NULL)
12681 		ipf->ipf_ptphn = ipfp;
12682 	ipfp[0] = ipf;
12683 	atomic_add_32(&ill->ill_frag_count, -count);
12684 	ASSERT(ipfb->ipfb_count >= count);
12685 	ipfb->ipfb_count -= count;
12686 	ipfb->ipfb_frag_pkts--;
12687 	mutex_exit(&ipfb->ipfb_lock);
12688 	/* Ditch the frag header. */
12689 	mp = mp1->b_cont;
12690 
12691 	freeb(mp1);
12692 
12693 	/* Restore original IP length in header. */
12694 	packet_size = (uint32_t)msgdsize(mp);
12695 	if (packet_size > IP_MAXPACKET) {
12696 		freemsg(mp);
12697 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12698 		return (B_FALSE);
12699 	}
12700 
12701 	if (DB_REF(mp) > 1) {
12702 		mblk_t *mp2 = copymsg(mp);
12703 
12704 		freemsg(mp);
12705 		if (mp2 == NULL) {
12706 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12707 			return (B_FALSE);
12708 		}
12709 		mp = mp2;
12710 	}
12711 	ipha = (ipha_t *)mp->b_rptr;
12712 
12713 	ipha->ipha_length = htons((uint16_t)packet_size);
12714 	/* We're now complete, zip the frag state */
12715 	ipha->ipha_fragment_offset_and_flags = 0;
12716 	/* Record the ECN info. */
12717 	ipha->ipha_type_of_service &= 0xFC;
12718 	ipha->ipha_type_of_service |= ecn_info;
12719 	*mpp = mp;
12720 
12721 	/* Reassembly is successful; return checksum information if needed */
12722 	if (cksum_val != NULL)
12723 		*cksum_val = sum_val;
12724 	if (cksum_flags != NULL)
12725 		*cksum_flags = sum_flags;
12726 
12727 	return (B_TRUE);
12728 }
12729 
12730 /*
12731  * Perform ip header check sum update local options.
12732  * return B_TRUE if all is well, else return B_FALSE and release
12733  * the mp. caller is responsible for decrementing ire ref cnt.
12734  */
12735 static boolean_t
12736 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12737     ip_stack_t *ipst)
12738 {
12739 	mblk_t		*first_mp;
12740 	boolean_t	mctl_present;
12741 	uint16_t	sum;
12742 
12743 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12744 	/*
12745 	 * Don't do the checksum if it has gone through AH/ESP
12746 	 * processing.
12747 	 */
12748 	if (!mctl_present) {
12749 		sum = ip_csum_hdr(ipha);
12750 		if (sum != 0) {
12751 			if (ill != NULL) {
12752 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12753 			} else {
12754 				BUMP_MIB(&ipst->ips_ip_mib,
12755 				    ipIfStatsInCksumErrs);
12756 			}
12757 			freemsg(first_mp);
12758 			return (B_FALSE);
12759 		}
12760 	}
12761 
12762 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12763 		if (mctl_present)
12764 			freeb(first_mp);
12765 		return (B_FALSE);
12766 	}
12767 
12768 	return (B_TRUE);
12769 }
12770 
12771 /*
12772  * All udp packet are delivered to the local host via this routine.
12773  */
12774 void
12775 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12776     ill_t *recv_ill)
12777 {
12778 	uint32_t	sum;
12779 	uint32_t	u1;
12780 	boolean_t	mctl_present;
12781 	conn_t		*connp;
12782 	mblk_t		*first_mp;
12783 	uint16_t	*up;
12784 	ill_t		*ill = (ill_t *)q->q_ptr;
12785 	uint16_t	reass_hck_flags = 0;
12786 	ip_stack_t	*ipst;
12787 
12788 	ASSERT(recv_ill != NULL);
12789 	ipst = recv_ill->ill_ipst;
12790 
12791 #define	rptr    ((uchar_t *)ipha)
12792 
12793 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12794 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12795 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12796 	ASSERT(ill != NULL);
12797 
12798 	/*
12799 	 * FAST PATH for udp packets
12800 	 */
12801 
12802 	/* u1 is # words of IP options */
12803 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12804 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12805 
12806 	/* IP options present */
12807 	if (u1 != 0)
12808 		goto ipoptions;
12809 
12810 	/* Check the IP header checksum.  */
12811 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12812 		/* Clear the IP header h/w cksum flag */
12813 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12814 	} else if (!mctl_present) {
12815 		/*
12816 		 * Don't verify header checksum if this packet is coming
12817 		 * back from AH/ESP as we already did it.
12818 		 */
12819 #define	uph	((uint16_t *)ipha)
12820 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12821 		    uph[6] + uph[7] + uph[8] + uph[9];
12822 #undef	uph
12823 		/* finish doing IP checksum */
12824 		sum = (sum & 0xFFFF) + (sum >> 16);
12825 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12826 		if (sum != 0 && sum != 0xFFFF) {
12827 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12828 			freemsg(first_mp);
12829 			return;
12830 		}
12831 	}
12832 
12833 	/*
12834 	 * Count for SNMP of inbound packets for ire.
12835 	 * if mctl is present this might be a secure packet and
12836 	 * has already been counted for in ip_proto_input().
12837 	 */
12838 	if (!mctl_present) {
12839 		UPDATE_IB_PKT_COUNT(ire);
12840 		ire->ire_last_used_time = lbolt;
12841 	}
12842 
12843 	/* packet part of fragmented IP packet? */
12844 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12845 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12846 		goto fragmented;
12847 	}
12848 
12849 	/* u1 = IP header length (20 bytes) */
12850 	u1 = IP_SIMPLE_HDR_LENGTH;
12851 
12852 	/* packet does not contain complete IP & UDP headers */
12853 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12854 		goto udppullup;
12855 
12856 	/* up points to UDP header */
12857 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12858 #define	iphs    ((uint16_t *)ipha)
12859 
12860 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12861 	if (up[3] != 0) {
12862 		mblk_t *mp1 = mp->b_cont;
12863 		boolean_t cksum_err;
12864 		uint16_t hck_flags = 0;
12865 
12866 		/* Pseudo-header checksum */
12867 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12868 		    iphs[9] + up[2];
12869 
12870 		/*
12871 		 * Revert to software checksum calculation if the interface
12872 		 * isn't capable of checksum offload or if IPsec is present.
12873 		 */
12874 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12875 			hck_flags = DB_CKSUMFLAGS(mp);
12876 
12877 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12878 			IP_STAT(ipst, ip_in_sw_cksum);
12879 
12880 		IP_CKSUM_RECV(hck_flags, u1,
12881 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12882 		    (int32_t)((uchar_t *)up - rptr),
12883 		    mp, mp1, cksum_err);
12884 
12885 		if (cksum_err) {
12886 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12887 			if (hck_flags & HCK_FULLCKSUM)
12888 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12889 			else if (hck_flags & HCK_PARTIALCKSUM)
12890 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12891 			else
12892 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12893 
12894 			freemsg(first_mp);
12895 			return;
12896 		}
12897 	}
12898 
12899 	/* Non-fragmented broadcast or multicast packet? */
12900 	if (ire->ire_type == IRE_BROADCAST)
12901 		goto udpslowpath;
12902 
12903 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12904 	    ire->ire_zoneid, ipst)) != NULL) {
12905 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
12906 		IP_STAT(ipst, ip_udp_fast_path);
12907 
12908 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
12909 		    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
12910 			freemsg(mp);
12911 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12912 		} else {
12913 			if (!mctl_present) {
12914 				BUMP_MIB(ill->ill_ip_mib,
12915 				    ipIfStatsHCInDelivers);
12916 			}
12917 			/*
12918 			 * mp and first_mp can change.
12919 			 */
12920 			if (ip_udp_check(q, connp, recv_ill,
12921 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12922 				/* Send it upstream */
12923 				(connp->conn_recv)(connp, mp, NULL);
12924 			}
12925 		}
12926 		/*
12927 		 * freeb() cannot deal with null mblk being passed
12928 		 * in and first_mp can be set to null in the call
12929 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12930 		 */
12931 		if (mctl_present && first_mp != NULL) {
12932 			freeb(first_mp);
12933 		}
12934 		CONN_DEC_REF(connp);
12935 		return;
12936 	}
12937 
12938 	/*
12939 	 * if we got here we know the packet is not fragmented and
12940 	 * has no options. The classifier could not find a conn_t and
12941 	 * most likely its an icmp packet so send it through slow path.
12942 	 */
12943 
12944 	goto udpslowpath;
12945 
12946 ipoptions:
12947 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12948 		goto slow_done;
12949 	}
12950 
12951 	UPDATE_IB_PKT_COUNT(ire);
12952 	ire->ire_last_used_time = lbolt;
12953 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12954 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12955 fragmented:
12956 		/*
12957 		 * "sum" and "reass_hck_flags" are non-zero if the
12958 		 * reassembled packet has a valid hardware computed
12959 		 * checksum information associated with it.
12960 		 */
12961 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12962 			goto slow_done;
12963 		/*
12964 		 * Make sure that first_mp points back to mp as
12965 		 * the mp we came in with could have changed in
12966 		 * ip_rput_fragment().
12967 		 */
12968 		ASSERT(!mctl_present);
12969 		ipha = (ipha_t *)mp->b_rptr;
12970 		first_mp = mp;
12971 	}
12972 
12973 	/* Now we have a complete datagram, destined for this machine. */
12974 	u1 = IPH_HDR_LENGTH(ipha);
12975 	/* Pull up the UDP header, if necessary. */
12976 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12977 udppullup:
12978 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12979 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12980 			freemsg(first_mp);
12981 			goto slow_done;
12982 		}
12983 		ipha = (ipha_t *)mp->b_rptr;
12984 	}
12985 
12986 	/*
12987 	 * Validate the checksum for the reassembled packet; for the
12988 	 * pullup case we calculate the payload checksum in software.
12989 	 */
12990 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12991 	if (up[3] != 0) {
12992 		boolean_t cksum_err;
12993 
12994 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12995 			IP_STAT(ipst, ip_in_sw_cksum);
12996 
12997 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12998 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12999 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
13000 		    iphs[9] + up[2], sum, cksum_err);
13001 
13002 		if (cksum_err) {
13003 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
13004 
13005 			if (reass_hck_flags & HCK_FULLCKSUM)
13006 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
13007 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
13008 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
13009 			else
13010 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
13011 
13012 			freemsg(first_mp);
13013 			goto slow_done;
13014 		}
13015 	}
13016 udpslowpath:
13017 
13018 	/* Clear hardware checksum flag to be safe */
13019 	DB_CKSUMFLAGS(mp) = 0;
13020 
13021 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
13022 	    (ire->ire_type == IRE_BROADCAST),
13023 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
13024 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
13025 
13026 slow_done:
13027 	IP_STAT(ipst, ip_udp_slow_path);
13028 	return;
13029 
13030 #undef  iphs
13031 #undef  rptr
13032 }
13033 
13034 /* ARGSUSED */
13035 static mblk_t *
13036 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13037     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
13038     ill_rx_ring_t *ill_ring)
13039 {
13040 	conn_t		*connp;
13041 	uint32_t	sum;
13042 	uint32_t	u1;
13043 	uint16_t	*up;
13044 	int		offset;
13045 	ssize_t		len;
13046 	mblk_t		*mp1;
13047 	boolean_t	syn_present = B_FALSE;
13048 	tcph_t		*tcph;
13049 	uint_t		tcph_flags;
13050 	uint_t		ip_hdr_len;
13051 	ill_t		*ill = (ill_t *)q->q_ptr;
13052 	zoneid_t	zoneid = ire->ire_zoneid;
13053 	boolean_t	cksum_err;
13054 	uint16_t	hck_flags = 0;
13055 	ip_stack_t	*ipst = recv_ill->ill_ipst;
13056 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
13057 
13058 #define	rptr	((uchar_t *)ipha)
13059 
13060 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
13061 	ASSERT(ill != NULL);
13062 
13063 	/*
13064 	 * FAST PATH for tcp packets
13065 	 */
13066 
13067 	/* u1 is # words of IP options */
13068 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13069 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13070 
13071 	/* IP options present */
13072 	if (u1) {
13073 		goto ipoptions;
13074 	} else if (!mctl_present) {
13075 		/* Check the IP header checksum.  */
13076 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13077 			/* Clear the IP header h/w cksum flag */
13078 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
13079 		} else if (!mctl_present) {
13080 			/*
13081 			 * Don't verify header checksum if this packet
13082 			 * is coming back from AH/ESP as we already did it.
13083 			 */
13084 #define	uph	((uint16_t *)ipha)
13085 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13086 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13087 #undef	uph
13088 			/* finish doing IP checksum */
13089 			sum = (sum & 0xFFFF) + (sum >> 16);
13090 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13091 			if (sum != 0 && sum != 0xFFFF) {
13092 				BUMP_MIB(ill->ill_ip_mib,
13093 				    ipIfStatsInCksumErrs);
13094 				goto error;
13095 			}
13096 		}
13097 	}
13098 
13099 	if (!mctl_present) {
13100 		UPDATE_IB_PKT_COUNT(ire);
13101 		ire->ire_last_used_time = lbolt;
13102 	}
13103 
13104 	/* packet part of fragmented IP packet? */
13105 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13106 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13107 		goto fragmented;
13108 	}
13109 
13110 	/* u1 = IP header length (20 bytes) */
13111 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13112 
13113 	/* does packet contain IP+TCP headers? */
13114 	len = mp->b_wptr - rptr;
13115 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13116 		IP_STAT(ipst, ip_tcppullup);
13117 		goto tcppullup;
13118 	}
13119 
13120 	/* TCP options present? */
13121 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13122 
13123 	/*
13124 	 * If options need to be pulled up, then goto tcpoptions.
13125 	 * otherwise we are still in the fast path
13126 	 */
13127 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13128 		IP_STAT(ipst, ip_tcpoptions);
13129 		goto tcpoptions;
13130 	}
13131 
13132 	/* multiple mblks of tcp data? */
13133 	if ((mp1 = mp->b_cont) != NULL) {
13134 		/* more then two? */
13135 		if (mp1->b_cont != NULL) {
13136 			IP_STAT(ipst, ip_multipkttcp);
13137 			goto multipkttcp;
13138 		}
13139 		len += mp1->b_wptr - mp1->b_rptr;
13140 	}
13141 
13142 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13143 
13144 	/* part of pseudo checksum */
13145 
13146 	/* TCP datagram length */
13147 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13148 
13149 #define	iphs    ((uint16_t *)ipha)
13150 
13151 #ifdef	_BIG_ENDIAN
13152 	u1 += IPPROTO_TCP;
13153 #else
13154 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13155 #endif
13156 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13157 
13158 	/*
13159 	 * Revert to software checksum calculation if the interface
13160 	 * isn't capable of checksum offload or if IPsec is present.
13161 	 */
13162 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13163 		hck_flags = DB_CKSUMFLAGS(mp);
13164 
13165 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13166 		IP_STAT(ipst, ip_in_sw_cksum);
13167 
13168 	IP_CKSUM_RECV(hck_flags, u1,
13169 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13170 	    (int32_t)((uchar_t *)up - rptr),
13171 	    mp, mp1, cksum_err);
13172 
13173 	if (cksum_err) {
13174 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13175 
13176 		if (hck_flags & HCK_FULLCKSUM)
13177 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13178 		else if (hck_flags & HCK_PARTIALCKSUM)
13179 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13180 		else
13181 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13182 
13183 		goto error;
13184 	}
13185 
13186 try_again:
13187 
13188 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13189 	    zoneid, ipst)) == NULL) {
13190 		/* Send the TH_RST */
13191 		goto no_conn;
13192 	}
13193 
13194 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13195 	tcph_flags = tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG);
13196 
13197 	/*
13198 	 * TCP FAST PATH for AF_INET socket.
13199 	 *
13200 	 * TCP fast path to avoid extra work. An AF_INET socket type
13201 	 * does not have facility to receive extra information via
13202 	 * ip_process or ip_add_info. Also, when the connection was
13203 	 * established, we made a check if this connection is impacted
13204 	 * by any global IPsec policy or per connection policy (a
13205 	 * policy that comes in effect later will not apply to this
13206 	 * connection). Since all this can be determined at the
13207 	 * connection establishment time, a quick check of flags
13208 	 * can avoid extra work.
13209 	 */
13210 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13211 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13212 		ASSERT(first_mp == mp);
13213 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13214 		if (tcph_flags != (TH_SYN | TH_ACK)) {
13215 			SET_SQUEUE(mp, tcp_rput_data, connp);
13216 			return (mp);
13217 		}
13218 		mp->b_datap->db_struioflag |= STRUIO_CONNECT;
13219 		DB_CKSUMSTART(mp) = (intptr_t)ip_squeue_get(ill_ring);
13220 		SET_SQUEUE(mp, tcp_input, connp);
13221 		return (mp);
13222 	}
13223 
13224 	if (tcph_flags == TH_SYN) {
13225 		if (IPCL_IS_TCP(connp)) {
13226 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13227 			DB_CKSUMSTART(mp) =
13228 			    (intptr_t)ip_squeue_get(ill_ring);
13229 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13230 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13231 				BUMP_MIB(ill->ill_ip_mib,
13232 				    ipIfStatsHCInDelivers);
13233 				SET_SQUEUE(mp, connp->conn_recv, connp);
13234 				return (mp);
13235 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13236 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13237 				BUMP_MIB(ill->ill_ip_mib,
13238 				    ipIfStatsHCInDelivers);
13239 				ip_squeue_enter_unbound++;
13240 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13241 				    connp);
13242 				return (mp);
13243 			}
13244 			syn_present = B_TRUE;
13245 		}
13246 	}
13247 
13248 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13249 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13250 
13251 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13252 		/* No need to send this packet to TCP */
13253 		if ((flags & TH_RST) || (flags & TH_URG)) {
13254 			CONN_DEC_REF(connp);
13255 			freemsg(first_mp);
13256 			return (NULL);
13257 		}
13258 		if (flags & TH_ACK) {
13259 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13260 			    ipst->ips_netstack->netstack_tcp, connp);
13261 			CONN_DEC_REF(connp);
13262 			return (NULL);
13263 		}
13264 
13265 		CONN_DEC_REF(connp);
13266 		freemsg(first_mp);
13267 		return (NULL);
13268 	}
13269 
13270 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13271 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13272 		    ipha, NULL, mctl_present);
13273 		if (first_mp == NULL) {
13274 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13275 			CONN_DEC_REF(connp);
13276 			return (NULL);
13277 		}
13278 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13279 			ASSERT(syn_present);
13280 			if (mctl_present) {
13281 				ASSERT(first_mp != mp);
13282 				first_mp->b_datap->db_struioflag |=
13283 				    STRUIO_POLICY;
13284 			} else {
13285 				ASSERT(first_mp == mp);
13286 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13287 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13288 			}
13289 		} else {
13290 			/*
13291 			 * Discard first_mp early since we're dealing with a
13292 			 * fully-connected conn_t and tcp doesn't do policy in
13293 			 * this case.
13294 			 */
13295 			if (mctl_present) {
13296 				freeb(first_mp);
13297 				mctl_present = B_FALSE;
13298 			}
13299 			first_mp = mp;
13300 		}
13301 	}
13302 
13303 	/* Initiate IPPF processing for fastpath */
13304 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13305 		uint32_t	ill_index;
13306 
13307 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13308 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13309 		if (mp == NULL) {
13310 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13311 			    "deferred/dropped during IPPF processing\n"));
13312 			CONN_DEC_REF(connp);
13313 			if (mctl_present)
13314 				freeb(first_mp);
13315 			return (NULL);
13316 		} else if (mctl_present) {
13317 			/*
13318 			 * ip_process might return a new mp.
13319 			 */
13320 			ASSERT(first_mp != mp);
13321 			first_mp->b_cont = mp;
13322 		} else {
13323 			first_mp = mp;
13324 		}
13325 
13326 	}
13327 
13328 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13329 		/*
13330 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13331 		 * make sure IPF_RECVIF is passed to ip_add_info.
13332 		 */
13333 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13334 		    IPCL_ZONEID(connp), ipst);
13335 		if (mp == NULL) {
13336 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13337 			CONN_DEC_REF(connp);
13338 			if (mctl_present)
13339 				freeb(first_mp);
13340 			return (NULL);
13341 		} else if (mctl_present) {
13342 			/*
13343 			 * ip_add_info might return a new mp.
13344 			 */
13345 			ASSERT(first_mp != mp);
13346 			first_mp->b_cont = mp;
13347 		} else {
13348 			first_mp = mp;
13349 		}
13350 	}
13351 
13352 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13353 	if (IPCL_IS_TCP(connp)) {
13354 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13355 		return (first_mp);
13356 	} else {
13357 		/* SOCK_RAW, IPPROTO_TCP case */
13358 		(connp->conn_recv)(connp, first_mp, NULL);
13359 		CONN_DEC_REF(connp);
13360 		return (NULL);
13361 	}
13362 
13363 no_conn:
13364 	/* Initiate IPPf processing, if needed. */
13365 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13366 		uint32_t ill_index;
13367 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13368 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13369 		if (first_mp == NULL) {
13370 			return (NULL);
13371 		}
13372 	}
13373 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13374 
13375 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13376 	    ipst->ips_netstack->netstack_tcp, NULL);
13377 	return (NULL);
13378 ipoptions:
13379 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13380 		goto slow_done;
13381 	}
13382 
13383 	UPDATE_IB_PKT_COUNT(ire);
13384 	ire->ire_last_used_time = lbolt;
13385 
13386 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13387 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13388 fragmented:
13389 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13390 			if (mctl_present)
13391 				freeb(first_mp);
13392 			goto slow_done;
13393 		}
13394 		/*
13395 		 * Make sure that first_mp points back to mp as
13396 		 * the mp we came in with could have changed in
13397 		 * ip_rput_fragment().
13398 		 */
13399 		ASSERT(!mctl_present);
13400 		ipha = (ipha_t *)mp->b_rptr;
13401 		first_mp = mp;
13402 	}
13403 
13404 	/* Now we have a complete datagram, destined for this machine. */
13405 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13406 
13407 	len = mp->b_wptr - mp->b_rptr;
13408 	/* Pull up a minimal TCP header, if necessary. */
13409 	if (len < (u1 + 20)) {
13410 tcppullup:
13411 		if (!pullupmsg(mp, u1 + 20)) {
13412 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13413 			goto error;
13414 		}
13415 		ipha = (ipha_t *)mp->b_rptr;
13416 		len = mp->b_wptr - mp->b_rptr;
13417 	}
13418 
13419 	/*
13420 	 * Extract the offset field from the TCP header.  As usual, we
13421 	 * try to help the compiler more than the reader.
13422 	 */
13423 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13424 	if (offset != 5) {
13425 tcpoptions:
13426 		if (offset < 5) {
13427 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13428 			goto error;
13429 		}
13430 		/*
13431 		 * There must be TCP options.
13432 		 * Make sure we can grab them.
13433 		 */
13434 		offset <<= 2;
13435 		offset += u1;
13436 		if (len < offset) {
13437 			if (!pullupmsg(mp, offset)) {
13438 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13439 				goto error;
13440 			}
13441 			ipha = (ipha_t *)mp->b_rptr;
13442 			len = mp->b_wptr - rptr;
13443 		}
13444 	}
13445 
13446 	/* Get the total packet length in len, including headers. */
13447 	if (mp->b_cont) {
13448 multipkttcp:
13449 		len = msgdsize(mp);
13450 	}
13451 
13452 	/*
13453 	 * Check the TCP checksum by pulling together the pseudo-
13454 	 * header checksum, and passing it to ip_csum to be added in
13455 	 * with the TCP datagram.
13456 	 *
13457 	 * Since we are not using the hwcksum if available we must
13458 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13459 	 * If either of these fails along the way the mblk is freed.
13460 	 * If this logic ever changes and mblk is reused to say send
13461 	 * ICMP's back, then this flag may need to be cleared in
13462 	 * other places as well.
13463 	 */
13464 	DB_CKSUMFLAGS(mp) = 0;
13465 
13466 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13467 
13468 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13469 #ifdef	_BIG_ENDIAN
13470 	u1 += IPPROTO_TCP;
13471 #else
13472 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13473 #endif
13474 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13475 	/*
13476 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13477 	 */
13478 	IP_STAT(ipst, ip_in_sw_cksum);
13479 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13480 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13481 		goto error;
13482 	}
13483 
13484 	IP_STAT(ipst, ip_tcp_slow_path);
13485 	goto try_again;
13486 #undef  iphs
13487 #undef  rptr
13488 
13489 error:
13490 	freemsg(first_mp);
13491 slow_done:
13492 	return (NULL);
13493 }
13494 
13495 /* ARGSUSED */
13496 static void
13497 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13498     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13499 {
13500 	conn_t		*connp;
13501 	uint32_t	sum;
13502 	uint32_t	u1;
13503 	ssize_t		len;
13504 	sctp_hdr_t	*sctph;
13505 	zoneid_t	zoneid = ire->ire_zoneid;
13506 	uint32_t	pktsum;
13507 	uint32_t	calcsum;
13508 	uint32_t	ports;
13509 	in6_addr_t	map_src, map_dst;
13510 	ill_t		*ill = (ill_t *)q->q_ptr;
13511 	ip_stack_t	*ipst;
13512 	sctp_stack_t	*sctps;
13513 	boolean_t	sctp_csum_err = B_FALSE;
13514 
13515 	ASSERT(recv_ill != NULL);
13516 	ipst = recv_ill->ill_ipst;
13517 	sctps = ipst->ips_netstack->netstack_sctp;
13518 
13519 #define	rptr	((uchar_t *)ipha)
13520 
13521 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13522 	ASSERT(ill != NULL);
13523 
13524 	/* u1 is # words of IP options */
13525 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13526 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13527 
13528 	/* IP options present */
13529 	if (u1 > 0) {
13530 		goto ipoptions;
13531 	} else {
13532 		/* Check the IP header checksum.  */
13533 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill) &&
13534 		    !mctl_present) {
13535 #define	uph	((uint16_t *)ipha)
13536 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13537 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13538 #undef	uph
13539 			/* finish doing IP checksum */
13540 			sum = (sum & 0xFFFF) + (sum >> 16);
13541 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13542 			/*
13543 			 * Don't verify header checksum if this packet
13544 			 * is coming back from AH/ESP as we already did it.
13545 			 */
13546 			if (sum != 0 && sum != 0xFFFF) {
13547 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13548 				goto error;
13549 			}
13550 		}
13551 		/*
13552 		 * Since there is no SCTP h/w cksum support yet, just
13553 		 * clear the flag.
13554 		 */
13555 		DB_CKSUMFLAGS(mp) = 0;
13556 	}
13557 
13558 	/*
13559 	 * Don't verify header checksum if this packet is coming
13560 	 * back from AH/ESP as we already did it.
13561 	 */
13562 	if (!mctl_present) {
13563 		UPDATE_IB_PKT_COUNT(ire);
13564 		ire->ire_last_used_time = lbolt;
13565 	}
13566 
13567 	/* packet part of fragmented IP packet? */
13568 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13569 	if (u1 & (IPH_MF | IPH_OFFSET))
13570 		goto fragmented;
13571 
13572 	/* u1 = IP header length (20 bytes) */
13573 	u1 = IP_SIMPLE_HDR_LENGTH;
13574 
13575 find_sctp_client:
13576 	/* Pullup if we don't have the sctp common header. */
13577 	len = MBLKL(mp);
13578 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13579 		if (mp->b_cont == NULL ||
13580 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13581 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13582 			goto error;
13583 		}
13584 		ipha = (ipha_t *)mp->b_rptr;
13585 		len = MBLKL(mp);
13586 	}
13587 
13588 	sctph = (sctp_hdr_t *)(rptr + u1);
13589 #ifdef	DEBUG
13590 	if (!skip_sctp_cksum) {
13591 #endif
13592 		pktsum = sctph->sh_chksum;
13593 		sctph->sh_chksum = 0;
13594 		calcsum = sctp_cksum(mp, u1);
13595 		sctph->sh_chksum = pktsum;
13596 		if (calcsum != pktsum)
13597 			sctp_csum_err = B_TRUE;
13598 #ifdef	DEBUG	/* skip_sctp_cksum */
13599 	}
13600 #endif
13601 	/* get the ports */
13602 	ports = *(uint32_t *)&sctph->sh_sport;
13603 
13604 	IRE_REFRELE(ire);
13605 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13606 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13607 	if (sctp_csum_err) {
13608 		/*
13609 		 * No potential sctp checksum errors go to the Sun
13610 		 * sctp stack however they might be Adler-32 summed
13611 		 * packets a userland stack bound to a raw IP socket
13612 		 * could reasonably use. Note though that Adler-32 is
13613 		 * a long deprecated algorithm and customer sctp
13614 		 * networks should eventually migrate to CRC-32 at
13615 		 * which time this facility should be removed.
13616 		 */
13617 		flags |= IP_FF_SCTP_CSUM_ERR;
13618 		goto no_conn;
13619 	}
13620 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13621 	    sctps)) == NULL) {
13622 		/* Check for raw socket or OOTB handling */
13623 		goto no_conn;
13624 	}
13625 
13626 	/* Found a client; up it goes */
13627 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13628 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13629 	return;
13630 
13631 no_conn:
13632 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13633 	    ports, mctl_present, flags, B_TRUE, zoneid);
13634 	return;
13635 
13636 ipoptions:
13637 	DB_CKSUMFLAGS(mp) = 0;
13638 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13639 		goto slow_done;
13640 
13641 	UPDATE_IB_PKT_COUNT(ire);
13642 	ire->ire_last_used_time = lbolt;
13643 
13644 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13645 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13646 fragmented:
13647 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13648 			goto slow_done;
13649 		/*
13650 		 * Make sure that first_mp points back to mp as
13651 		 * the mp we came in with could have changed in
13652 		 * ip_rput_fragment().
13653 		 */
13654 		ASSERT(!mctl_present);
13655 		ipha = (ipha_t *)mp->b_rptr;
13656 		first_mp = mp;
13657 	}
13658 
13659 	/* Now we have a complete datagram, destined for this machine. */
13660 	u1 = IPH_HDR_LENGTH(ipha);
13661 	goto find_sctp_client;
13662 #undef  iphs
13663 #undef  rptr
13664 
13665 error:
13666 	freemsg(first_mp);
13667 slow_done:
13668 	IRE_REFRELE(ire);
13669 }
13670 
13671 #define	VER_BITS	0xF0
13672 #define	VERSION_6	0x60
13673 
13674 static boolean_t
13675 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13676     ipaddr_t *dstp, ip_stack_t *ipst)
13677 {
13678 	uint_t	opt_len;
13679 	ipha_t *ipha;
13680 	ssize_t len;
13681 	uint_t	pkt_len;
13682 
13683 	ASSERT(ill != NULL);
13684 	IP_STAT(ipst, ip_ipoptions);
13685 	ipha = *iphapp;
13686 
13687 #define	rptr    ((uchar_t *)ipha)
13688 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13689 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13690 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13691 		freemsg(mp);
13692 		return (B_FALSE);
13693 	}
13694 
13695 	/* multiple mblk or too short */
13696 	pkt_len = ntohs(ipha->ipha_length);
13697 
13698 	/* Get the number of words of IP options in the IP header. */
13699 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13700 	if (opt_len) {
13701 		/* IP Options present!  Validate and process. */
13702 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13703 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13704 			goto done;
13705 		}
13706 		/*
13707 		 * Recompute complete header length and make sure we
13708 		 * have access to all of it.
13709 		 */
13710 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13711 		if (len > (mp->b_wptr - rptr)) {
13712 			if (len > pkt_len) {
13713 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13714 				goto done;
13715 			}
13716 			if (!pullupmsg(mp, len)) {
13717 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13718 				goto done;
13719 			}
13720 			ipha = (ipha_t *)mp->b_rptr;
13721 		}
13722 		/*
13723 		 * Go off to ip_rput_options which returns the next hop
13724 		 * destination address, which may have been affected
13725 		 * by source routing.
13726 		 */
13727 		IP_STAT(ipst, ip_opt);
13728 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13729 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13730 			return (B_FALSE);
13731 		}
13732 	}
13733 	*iphapp = ipha;
13734 	return (B_TRUE);
13735 done:
13736 	/* clear b_prev - used by ip_mroute_decap */
13737 	mp->b_prev = NULL;
13738 	freemsg(mp);
13739 	return (B_FALSE);
13740 #undef  rptr
13741 }
13742 
13743 /*
13744  * Deal with the fact that there is no ire for the destination.
13745  */
13746 static ire_t *
13747 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13748 {
13749 	ipha_t	*ipha;
13750 	ill_t	*ill;
13751 	ire_t	*ire;
13752 	ip_stack_t *ipst;
13753 	enum	ire_forward_action ret_action;
13754 
13755 	ipha = (ipha_t *)mp->b_rptr;
13756 	ill = (ill_t *)q->q_ptr;
13757 
13758 	ASSERT(ill != NULL);
13759 	ipst = ill->ill_ipst;
13760 
13761 	/*
13762 	 * No IRE for this destination, so it can't be for us.
13763 	 * Unless we are forwarding, drop the packet.
13764 	 * We have to let source routed packets through
13765 	 * since we don't yet know if they are 'ping -l'
13766 	 * packets i.e. if they will go out over the
13767 	 * same interface as they came in on.
13768 	 */
13769 	if (ll_multicast) {
13770 		freemsg(mp);
13771 		return (NULL);
13772 	}
13773 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13774 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13775 		freemsg(mp);
13776 		return (NULL);
13777 	}
13778 
13779 	/*
13780 	 * Mark this packet as having originated externally.
13781 	 *
13782 	 * For non-forwarding code path, ire_send later double
13783 	 * checks this interface to see if it is still exists
13784 	 * post-ARP resolution.
13785 	 *
13786 	 * Also, IPQOS uses this to differentiate between
13787 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13788 	 * QOS packet processing in ip_wput_attach_llhdr().
13789 	 * The QoS module can mark the b_band for a fastpath message
13790 	 * or the dl_priority field in a unitdata_req header for
13791 	 * CoS marking. This info can only be found in
13792 	 * ip_wput_attach_llhdr().
13793 	 */
13794 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13795 	/*
13796 	 * Clear the indication that this may have a hardware checksum
13797 	 * as we are not using it
13798 	 */
13799 	DB_CKSUMFLAGS(mp) = 0;
13800 
13801 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13802 	    MBLK_GETLABEL(mp), ipst);
13803 
13804 	if (ire == NULL && ret_action == Forward_check_multirt) {
13805 		/* Let ip_newroute handle CGTP  */
13806 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13807 		return (NULL);
13808 	}
13809 
13810 	if (ire != NULL)
13811 		return (ire);
13812 
13813 	mp->b_prev = mp->b_next = 0;
13814 
13815 	if (ret_action == Forward_blackhole) {
13816 		freemsg(mp);
13817 		return (NULL);
13818 	}
13819 	/* send icmp unreachable */
13820 	q = WR(q);
13821 	/* Sent by forwarding path, and router is global zone */
13822 	if (ip_source_routed(ipha, ipst)) {
13823 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13824 		    GLOBAL_ZONEID, ipst);
13825 	} else {
13826 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13827 		    ipst);
13828 	}
13829 
13830 	return (NULL);
13831 
13832 }
13833 
13834 /*
13835  * check ip header length and align it.
13836  */
13837 static boolean_t
13838 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13839 {
13840 	ssize_t len;
13841 	ill_t *ill;
13842 	ipha_t	*ipha;
13843 
13844 	len = MBLKL(mp);
13845 
13846 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13847 		ill = (ill_t *)q->q_ptr;
13848 
13849 		if (!OK_32PTR(mp->b_rptr))
13850 			IP_STAT(ipst, ip_notaligned1);
13851 		else
13852 			IP_STAT(ipst, ip_notaligned2);
13853 		/* Guard against bogus device drivers */
13854 		if (len < 0) {
13855 			/* clear b_prev - used by ip_mroute_decap */
13856 			mp->b_prev = NULL;
13857 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13858 			freemsg(mp);
13859 			return (B_FALSE);
13860 		}
13861 
13862 		if (ip_rput_pullups++ == 0) {
13863 			ipha = (ipha_t *)mp->b_rptr;
13864 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13865 			    "ip_check_and_align_header: %s forced us to "
13866 			    " pullup pkt, hdr len %ld, hdr addr %p",
13867 			    ill->ill_name, len, (void *)ipha);
13868 		}
13869 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13870 			/* clear b_prev - used by ip_mroute_decap */
13871 			mp->b_prev = NULL;
13872 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13873 			freemsg(mp);
13874 			return (B_FALSE);
13875 		}
13876 	}
13877 	return (B_TRUE);
13878 }
13879 
13880 ire_t *
13881 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13882 {
13883 	ire_t		*new_ire;
13884 	ill_t		*ire_ill;
13885 	uint_t		ifindex;
13886 	ip_stack_t	*ipst = ill->ill_ipst;
13887 	boolean_t	strict_check = B_FALSE;
13888 
13889 	/*
13890 	 * This packet came in on an interface other than the one associated
13891 	 * with the first ire we found for the destination address. We do
13892 	 * another ire lookup here, using the ingress ill, to see if the
13893 	 * interface is in an interface group.
13894 	 * As long as the ills belong to the same group, we don't consider
13895 	 * them to be arriving on the wrong interface. Thus, if the switch
13896 	 * is doing inbound load spreading, we won't drop packets when the
13897 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13898 	 * for 'usesrc groups' where the destination address may belong to
13899 	 * another interface to allow multipathing to happen.
13900 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13901 	 * where the local address may not be unique. In this case we were
13902 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13903 	 * actually returned. The new lookup, which is more specific, should
13904 	 * only find the IRE_LOCAL associated with the ingress ill if one
13905 	 * exists.
13906 	 */
13907 
13908 	if (ire->ire_ipversion == IPV4_VERSION) {
13909 		if (ipst->ips_ip_strict_dst_multihoming)
13910 			strict_check = B_TRUE;
13911 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13912 		    ill->ill_ipif, ALL_ZONES, NULL,
13913 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13914 	} else {
13915 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13916 		if (ipst->ips_ipv6_strict_dst_multihoming)
13917 			strict_check = B_TRUE;
13918 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13919 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13920 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13921 	}
13922 	/*
13923 	 * If the same ire that was returned in ip_input() is found then this
13924 	 * is an indication that interface groups are in use. The packet
13925 	 * arrived on a different ill in the group than the one associated with
13926 	 * the destination address.  If a different ire was found then the same
13927 	 * IP address must be hosted on multiple ills. This is possible with
13928 	 * unnumbered point2point interfaces. We switch to use this new ire in
13929 	 * order to have accurate interface statistics.
13930 	 */
13931 	if (new_ire != NULL) {
13932 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13933 			ire_refrele(ire);
13934 			ire = new_ire;
13935 		} else {
13936 			ire_refrele(new_ire);
13937 		}
13938 		return (ire);
13939 	} else if ((ire->ire_rfq == NULL) &&
13940 	    (ire->ire_ipversion == IPV4_VERSION)) {
13941 		/*
13942 		 * The best match could have been the original ire which
13943 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13944 		 * the strict multihoming checks are irrelevant as we consider
13945 		 * local addresses hosted on lo0 to be interface agnostic. We
13946 		 * only expect a null ire_rfq on IREs which are associated with
13947 		 * lo0 hence we can return now.
13948 		 */
13949 		return (ire);
13950 	}
13951 
13952 	/*
13953 	 * Chase pointers once and store locally.
13954 	 */
13955 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13956 	    (ill_t *)(ire->ire_rfq->q_ptr);
13957 	ifindex = ill->ill_usesrc_ifindex;
13958 
13959 	/*
13960 	 * Check if it's a legal address on the 'usesrc' interface.
13961 	 */
13962 	if ((ifindex != 0) && (ire_ill != NULL) &&
13963 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13964 		return (ire);
13965 	}
13966 
13967 	/*
13968 	 * If the ip*_strict_dst_multihoming switch is on then we can
13969 	 * only accept this packet if the interface is marked as routing.
13970 	 */
13971 	if (!(strict_check))
13972 		return (ire);
13973 
13974 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13975 	    ILLF_ROUTER) != 0) {
13976 		return (ire);
13977 	}
13978 
13979 	ire_refrele(ire);
13980 	return (NULL);
13981 }
13982 
13983 /*
13984  *
13985  * This is the fast forward path. If we are here, we dont need to
13986  * worry about RSVP, CGTP, or TSol. Furthermore the ftable lookup
13987  * needed to find the nexthop in this case is much simpler
13988  */
13989 ire_t *
13990 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13991 {
13992 	ipha_t	*ipha;
13993 	ire_t	*src_ire;
13994 	ill_t	*stq_ill;
13995 	uint_t	hlen;
13996 	uint_t	pkt_len;
13997 	uint32_t sum;
13998 	queue_t	*dev_q;
13999 	ip_stack_t *ipst = ill->ill_ipst;
14000 	mblk_t *fpmp;
14001 	enum	ire_forward_action ret_action;
14002 
14003 	ipha = (ipha_t *)mp->b_rptr;
14004 
14005 	if (ire != NULL &&
14006 	    ire->ire_zoneid != GLOBAL_ZONEID &&
14007 	    ire->ire_zoneid != ALL_ZONES) {
14008 		/*
14009 		 * Should only use IREs that are visible to the global
14010 		 * zone for forwarding.
14011 		 */
14012 		ire_refrele(ire);
14013 		ire = ire_cache_lookup(dst, GLOBAL_ZONEID, NULL, ipst);
14014 		/*
14015 		 * ire_cache_lookup() can return ire of IRE_LOCAL in
14016 		 * transient cases. In such case, just drop the packet
14017 		 */
14018 		if (ire->ire_type != IRE_CACHE)
14019 			goto drop;
14020 	}
14021 
14022 	/*
14023 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
14024 	 * The loopback address check for both src and dst has already
14025 	 * been checked in ip_input
14026 	 */
14027 
14028 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
14029 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14030 		goto drop;
14031 	}
14032 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14033 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14034 
14035 	if (src_ire != NULL) {
14036 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14037 		ire_refrele(src_ire);
14038 		goto drop;
14039 	}
14040 
14041 	/* No ire cache of nexthop. So first create one  */
14042 	if (ire == NULL) {
14043 
14044 		ire = ire_forward_simple(dst, &ret_action, ipst);
14045 
14046 		/*
14047 		 * We only come to ip_fast_forward if ip_cgtp_filter
14048 		 * is not set. So ire_forward() should not return with
14049 		 * Forward_check_multirt as the next action.
14050 		 */
14051 		ASSERT(ret_action != Forward_check_multirt);
14052 		if (ire == NULL) {
14053 			/* An attempt was made to forward the packet */
14054 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14055 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14056 			mp->b_prev = mp->b_next = 0;
14057 			/* send icmp unreachable */
14058 			/* Sent by forwarding path, and router is global zone */
14059 			if (ret_action == Forward_ret_icmp_err) {
14060 				if (ip_source_routed(ipha, ipst)) {
14061 					icmp_unreachable(ill->ill_wq, mp,
14062 					    ICMP_SOURCE_ROUTE_FAILED,
14063 					    GLOBAL_ZONEID, ipst);
14064 				} else {
14065 					icmp_unreachable(ill->ill_wq, mp,
14066 					    ICMP_HOST_UNREACHABLE,
14067 					    GLOBAL_ZONEID, ipst);
14068 				}
14069 			} else {
14070 				freemsg(mp);
14071 			}
14072 			return (NULL);
14073 		}
14074 	}
14075 
14076 	/*
14077 	 * Forwarding fastpath exception case:
14078 	 * If either of the follwoing case is true, we take
14079 	 * the slowpath
14080 	 *	o forwarding is not enabled
14081 	 *	o incoming and outgoing interface are the same, or the same
14082 	 *	  IPMP group
14083 	 *	o corresponding ire is in incomplete state
14084 	 *	o packet needs fragmentation
14085 	 *	o ARP cache is not resolved
14086 	 *
14087 	 * The codeflow from here on is thus:
14088 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
14089 	 */
14090 	pkt_len = ntohs(ipha->ipha_length);
14091 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
14092 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
14093 	    (ill == stq_ill) ||
14094 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
14095 	    (ire->ire_nce == NULL) ||
14096 	    (pkt_len > ire->ire_max_frag) ||
14097 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
14098 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
14099 	    ipha->ipha_ttl <= 1) {
14100 		ip_rput_process_forward(ill->ill_rq, mp, ire,
14101 		    ipha, ill, B_FALSE, B_TRUE);
14102 		return (ire);
14103 	}
14104 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14105 
14106 	DTRACE_PROBE4(ip4__forwarding__start,
14107 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14108 
14109 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
14110 	    ipst->ips_ipv4firewall_forwarding,
14111 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
14112 
14113 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
14114 
14115 	if (mp == NULL)
14116 		goto drop;
14117 
14118 	mp->b_datap->db_struioun.cksum.flags = 0;
14119 	/* Adjust the checksum to reflect the ttl decrement. */
14120 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14121 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14122 	ipha->ipha_ttl--;
14123 
14124 	/*
14125 	 * Write the link layer header.  We can do this safely here,
14126 	 * because we have already tested to make sure that the IP
14127 	 * policy is not set, and that we have a fast path destination
14128 	 * header.
14129 	 */
14130 	mp->b_rptr -= hlen;
14131 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
14132 
14133 	UPDATE_IB_PKT_COUNT(ire);
14134 	ire->ire_last_used_time = lbolt;
14135 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
14136 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14137 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
14138 
14139 	if (!ILL_DIRECT_CAPABLE(stq_ill) || DB_TYPE(mp) != M_DATA) {
14140 		dev_q = ire->ire_stq->q_next;
14141 		if (DEV_Q_FLOW_BLOCKED(dev_q))
14142 			goto indiscard;
14143 	}
14144 
14145 	DTRACE_PROBE4(ip4__physical__out__start,
14146 	    ill_t *, NULL, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14147 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
14148 	    ipst->ips_ipv4firewall_physical_out,
14149 	    NULL, stq_ill, ipha, mp, mp, 0, ipst);
14150 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
14151 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,
14152 	    ipha, __dtrace_ipsr_ill_t *, stq_ill, ipha_t *, ipha,
14153 	    ip6_t *, NULL, int, 0);
14154 
14155 	if (mp != NULL) {
14156 		if (ipst->ips_ipobs_enabled) {
14157 			zoneid_t szone;
14158 
14159 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
14160 			    ipst, ALL_ZONES);
14161 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
14162 			    ALL_ZONES, ill, IPV4_VERSION, hlen, ipst);
14163 		}
14164 
14165 		ILL_SEND_TX(stq_ill, ire, dst, mp, IP_DROP_ON_NO_DESC);
14166 	}
14167 	return (ire);
14168 
14169 indiscard:
14170 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14171 drop:
14172 	if (mp != NULL)
14173 		freemsg(mp);
14174 	return (ire);
14175 
14176 }
14177 
14178 /*
14179  * This function is called in the forwarding slowpath, when
14180  * either the ire lacks the link-layer address, or the packet needs
14181  * further processing(eg. fragmentation), before transmission.
14182  */
14183 
14184 static void
14185 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14186     ill_t *ill, boolean_t ll_multicast, boolean_t from_ip_fast_forward)
14187 {
14188 	ill_group_t	*ill_group;
14189 	ill_group_t	*ire_group;
14190 	queue_t		*dev_q;
14191 	ire_t		*src_ire;
14192 	ip_stack_t	*ipst = ill->ill_ipst;
14193 
14194 	ASSERT(ire->ire_stq != NULL);
14195 
14196 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14197 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14198 
14199 	/*
14200 	 * If the caller of this function is ip_fast_forward() skip the
14201 	 * next three checks as it does not apply.
14202 	 */
14203 	if (from_ip_fast_forward) {
14204 		ill_group = ill->ill_group;
14205 		ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14206 		goto skip;
14207 	}
14208 
14209 	if (ll_multicast != 0) {
14210 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14211 		goto drop_pkt;
14212 	}
14213 
14214 	/*
14215 	 * check if ipha_src is a broadcast address. Note that this
14216 	 * check is redundant when we get here from ip_fast_forward()
14217 	 * which has already done this check. However, since we can
14218 	 * also get here from ip_rput_process_broadcast() or, for
14219 	 * for the slow path through ip_fast_forward(), we perform
14220 	 * the check again for code-reusability
14221 	 */
14222 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14223 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14224 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14225 		if (src_ire != NULL)
14226 			ire_refrele(src_ire);
14227 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14228 		ip2dbg(("ip_rput_process_forward: Received packet with"
14229 		    " bad src/dst address on %s\n", ill->ill_name));
14230 		goto drop_pkt;
14231 	}
14232 
14233 	ill_group = ill->ill_group;
14234 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14235 	/*
14236 	 * Check if we want to forward this one at this time.
14237 	 * We allow source routed packets on a host provided that
14238 	 * they go out the same interface or same interface group
14239 	 * as they came in on.
14240 	 *
14241 	 * XXX To be quicker, we may wish to not chase pointers to
14242 	 * get the ILLF_ROUTER flag and instead store the
14243 	 * forwarding policy in the ire.  An unfortunate
14244 	 * side-effect of that would be requiring an ire flush
14245 	 * whenever the ILLF_ROUTER flag changes.
14246 	 */
14247 skip:
14248 	if (((ill->ill_flags &
14249 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14250 	    ILLF_ROUTER) == 0) &&
14251 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14252 	    (ill_group != NULL && ill_group == ire_group)))) {
14253 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14254 		if (ip_source_routed(ipha, ipst)) {
14255 			q = WR(q);
14256 			/*
14257 			 * Clear the indication that this may have
14258 			 * hardware checksum as we are not using it.
14259 			 */
14260 			DB_CKSUMFLAGS(mp) = 0;
14261 			/* Sent by forwarding path, and router is global zone */
14262 			icmp_unreachable(q, mp,
14263 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14264 			return;
14265 		}
14266 		goto drop_pkt;
14267 	}
14268 
14269 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14270 
14271 	/* Packet is being forwarded. Turning off hwcksum flag. */
14272 	DB_CKSUMFLAGS(mp) = 0;
14273 	if (ipst->ips_ip_g_send_redirects) {
14274 		/*
14275 		 * Check whether the incoming interface and outgoing
14276 		 * interface is part of the same group. If so,
14277 		 * send redirects.
14278 		 *
14279 		 * Check the source address to see if it originated
14280 		 * on the same logical subnet it is going back out on.
14281 		 * If so, we should be able to send it a redirect.
14282 		 * Avoid sending a redirect if the destination
14283 		 * is directly connected (i.e., ipha_dst is the same
14284 		 * as ire_gateway_addr or the ire_addr of the
14285 		 * nexthop IRE_CACHE ), or if the packet was source
14286 		 * routed out this interface.
14287 		 */
14288 		ipaddr_t src, nhop;
14289 		mblk_t	*mp1;
14290 		ire_t	*nhop_ire = NULL;
14291 
14292 		/*
14293 		 * Check whether ire_rfq and q are from the same ill
14294 		 * or if they are not same, they at least belong
14295 		 * to the same group. If so, send redirects.
14296 		 */
14297 		if ((ire->ire_rfq == q ||
14298 		    (ill_group != NULL && ill_group == ire_group)) &&
14299 		    !ip_source_routed(ipha, ipst)) {
14300 
14301 			nhop = (ire->ire_gateway_addr != 0 ?
14302 			    ire->ire_gateway_addr : ire->ire_addr);
14303 
14304 			if (ipha->ipha_dst == nhop) {
14305 				/*
14306 				 * We avoid sending a redirect if the
14307 				 * destination is directly connected
14308 				 * because it is possible that multiple
14309 				 * IP subnets may have been configured on
14310 				 * the link, and the source may not
14311 				 * be on the same subnet as ip destination,
14312 				 * even though they are on the same
14313 				 * physical link.
14314 				 */
14315 				goto sendit;
14316 			}
14317 
14318 			src = ipha->ipha_src;
14319 
14320 			/*
14321 			 * We look up the interface ire for the nexthop,
14322 			 * to see if ipha_src is in the same subnet
14323 			 * as the nexthop.
14324 			 *
14325 			 * Note that, if, in the future, IRE_CACHE entries
14326 			 * are obsoleted,  this lookup will not be needed,
14327 			 * as the ire passed to this function will be the
14328 			 * same as the nhop_ire computed below.
14329 			 */
14330 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14331 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14332 			    0, NULL, MATCH_IRE_TYPE, ipst);
14333 
14334 			if (nhop_ire != NULL) {
14335 				if ((src & nhop_ire->ire_mask) ==
14336 				    (nhop & nhop_ire->ire_mask)) {
14337 					/*
14338 					 * The source is directly connected.
14339 					 * Just copy the ip header (which is
14340 					 * in the first mblk)
14341 					 */
14342 					mp1 = copyb(mp);
14343 					if (mp1 != NULL) {
14344 						icmp_send_redirect(WR(q), mp1,
14345 						    nhop, ipst);
14346 					}
14347 				}
14348 				ire_refrele(nhop_ire);
14349 			}
14350 		}
14351 	}
14352 sendit:
14353 	dev_q = ire->ire_stq->q_next;
14354 	if (DEV_Q_FLOW_BLOCKED(dev_q)) {
14355 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14356 		freemsg(mp);
14357 		return;
14358 	}
14359 
14360 	ip_rput_forward(ire, ipha, mp, ill);
14361 	return;
14362 
14363 drop_pkt:
14364 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14365 	freemsg(mp);
14366 }
14367 
14368 ire_t *
14369 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14370     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14371 {
14372 	queue_t		*q;
14373 	uint16_t	hcksumflags;
14374 	ip_stack_t	*ipst = ill->ill_ipst;
14375 
14376 	q = *qp;
14377 
14378 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14379 
14380 	/*
14381 	 * Clear the indication that this may have hardware
14382 	 * checksum as we are not using it for forwarding.
14383 	 */
14384 	hcksumflags = DB_CKSUMFLAGS(mp);
14385 	DB_CKSUMFLAGS(mp) = 0;
14386 
14387 	/*
14388 	 * Directed broadcast forwarding: if the packet came in over a
14389 	 * different interface then it is routed out over we can forward it.
14390 	 */
14391 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14392 		ire_refrele(ire);
14393 		freemsg(mp);
14394 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14395 		return (NULL);
14396 	}
14397 	/*
14398 	 * For multicast we have set dst to be INADDR_BROADCAST
14399 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14400 	 * only for broadcast packets.
14401 	 */
14402 	if (!CLASSD(ipha->ipha_dst)) {
14403 		ire_t *new_ire;
14404 		ipif_t *ipif;
14405 		/*
14406 		 * For ill groups, as the switch duplicates broadcasts
14407 		 * across all the ports, we need to filter out and
14408 		 * send up only one copy. There is one copy for every
14409 		 * broadcast address on each ill. Thus, we look for a
14410 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14411 		 * later to see whether this ill is eligible to receive
14412 		 * them or not. ill_nominate_bcast_rcv() nominates only
14413 		 * one set of IREs for receiving.
14414 		 */
14415 
14416 		ipif = ipif_get_next_ipif(NULL, ill);
14417 		if (ipif == NULL) {
14418 			ire_refrele(ire);
14419 			freemsg(mp);
14420 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14421 			return (NULL);
14422 		}
14423 		new_ire = ire_ctable_lookup(dst, 0, 0,
14424 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14425 		ipif_refrele(ipif);
14426 
14427 		if (new_ire != NULL) {
14428 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14429 				ire_refrele(ire);
14430 				ire_refrele(new_ire);
14431 				freemsg(mp);
14432 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14433 				return (NULL);
14434 			}
14435 			/*
14436 			 * In the special case of multirouted broadcast
14437 			 * packets, we unconditionally need to "gateway"
14438 			 * them to the appropriate interface here.
14439 			 * In the normal case, this cannot happen, because
14440 			 * there is no broadcast IRE tagged with the
14441 			 * RTF_MULTIRT flag.
14442 			 */
14443 			if (new_ire->ire_flags & RTF_MULTIRT) {
14444 				ire_refrele(new_ire);
14445 				if (ire->ire_rfq != NULL) {
14446 					q = ire->ire_rfq;
14447 					*qp = q;
14448 				}
14449 			} else {
14450 				ire_refrele(ire);
14451 				ire = new_ire;
14452 			}
14453 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14454 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14455 				/*
14456 				 * Free the message if
14457 				 * ip_g_forward_directed_bcast is turned
14458 				 * off for non-local broadcast.
14459 				 */
14460 				ire_refrele(ire);
14461 				freemsg(mp);
14462 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14463 				return (NULL);
14464 			}
14465 		} else {
14466 			/*
14467 			 * This CGTP packet successfully passed the
14468 			 * CGTP filter, but the related CGTP
14469 			 * broadcast IRE has not been found,
14470 			 * meaning that the redundant ipif is
14471 			 * probably down. However, if we discarded
14472 			 * this packet, its duplicate would be
14473 			 * filtered out by the CGTP filter so none
14474 			 * of them would get through. So we keep
14475 			 * going with this one.
14476 			 */
14477 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14478 			if (ire->ire_rfq != NULL) {
14479 				q = ire->ire_rfq;
14480 				*qp = q;
14481 			}
14482 		}
14483 	}
14484 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14485 		/*
14486 		 * Verify that there are not more then one
14487 		 * IRE_BROADCAST with this broadcast address which
14488 		 * has ire_stq set.
14489 		 * TODO: simplify, loop over all IRE's
14490 		 */
14491 		ire_t	*ire1;
14492 		int	num_stq = 0;
14493 		mblk_t	*mp1;
14494 
14495 		/* Find the first one with ire_stq set */
14496 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14497 		for (ire1 = ire; ire1 &&
14498 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14499 		    ire1 = ire1->ire_next)
14500 			;
14501 		if (ire1) {
14502 			ire_refrele(ire);
14503 			ire = ire1;
14504 			IRE_REFHOLD(ire);
14505 		}
14506 
14507 		/* Check if there are additional ones with stq set */
14508 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14509 			if (ire->ire_addr != ire1->ire_addr)
14510 				break;
14511 			if (ire1->ire_stq) {
14512 				num_stq++;
14513 				break;
14514 			}
14515 		}
14516 		rw_exit(&ire->ire_bucket->irb_lock);
14517 		if (num_stq == 1 && ire->ire_stq != NULL) {
14518 			ip1dbg(("ip_rput_process_broadcast: directed "
14519 			    "broadcast to 0x%x\n",
14520 			    ntohl(ire->ire_addr)));
14521 			mp1 = copymsg(mp);
14522 			if (mp1) {
14523 				switch (ipha->ipha_protocol) {
14524 				case IPPROTO_UDP:
14525 					ip_udp_input(q, mp1, ipha, ire, ill);
14526 					break;
14527 				default:
14528 					ip_proto_input(q, mp1, ipha, ire, ill,
14529 					    0);
14530 					break;
14531 				}
14532 			}
14533 			/*
14534 			 * Adjust ttl to 2 (1+1 - the forward engine
14535 			 * will decrement it by one.
14536 			 */
14537 			if (ip_csum_hdr(ipha)) {
14538 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14539 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14540 				freemsg(mp);
14541 				ire_refrele(ire);
14542 				return (NULL);
14543 			}
14544 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14545 			ipha->ipha_hdr_checksum = 0;
14546 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14547 			ip_rput_process_forward(q, mp, ire, ipha,
14548 			    ill, ll_multicast, B_FALSE);
14549 			ire_refrele(ire);
14550 			return (NULL);
14551 		}
14552 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14553 		    ntohl(ire->ire_addr)));
14554 	}
14555 
14556 
14557 	/* Restore any hardware checksum flags */
14558 	DB_CKSUMFLAGS(mp) = hcksumflags;
14559 	return (ire);
14560 }
14561 
14562 /* ARGSUSED */
14563 static boolean_t
14564 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14565     int *ll_multicast, ipaddr_t *dstp)
14566 {
14567 	ip_stack_t	*ipst = ill->ill_ipst;
14568 
14569 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14570 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14571 	    ntohs(ipha->ipha_length));
14572 
14573 	/*
14574 	 * Forward packets only if we have joined the allmulti
14575 	 * group on this interface.
14576 	 */
14577 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14578 		int retval;
14579 
14580 		/*
14581 		 * Clear the indication that this may have hardware
14582 		 * checksum as we are not using it.
14583 		 */
14584 		DB_CKSUMFLAGS(mp) = 0;
14585 		retval = ip_mforward(ill, ipha, mp);
14586 		/* ip_mforward updates mib variables if needed */
14587 		/* clear b_prev - used by ip_mroute_decap */
14588 		mp->b_prev = NULL;
14589 
14590 		switch (retval) {
14591 		case 0:
14592 			/*
14593 			 * pkt is okay and arrived on phyint.
14594 			 *
14595 			 * If we are running as a multicast router
14596 			 * we need to see all IGMP and/or PIM packets.
14597 			 */
14598 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14599 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14600 				goto done;
14601 			}
14602 			break;
14603 		case -1:
14604 			/* pkt is mal-formed, toss it */
14605 			goto drop_pkt;
14606 		case 1:
14607 			/* pkt is okay and arrived on a tunnel */
14608 			/*
14609 			 * If we are running a multicast router
14610 			 *  we need to see all igmp packets.
14611 			 */
14612 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14613 				*dstp = INADDR_BROADCAST;
14614 				*ll_multicast = 1;
14615 				return (B_FALSE);
14616 			}
14617 
14618 			goto drop_pkt;
14619 		}
14620 	}
14621 
14622 	ILM_WALKER_HOLD(ill);
14623 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14624 		/*
14625 		 * This might just be caused by the fact that
14626 		 * multiple IP Multicast addresses map to the same
14627 		 * link layer multicast - no need to increment counter!
14628 		 */
14629 		ILM_WALKER_RELE(ill);
14630 		freemsg(mp);
14631 		return (B_TRUE);
14632 	}
14633 	ILM_WALKER_RELE(ill);
14634 done:
14635 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14636 	/*
14637 	 * This assumes the we deliver to all streams for multicast
14638 	 * and broadcast packets.
14639 	 */
14640 	*dstp = INADDR_BROADCAST;
14641 	*ll_multicast = 1;
14642 	return (B_FALSE);
14643 drop_pkt:
14644 	ip2dbg(("ip_rput: drop pkt\n"));
14645 	freemsg(mp);
14646 	return (B_TRUE);
14647 }
14648 
14649 /*
14650  * This function is used to both return an indication of whether or not
14651  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14652  * and in doing so, determine whether or not it is broadcast vs multicast.
14653  * For it to be a broadcast packet, we must have the appropriate mblk_t
14654  * hanging off the ill_t.  If this is either not present or doesn't match
14655  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14656  * to be multicast.  Thus NICs that have no broadcast address (or no
14657  * capability for one, such as point to point links) cannot return as
14658  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14659  * the return values simplifies the current use of the return value of this
14660  * function, which is to pass through the multicast/broadcast characteristic
14661  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14662  * changing the return value to some other symbol demands the appropriate
14663  * "translation" when hpe_flags is set prior to calling hook_run() for
14664  * packet events.
14665  */
14666 int
14667 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14668 {
14669 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14670 	mblk_t *bmp;
14671 
14672 	if (ind->dl_group_address) {
14673 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14674 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14675 		    MBLKL(mb) &&
14676 		    (bmp = ill->ill_bcast_mp) != NULL) {
14677 			dl_unitdata_req_t *dlur;
14678 			uint8_t *bphys_addr;
14679 
14680 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14681 			if (ill->ill_sap_length < 0)
14682 				bphys_addr = (uchar_t *)dlur +
14683 				    dlur->dl_dest_addr_offset;
14684 			else
14685 				bphys_addr = (uchar_t *)dlur +
14686 				    dlur->dl_dest_addr_offset +
14687 				    ill->ill_sap_length;
14688 
14689 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14690 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14691 				return (HPE_BROADCAST);
14692 			}
14693 			return (HPE_MULTICAST);
14694 		}
14695 		return (HPE_MULTICAST);
14696 	}
14697 	return (0);
14698 }
14699 
14700 static boolean_t
14701 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14702     int *ll_multicast, mblk_t **mpp)
14703 {
14704 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14705 	boolean_t must_copy = B_FALSE;
14706 	struct iocblk   *iocp;
14707 	ipha_t		*ipha;
14708 	ip_stack_t	*ipst = ill->ill_ipst;
14709 
14710 #define	rptr    ((uchar_t *)ipha)
14711 
14712 	first_mp = *first_mpp;
14713 	mp = *mpp;
14714 
14715 	ASSERT(first_mp == mp);
14716 
14717 	/*
14718 	 * if db_ref > 1 then copymsg and free original. Packet may be
14719 	 * changed and do not want other entity who has a reference to this
14720 	 * message to trip over the changes. This is a blind change because
14721 	 * trying to catch all places that might change packet is too
14722 	 * difficult (since it may be a module above this one)
14723 	 *
14724 	 * This corresponds to the non-fast path case. We walk down the full
14725 	 * chain in this case, and check the db_ref count of all the dblks,
14726 	 * and do a copymsg if required. It is possible that the db_ref counts
14727 	 * of the data blocks in the mblk chain can be different.
14728 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14729 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14730 	 * 'snoop' is running.
14731 	 */
14732 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14733 		if (mp1->b_datap->db_ref > 1) {
14734 			must_copy = B_TRUE;
14735 			break;
14736 		}
14737 	}
14738 
14739 	if (must_copy) {
14740 		mp1 = copymsg(mp);
14741 		if (mp1 == NULL) {
14742 			for (mp1 = mp; mp1 != NULL;
14743 			    mp1 = mp1->b_cont) {
14744 				mp1->b_next = NULL;
14745 				mp1->b_prev = NULL;
14746 			}
14747 			freemsg(mp);
14748 			if (ill != NULL) {
14749 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14750 			} else {
14751 				BUMP_MIB(&ipst->ips_ip_mib,
14752 				    ipIfStatsInDiscards);
14753 			}
14754 			return (B_TRUE);
14755 		}
14756 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14757 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14758 			/* Copy b_prev - used by ip_mroute_decap */
14759 			to_mp->b_prev = from_mp->b_prev;
14760 			from_mp->b_prev = NULL;
14761 		}
14762 		*first_mpp = first_mp = mp1;
14763 		freemsg(mp);
14764 		mp = mp1;
14765 		*mpp = mp1;
14766 	}
14767 
14768 	ipha = (ipha_t *)mp->b_rptr;
14769 
14770 	/*
14771 	 * previous code has a case for M_DATA.
14772 	 * We want to check how that happens.
14773 	 */
14774 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14775 	switch (first_mp->b_datap->db_type) {
14776 	case M_PROTO:
14777 	case M_PCPROTO:
14778 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14779 		    DL_UNITDATA_IND) {
14780 			/* Go handle anything other than data elsewhere. */
14781 			ip_rput_dlpi(q, mp);
14782 			return (B_TRUE);
14783 		}
14784 
14785 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14786 		/* Ditch the DLPI header. */
14787 		mp1 = mp->b_cont;
14788 		ASSERT(first_mp == mp);
14789 		*first_mpp = mp1;
14790 		freeb(mp);
14791 		*mpp = mp1;
14792 		return (B_FALSE);
14793 	case M_IOCACK:
14794 		ip1dbg(("got iocack "));
14795 		iocp = (struct iocblk *)mp->b_rptr;
14796 		switch (iocp->ioc_cmd) {
14797 		case DL_IOC_HDR_INFO:
14798 			ill = (ill_t *)q->q_ptr;
14799 			ill_fastpath_ack(ill, mp);
14800 			return (B_TRUE);
14801 		case SIOCSTUNPARAM:
14802 		case OSIOCSTUNPARAM:
14803 			/* Go through qwriter_ip */
14804 			break;
14805 		case SIOCGTUNPARAM:
14806 		case OSIOCGTUNPARAM:
14807 			ip_rput_other(NULL, q, mp, NULL);
14808 			return (B_TRUE);
14809 		default:
14810 			putnext(q, mp);
14811 			return (B_TRUE);
14812 		}
14813 		/* FALLTHRU */
14814 	case M_ERROR:
14815 	case M_HANGUP:
14816 		/*
14817 		 * Since this is on the ill stream we unconditionally
14818 		 * bump up the refcount
14819 		 */
14820 		ill_refhold(ill);
14821 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14822 		return (B_TRUE);
14823 	case M_CTL:
14824 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14825 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14826 		    IPHADA_M_CTL)) {
14827 			/*
14828 			 * It's an IPsec accelerated packet.
14829 			 * Make sure that the ill from which we received the
14830 			 * packet has enabled IPsec hardware acceleration.
14831 			 */
14832 			if (!(ill->ill_capabilities &
14833 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14834 				/* IPsec kstats: bean counter */
14835 				freemsg(mp);
14836 				return (B_TRUE);
14837 			}
14838 
14839 			/*
14840 			 * Make mp point to the mblk following the M_CTL,
14841 			 * then process according to type of mp.
14842 			 * After this processing, first_mp will point to
14843 			 * the data-attributes and mp to the pkt following
14844 			 * the M_CTL.
14845 			 */
14846 			mp = first_mp->b_cont;
14847 			if (mp == NULL) {
14848 				freemsg(first_mp);
14849 				return (B_TRUE);
14850 			}
14851 			/*
14852 			 * A Hardware Accelerated packet can only be M_DATA
14853 			 * ESP or AH packet.
14854 			 */
14855 			if (mp->b_datap->db_type != M_DATA) {
14856 				/* non-M_DATA IPsec accelerated packet */
14857 				IPSECHW_DEBUG(IPSECHW_PKT,
14858 				    ("non-M_DATA IPsec accelerated pkt\n"));
14859 				freemsg(first_mp);
14860 				return (B_TRUE);
14861 			}
14862 			ipha = (ipha_t *)mp->b_rptr;
14863 			if (ipha->ipha_protocol != IPPROTO_AH &&
14864 			    ipha->ipha_protocol != IPPROTO_ESP) {
14865 				IPSECHW_DEBUG(IPSECHW_PKT,
14866 				    ("non-M_DATA IPsec accelerated pkt\n"));
14867 				freemsg(first_mp);
14868 				return (B_TRUE);
14869 			}
14870 			*mpp = mp;
14871 			return (B_FALSE);
14872 		}
14873 		putnext(q, mp);
14874 		return (B_TRUE);
14875 	case M_IOCNAK:
14876 		ip1dbg(("got iocnak "));
14877 		iocp = (struct iocblk *)mp->b_rptr;
14878 		switch (iocp->ioc_cmd) {
14879 		case SIOCSTUNPARAM:
14880 		case OSIOCSTUNPARAM:
14881 			/*
14882 			 * Since this is on the ill stream we unconditionally
14883 			 * bump up the refcount
14884 			 */
14885 			ill_refhold(ill);
14886 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14887 			return (B_TRUE);
14888 		case DL_IOC_HDR_INFO:
14889 		case SIOCGTUNPARAM:
14890 		case OSIOCGTUNPARAM:
14891 			ip_rput_other(NULL, q, mp, NULL);
14892 			return (B_TRUE);
14893 		default:
14894 			break;
14895 		}
14896 		/* FALLTHRU */
14897 	default:
14898 		putnext(q, mp);
14899 		return (B_TRUE);
14900 	}
14901 }
14902 
14903 /* Read side put procedure.  Packets coming from the wire arrive here. */
14904 void
14905 ip_rput(queue_t *q, mblk_t *mp)
14906 {
14907 	ill_t	*ill;
14908 	union DL_primitives *dl;
14909 
14910 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14911 
14912 	ill = (ill_t *)q->q_ptr;
14913 
14914 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14915 		/*
14916 		 * If things are opening or closing, only accept high-priority
14917 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14918 		 * created; on close, things hanging off the ill may have been
14919 		 * freed already.)
14920 		 */
14921 		dl = (union DL_primitives *)mp->b_rptr;
14922 		if (DB_TYPE(mp) != M_PCPROTO ||
14923 		    dl->dl_primitive == DL_UNITDATA_IND) {
14924 			/*
14925 			 * SIOC[GS]TUNPARAM ioctls can come here.
14926 			 */
14927 			inet_freemsg(mp);
14928 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14929 			    "ip_rput_end: q %p (%S)", q, "uninit");
14930 			return;
14931 		}
14932 	}
14933 
14934 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14935 	    "ip_rput_end: q %p (%S)", q, "end");
14936 
14937 	ip_input(ill, NULL, mp, NULL);
14938 }
14939 
14940 static mblk_t *
14941 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14942 {
14943 	mblk_t *mp1;
14944 	boolean_t adjusted = B_FALSE;
14945 	ip_stack_t *ipst = ill->ill_ipst;
14946 
14947 	IP_STAT(ipst, ip_db_ref);
14948 	/*
14949 	 * The IP_RECVSLLA option depends on having the
14950 	 * link layer header. First check that:
14951 	 * a> the underlying device is of type ether,
14952 	 * since this option is currently supported only
14953 	 * over ethernet.
14954 	 * b> there is enough room to copy over the link
14955 	 * layer header.
14956 	 *
14957 	 * Once the checks are done, adjust rptr so that
14958 	 * the link layer header will be copied via
14959 	 * copymsg. Note that, IFT_ETHER may be returned
14960 	 * by some non-ethernet drivers but in this case
14961 	 * the second check will fail.
14962 	 */
14963 	if (ill->ill_type == IFT_ETHER &&
14964 	    (mp->b_rptr - mp->b_datap->db_base) >=
14965 	    sizeof (struct ether_header)) {
14966 		mp->b_rptr -= sizeof (struct ether_header);
14967 		adjusted = B_TRUE;
14968 	}
14969 	mp1 = copymsg(mp);
14970 
14971 	if (mp1 == NULL) {
14972 		mp->b_next = NULL;
14973 		/* clear b_prev - used by ip_mroute_decap */
14974 		mp->b_prev = NULL;
14975 		freemsg(mp);
14976 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14977 		return (NULL);
14978 	}
14979 
14980 	if (adjusted) {
14981 		/*
14982 		 * Copy is done. Restore the pointer in
14983 		 * the _new_ mblk
14984 		 */
14985 		mp1->b_rptr += sizeof (struct ether_header);
14986 	}
14987 
14988 	/* Copy b_prev - used by ip_mroute_decap */
14989 	mp1->b_prev = mp->b_prev;
14990 	mp->b_prev = NULL;
14991 
14992 	/* preserve the hardware checksum flags and data, if present */
14993 	if (DB_CKSUMFLAGS(mp) != 0) {
14994 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14995 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14996 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14997 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14998 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14999 	}
15000 
15001 	freemsg(mp);
15002 	return (mp1);
15003 }
15004 
15005 #define	ADD_TO_CHAIN(head, tail, cnt, mp) {    			\
15006 	if (tail != NULL)					\
15007 		tail->b_next = mp;				\
15008 	else							\
15009 		head = mp;					\
15010 	tail = mp;						\
15011 	cnt++;							\
15012 }
15013 
15014 /*
15015  * Direct read side procedure capable of dealing with chains. GLDv3 based
15016  * drivers call this function directly with mblk chains while STREAMS
15017  * read side procedure ip_rput() calls this for single packet with ip_ring
15018  * set to NULL to process one packet at a time.
15019  *
15020  * The ill will always be valid if this function is called directly from
15021  * the driver.
15022  *
15023  * If ip_input() is called from GLDv3:
15024  *
15025  *   - This must be a non-VLAN IP stream.
15026  *   - 'mp' is either an untagged or a special priority-tagged packet.
15027  *   - Any VLAN tag that was in the MAC header has been stripped.
15028  *
15029  * If the IP header in packet is not 32-bit aligned, every message in the
15030  * chain will be aligned before further operations. This is required on SPARC
15031  * platform.
15032  */
15033 /* ARGSUSED */
15034 void
15035 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
15036     struct mac_header_info_s *mhip)
15037 {
15038 	ipaddr_t		dst = NULL;
15039 	ipaddr_t		prev_dst;
15040 	ire_t			*ire = NULL;
15041 	ipha_t			*ipha;
15042 	uint_t			pkt_len;
15043 	ssize_t			len;
15044 	uint_t			opt_len;
15045 	int			ll_multicast;
15046 	int			cgtp_flt_pkt;
15047 	queue_t			*q = ill->ill_rq;
15048 	squeue_t		*curr_sqp = NULL;
15049 	mblk_t 			*head = NULL;
15050 	mblk_t			*tail = NULL;
15051 	mblk_t			*first_mp;
15052 	int			cnt = 0;
15053 	ip_stack_t		*ipst = ill->ill_ipst;
15054 	mblk_t			*mp;
15055 	mblk_t			*dmp;
15056 	uint8_t			tag;
15057 
15058 	ASSERT(mp_chain != NULL);
15059 	ASSERT(ill != NULL);
15060 
15061 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
15062 
15063 	tag = (ip_ring != NULL) ? SQTAG_IP_INPUT_RX_RING : SQTAG_IP_INPUT;
15064 
15065 #define	rptr	((uchar_t *)ipha)
15066 
15067 	while (mp_chain != NULL) {
15068 		mp = mp_chain;
15069 		mp_chain = mp_chain->b_next;
15070 		mp->b_next = NULL;
15071 		ll_multicast = 0;
15072 
15073 		/*
15074 		 * We do ire caching from one iteration to
15075 		 * another. In the event the packet chain contains
15076 		 * all packets from the same dst, this caching saves
15077 		 * an ire_cache_lookup for each of the succeeding
15078 		 * packets in a packet chain.
15079 		 */
15080 		prev_dst = dst;
15081 
15082 		/*
15083 		 * if db_ref > 1 then copymsg and free original. Packet
15084 		 * may be changed and we do not want the other entity
15085 		 * who has a reference to this message to trip over the
15086 		 * changes. This is a blind change because trying to
15087 		 * catch all places that might change the packet is too
15088 		 * difficult.
15089 		 *
15090 		 * This corresponds to the fast path case, where we have
15091 		 * a chain of M_DATA mblks.  We check the db_ref count
15092 		 * of only the 1st data block in the mblk chain. There
15093 		 * doesn't seem to be a reason why a device driver would
15094 		 * send up data with varying db_ref counts in the mblk
15095 		 * chain. In any case the Fast path is a private
15096 		 * interface, and our drivers don't do such a thing.
15097 		 * Given the above assumption, there is no need to walk
15098 		 * down the entire mblk chain (which could have a
15099 		 * potential performance problem)
15100 		 *
15101 		 * The "(DB_REF(mp) > 1)" check was moved from ip_rput()
15102 		 * to here because of exclusive ip stacks and vnics.
15103 		 * Packets transmitted from exclusive stack over vnic
15104 		 * can have db_ref > 1 and when it gets looped back to
15105 		 * another vnic in a different zone, you have ip_input()
15106 		 * getting dblks with db_ref > 1. So if someone
15107 		 * complains of TCP performance under this scenario,
15108 		 * take a serious look here on the impact of copymsg().
15109 		 */
15110 
15111 		if (DB_REF(mp) > 1) {
15112 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
15113 				continue;
15114 		}
15115 
15116 		/*
15117 		 * Check and align the IP header.
15118 		 */
15119 		first_mp = mp;
15120 		if (DB_TYPE(mp) == M_DATA) {
15121 			dmp = mp;
15122 		} else if (DB_TYPE(mp) == M_PROTO &&
15123 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
15124 			dmp = mp->b_cont;
15125 		} else {
15126 			dmp = NULL;
15127 		}
15128 		if (dmp != NULL) {
15129 			/*
15130 			 * IP header ptr not aligned?
15131 			 * OR IP header not complete in first mblk
15132 			 */
15133 			if (!OK_32PTR(dmp->b_rptr) ||
15134 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
15135 				if (!ip_check_and_align_header(q, dmp, ipst))
15136 					continue;
15137 			}
15138 		}
15139 
15140 		/*
15141 		 * ip_input fast path
15142 		 */
15143 
15144 		/* mblk type is not M_DATA */
15145 		if (DB_TYPE(mp) != M_DATA) {
15146 			if (ip_rput_process_notdata(q, &first_mp, ill,
15147 			    &ll_multicast, &mp))
15148 				continue;
15149 
15150 			/*
15151 			 * The only way we can get here is if we had a
15152 			 * packet that was either a DL_UNITDATA_IND or
15153 			 * an M_CTL for an IPsec accelerated packet.
15154 			 *
15155 			 * In either case, the first_mp will point to
15156 			 * the leading M_PROTO or M_CTL.
15157 			 */
15158 			ASSERT(first_mp != NULL);
15159 		} else if (mhip != NULL) {
15160 			/*
15161 			 * ll_multicast is set here so that it is ready
15162 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
15163 			 * manipulates ll_multicast in the same fashion when
15164 			 * called from ip_rput_process_notdata.
15165 			 */
15166 			switch (mhip->mhi_dsttype) {
15167 			case MAC_ADDRTYPE_MULTICAST :
15168 				ll_multicast = HPE_MULTICAST;
15169 				break;
15170 			case MAC_ADDRTYPE_BROADCAST :
15171 				ll_multicast = HPE_BROADCAST;
15172 				break;
15173 			default :
15174 				break;
15175 			}
15176 		}
15177 
15178 		/* Only M_DATA can come here and it is always aligned */
15179 		ASSERT(DB_TYPE(mp) == M_DATA);
15180 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15181 
15182 		ipha = (ipha_t *)mp->b_rptr;
15183 		len = mp->b_wptr - rptr;
15184 		pkt_len = ntohs(ipha->ipha_length);
15185 
15186 		/*
15187 		 * We must count all incoming packets, even if they end
15188 		 * up being dropped later on.
15189 		 */
15190 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15191 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15192 
15193 		/* multiple mblk or too short */
15194 		len -= pkt_len;
15195 		if (len != 0) {
15196 			/*
15197 			 * Make sure we have data length consistent
15198 			 * with the IP header.
15199 			 */
15200 			if (mp->b_cont == NULL) {
15201 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15202 					BUMP_MIB(ill->ill_ip_mib,
15203 					    ipIfStatsInHdrErrors);
15204 					ip2dbg(("ip_input: drop pkt\n"));
15205 					freemsg(mp);
15206 					continue;
15207 				}
15208 				mp->b_wptr = rptr + pkt_len;
15209 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15210 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15211 					BUMP_MIB(ill->ill_ip_mib,
15212 					    ipIfStatsInHdrErrors);
15213 					ip2dbg(("ip_input: drop pkt\n"));
15214 					freemsg(mp);
15215 					continue;
15216 				}
15217 				(void) adjmsg(mp, -len);
15218 				IP_STAT(ipst, ip_multimblk3);
15219 			}
15220 		}
15221 
15222 		/* Obtain the dst of the current packet */
15223 		dst = ipha->ipha_dst;
15224 
15225 		DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL,
15226 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *,
15227 		    ipha, ip6_t *, NULL, int, 0);
15228 
15229 		/*
15230 		 * The following test for loopback is faster than
15231 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15232 		 * operations.
15233 		 * Note that these addresses are always in network byte order
15234 		 */
15235 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15236 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15237 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15238 			freemsg(mp);
15239 			continue;
15240 		}
15241 
15242 		/*
15243 		 * The event for packets being received from a 'physical'
15244 		 * interface is placed after validation of the source and/or
15245 		 * destination address as being local so that packets can be
15246 		 * redirected to loopback addresses using ipnat.
15247 		 */
15248 		DTRACE_PROBE4(ip4__physical__in__start,
15249 		    ill_t *, ill, ill_t *, NULL,
15250 		    ipha_t *, ipha, mblk_t *, first_mp);
15251 
15252 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15253 		    ipst->ips_ipv4firewall_physical_in,
15254 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
15255 
15256 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15257 
15258 		if (first_mp == NULL) {
15259 			continue;
15260 		}
15261 		dst = ipha->ipha_dst;
15262 		/*
15263 		 * Attach any necessary label information to
15264 		 * this packet
15265 		 */
15266 		if (is_system_labeled() &&
15267 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15268 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15269 			freemsg(mp);
15270 			continue;
15271 		}
15272 
15273 		if (ipst->ips_ipobs_enabled) {
15274 			zoneid_t dzone;
15275 
15276 			/*
15277 			 * On the inbound path the src zone will be unknown as
15278 			 * this packet has come from the wire.
15279 			 */
15280 			dzone = ip_get_zoneid_v4(dst, mp, ipst, ALL_ZONES);
15281 			ipobs_hook(mp, IPOBS_HOOK_INBOUND, ALL_ZONES, dzone,
15282 			    ill, IPV4_VERSION, 0, ipst);
15283 		}
15284 
15285 		/*
15286 		 * Reuse the cached ire only if the ipha_dst of the previous
15287 		 * packet is the same as the current packet AND it is not
15288 		 * INADDR_ANY.
15289 		 */
15290 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15291 		    (ire != NULL)) {
15292 			ire_refrele(ire);
15293 			ire = NULL;
15294 		}
15295 
15296 		opt_len = ipha->ipha_version_and_hdr_length -
15297 		    IP_SIMPLE_HDR_VERSION;
15298 
15299 		/*
15300 		 * Check to see if we can take the fastpath.
15301 		 * That is possible if the following conditions are met
15302 		 *	o Tsol disabled
15303 		 *	o CGTP disabled
15304 		 *	o ipp_action_count is 0
15305 		 *	o no options in the packet
15306 		 *	o not a RSVP packet
15307 		 * 	o not a multicast packet
15308 		 *	o ill not in IP_DHCPINIT_IF mode
15309 		 */
15310 		if (!is_system_labeled() &&
15311 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15312 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15313 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15314 			if (ire == NULL)
15315 				ire = ire_cache_lookup_simple(dst, ipst);
15316 			/*
15317 			 * Unless forwarding is enabled, dont call
15318 			 * ip_fast_forward(). Incoming packet is for forwarding
15319 			 */
15320 			if ((ill->ill_flags & ILLF_ROUTER) &&
15321 			    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15322 				ire = ip_fast_forward(ire, dst, ill, mp);
15323 				continue;
15324 			}
15325 			/* incoming packet is for local consumption */
15326 			if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15327 				goto local;
15328 		}
15329 
15330 		/*
15331 		 * Disable ire caching for anything more complex
15332 		 * than the simple fast path case we checked for above.
15333 		 */
15334 		if (ire != NULL) {
15335 			ire_refrele(ire);
15336 			ire = NULL;
15337 		}
15338 
15339 		/*
15340 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15341 		 * server to unicast DHCP packets to a DHCP client using the
15342 		 * IP address it is offering to the client.  This can be
15343 		 * disabled through the "broadcast bit", but not all DHCP
15344 		 * servers honor that bit.  Therefore, to interoperate with as
15345 		 * many DHCP servers as possible, the DHCP client allows the
15346 		 * server to unicast, but we treat those packets as broadcast
15347 		 * here.  Note that we don't rewrite the packet itself since
15348 		 * (a) that would mess up the checksums and (b) the DHCP
15349 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15350 		 * hand it the packet regardless.
15351 		 */
15352 		if (ill->ill_dhcpinit != 0 &&
15353 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15354 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15355 			udpha_t *udpha;
15356 
15357 			/*
15358 			 * Reload ipha since pullupmsg() can change b_rptr.
15359 			 */
15360 			ipha = (ipha_t *)mp->b_rptr;
15361 			udpha = (udpha_t *)&ipha[1];
15362 
15363 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15364 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15365 				    mblk_t *, mp);
15366 				dst = INADDR_BROADCAST;
15367 			}
15368 		}
15369 
15370 		/* Full-blown slow path */
15371 		if (opt_len != 0) {
15372 			if (len != 0)
15373 				IP_STAT(ipst, ip_multimblk4);
15374 			else
15375 				IP_STAT(ipst, ip_ipoptions);
15376 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15377 			    &dst, ipst))
15378 				continue;
15379 		}
15380 
15381 		/*
15382 		 * Invoke the CGTP (multirouting) filtering module to process
15383 		 * the incoming packet. Packets identified as duplicates
15384 		 * must be discarded. Filtering is active only if the
15385 		 * the ip_cgtp_filter ndd variable is non-zero.
15386 		 */
15387 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15388 		if (ipst->ips_ip_cgtp_filter &&
15389 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15390 			netstackid_t stackid;
15391 
15392 			stackid = ipst->ips_netstack->netstack_stackid;
15393 			cgtp_flt_pkt =
15394 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15395 			    ill->ill_phyint->phyint_ifindex, mp);
15396 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15397 				freemsg(first_mp);
15398 				continue;
15399 			}
15400 		}
15401 
15402 		/*
15403 		 * If rsvpd is running, let RSVP daemon handle its processing
15404 		 * and forwarding of RSVP multicast/unicast packets.
15405 		 * If rsvpd is not running but mrouted is running, RSVP
15406 		 * multicast packets are forwarded as multicast traffic
15407 		 * and RSVP unicast packets are forwarded by unicast router.
15408 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15409 		 * packets are not forwarded, but the unicast packets are
15410 		 * forwarded like unicast traffic.
15411 		 */
15412 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15413 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15414 		    NULL) {
15415 			/* RSVP packet and rsvpd running. Treat as ours */
15416 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15417 			/*
15418 			 * This assumes that we deliver to all streams for
15419 			 * multicast and broadcast packets.
15420 			 * We have to force ll_multicast to 1 to handle the
15421 			 * M_DATA messages passed in from ip_mroute_decap.
15422 			 */
15423 			dst = INADDR_BROADCAST;
15424 			ll_multicast = 1;
15425 		} else if (CLASSD(dst)) {
15426 			/* packet is multicast */
15427 			mp->b_next = NULL;
15428 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15429 			    &ll_multicast, &dst))
15430 				continue;
15431 		}
15432 
15433 		if (ire == NULL) {
15434 			ire = ire_cache_lookup(dst, ALL_ZONES,
15435 			    MBLK_GETLABEL(mp), ipst);
15436 		}
15437 
15438 		if (ire != NULL && ire->ire_stq != NULL &&
15439 		    ire->ire_zoneid != GLOBAL_ZONEID &&
15440 		    ire->ire_zoneid != ALL_ZONES) {
15441 			/*
15442 			 * Should only use IREs that are visible from the
15443 			 * global zone for forwarding.
15444 			 */
15445 			ire_refrele(ire);
15446 			ire = ire_cache_lookup(dst, GLOBAL_ZONEID,
15447 			    MBLK_GETLABEL(mp), ipst);
15448 		}
15449 
15450 		if (ire == NULL) {
15451 			/*
15452 			 * No IRE for this destination, so it can't be for us.
15453 			 * Unless we are forwarding, drop the packet.
15454 			 * We have to let source routed packets through
15455 			 * since we don't yet know if they are 'ping -l'
15456 			 * packets i.e. if they will go out over the
15457 			 * same interface as they came in on.
15458 			 */
15459 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15460 			if (ire == NULL)
15461 				continue;
15462 		}
15463 
15464 		/*
15465 		 * Broadcast IRE may indicate either broadcast or
15466 		 * multicast packet
15467 		 */
15468 		if (ire->ire_type == IRE_BROADCAST) {
15469 			/*
15470 			 * Skip broadcast checks if packet is UDP multicast;
15471 			 * we'd rather not enter ip_rput_process_broadcast()
15472 			 * unless the packet is broadcast for real, since
15473 			 * that routine is a no-op for multicast.
15474 			 */
15475 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15476 			    !CLASSD(ipha->ipha_dst)) {
15477 				ire = ip_rput_process_broadcast(&q, mp,
15478 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15479 				    ll_multicast);
15480 				if (ire == NULL)
15481 					continue;
15482 			}
15483 		} else if (ire->ire_stq != NULL) {
15484 			/* fowarding? */
15485 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15486 			    ll_multicast, B_FALSE);
15487 			/* ip_rput_process_forward consumed the packet */
15488 			continue;
15489 		}
15490 
15491 local:
15492 		/*
15493 		 * If the queue in the ire is different to the ingress queue
15494 		 * then we need to check to see if we can accept the packet.
15495 		 * Note that for multicast packets and broadcast packets sent
15496 		 * to a broadcast address which is shared between multiple
15497 		 * interfaces we should not do this since we just got a random
15498 		 * broadcast ire.
15499 		 */
15500 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15501 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15502 			    ill)) == NULL) {
15503 				/* Drop packet */
15504 				BUMP_MIB(ill->ill_ip_mib,
15505 				    ipIfStatsForwProhibits);
15506 				freemsg(mp);
15507 				continue;
15508 			}
15509 			if (ire->ire_rfq != NULL)
15510 				q = ire->ire_rfq;
15511 		}
15512 
15513 		switch (ipha->ipha_protocol) {
15514 		case IPPROTO_TCP:
15515 			ASSERT(first_mp == mp);
15516 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15517 			    mp, 0, q, ip_ring)) != NULL) {
15518 				if (curr_sqp == NULL) {
15519 					curr_sqp = GET_SQUEUE(mp);
15520 					ASSERT(cnt == 0);
15521 					cnt++;
15522 					head = tail = mp;
15523 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15524 					ASSERT(tail != NULL);
15525 					cnt++;
15526 					tail->b_next = mp;
15527 					tail = mp;
15528 				} else {
15529 					/*
15530 					 * A different squeue. Send the
15531 					 * chain for the previous squeue on
15532 					 * its way. This shouldn't happen
15533 					 * often unless interrupt binding
15534 					 * changes.
15535 					 */
15536 					IP_STAT(ipst, ip_input_multi_squeue);
15537 					SQUEUE_ENTER(curr_sqp, head,
15538 					    tail, cnt, SQ_PROCESS, tag);
15539 					curr_sqp = GET_SQUEUE(mp);
15540 					head = mp;
15541 					tail = mp;
15542 					cnt = 1;
15543 				}
15544 			}
15545 			continue;
15546 		case IPPROTO_UDP:
15547 			ASSERT(first_mp == mp);
15548 			ip_udp_input(q, mp, ipha, ire, ill);
15549 			continue;
15550 		case IPPROTO_SCTP:
15551 			ASSERT(first_mp == mp);
15552 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15553 			    q, dst);
15554 			/* ire has been released by ip_sctp_input */
15555 			ire = NULL;
15556 			continue;
15557 		default:
15558 			ip_proto_input(q, first_mp, ipha, ire, ill, 0);
15559 			continue;
15560 		}
15561 	}
15562 
15563 	if (ire != NULL)
15564 		ire_refrele(ire);
15565 
15566 	if (head != NULL)
15567 		SQUEUE_ENTER(curr_sqp, head, tail, cnt, SQ_PROCESS, tag);
15568 
15569 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15570 	    "ip_input_end: q %p (%S)", q, "end");
15571 #undef  rptr
15572 }
15573 
15574 /*
15575  * ip_accept_tcp() - This function is called by the squeue when it retrieves
15576  * a chain of packets in the poll mode. The packets have gone through the
15577  * data link processing but not IP processing. For performance and latency
15578  * reasons, the squeue wants to process the chain in line instead of feeding
15579  * it back via ip_input path.
15580  *
15581  * So this is a light weight function which checks to see if the packets
15582  * retrived are indeed TCP packets (TCP squeue always polls TCP soft ring
15583  * but we still do the paranoid check) meant for local machine and we don't
15584  * have labels etc enabled. Packets that meet the criterion are returned to
15585  * the squeue and processed inline while the rest go via ip_input path.
15586  */
15587 /*ARGSUSED*/
15588 mblk_t *
15589 ip_accept_tcp(ill_t *ill, ill_rx_ring_t *ip_ring, squeue_t *target_sqp,
15590     mblk_t *mp_chain, mblk_t **last, uint_t *cnt)
15591 {
15592 	mblk_t 		*mp;
15593 	ipaddr_t	dst = NULL;
15594 	ipaddr_t	prev_dst;
15595 	ire_t		*ire = NULL;
15596 	ipha_t		*ipha;
15597 	uint_t		pkt_len;
15598 	ssize_t		len;
15599 	uint_t		opt_len;
15600 	queue_t		*q = ill->ill_rq;
15601 	squeue_t	*curr_sqp;
15602 	mblk_t 		*ahead = NULL;	/* Accepted head */
15603 	mblk_t		*atail = NULL;	/* Accepted tail */
15604 	uint_t		acnt = 0;	/* Accepted count */
15605 	mblk_t		*utail = NULL;	/* Unaccepted head */
15606 	mblk_t		*uhead = NULL;	/* Unaccepted tail */
15607 	uint_t		ucnt = 0;	/* Unaccepted cnt */
15608 	ip_stack_t	*ipst = ill->ill_ipst;
15609 
15610 	*cnt = 0;
15611 
15612 	ASSERT(ill != NULL);
15613 	ASSERT(ip_ring != NULL);
15614 
15615 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_accept_tcp: q %p", q);
15616 
15617 #define	rptr	((uchar_t *)ipha)
15618 
15619 	while (mp_chain != NULL) {
15620 		mp = mp_chain;
15621 		mp_chain = mp_chain->b_next;
15622 		mp->b_next = NULL;
15623 
15624 		/*
15625 		 * We do ire caching from one iteration to
15626 		 * another. In the event the packet chain contains
15627 		 * all packets from the same dst, this caching saves
15628 		 * an ire_cache_lookup for each of the succeeding
15629 		 * packets in a packet chain.
15630 		 */
15631 		prev_dst = dst;
15632 
15633 		ipha = (ipha_t *)mp->b_rptr;
15634 		len = mp->b_wptr - rptr;
15635 
15636 		ASSERT(!MBLK_RX_FANOUT_SLOWPATH(mp, ipha));
15637 
15638 		/*
15639 		 * If it is a non TCP packet, or doesn't have H/W cksum,
15640 		 * or doesn't have min len, reject.
15641 		 */
15642 		if ((ipha->ipha_protocol != IPPROTO_TCP) || (len <
15643 		    (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH))) {
15644 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15645 			continue;
15646 		}
15647 
15648 		pkt_len = ntohs(ipha->ipha_length);
15649 		if (len != pkt_len) {
15650 			if (len > pkt_len) {
15651 				mp->b_wptr = rptr + pkt_len;
15652 			} else {
15653 				ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15654 				continue;
15655 			}
15656 		}
15657 
15658 		opt_len = ipha->ipha_version_and_hdr_length -
15659 		    IP_SIMPLE_HDR_VERSION;
15660 		dst = ipha->ipha_dst;
15661 
15662 		/* IP version bad or there are IP options */
15663 		if (opt_len && (!ip_rput_multimblk_ipoptions(q, ill,
15664 		    mp, &ipha, &dst, ipst)))
15665 			continue;
15666 
15667 		if (is_system_labeled() || (ill->ill_dhcpinit != 0) ||
15668 		    (ipst->ips_ip_cgtp_filter &&
15669 		    ipst->ips_ip_cgtp_filter_ops != NULL)) {
15670 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15671 			continue;
15672 		}
15673 
15674 		/*
15675 		 * Reuse the cached ire only if the ipha_dst of the previous
15676 		 * packet is the same as the current packet AND it is not
15677 		 * INADDR_ANY.
15678 		 */
15679 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15680 		    (ire != NULL)) {
15681 			ire_refrele(ire);
15682 			ire = NULL;
15683 		}
15684 
15685 		if (ire == NULL)
15686 			ire = ire_cache_lookup_simple(dst, ipst);
15687 
15688 		/*
15689 		 * Unless forwarding is enabled, dont call
15690 		 * ip_fast_forward(). Incoming packet is for forwarding
15691 		 */
15692 		if ((ill->ill_flags & ILLF_ROUTER) &&
15693 		    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15694 
15695 			DTRACE_PROBE4(ip4__physical__in__start,
15696 			    ill_t *, ill, ill_t *, NULL,
15697 			    ipha_t *, ipha, mblk_t *, mp);
15698 
15699 			FW_HOOKS(ipst->ips_ip4_physical_in_event,
15700 			    ipst->ips_ipv4firewall_physical_in,
15701 			    ill, NULL, ipha, mp, mp, 0, ipst);
15702 
15703 			DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15704 
15705 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15706 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets,
15707 			    pkt_len);
15708 
15709 			ire = ip_fast_forward(ire, dst, ill, mp);
15710 			continue;
15711 		}
15712 
15713 		/* incoming packet is for local consumption */
15714 		if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15715 			goto local_accept;
15716 
15717 		/*
15718 		 * Disable ire caching for anything more complex
15719 		 * than the simple fast path case we checked for above.
15720 		 */
15721 		if (ire != NULL) {
15722 			ire_refrele(ire);
15723 			ire = NULL;
15724 		}
15725 
15726 		ire = ire_cache_lookup(dst, ALL_ZONES, MBLK_GETLABEL(mp),
15727 		    ipst);
15728 		if (ire == NULL || ire->ire_type == IRE_BROADCAST ||
15729 		    ire->ire_stq != NULL) {
15730 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15731 			if (ire != NULL) {
15732 				ire_refrele(ire);
15733 				ire = NULL;
15734 			}
15735 			continue;
15736 		}
15737 
15738 local_accept:
15739 
15740 		if (ire->ire_rfq != q) {
15741 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15742 			if (ire != NULL) {
15743 				ire_refrele(ire);
15744 				ire = NULL;
15745 			}
15746 			continue;
15747 		}
15748 
15749 		/*
15750 		 * The event for packets being received from a 'physical'
15751 		 * interface is placed after validation of the source and/or
15752 		 * destination address as being local so that packets can be
15753 		 * redirected to loopback addresses using ipnat.
15754 		 */
15755 		DTRACE_PROBE4(ip4__physical__in__start,
15756 		    ill_t *, ill, ill_t *, NULL,
15757 		    ipha_t *, ipha, mblk_t *, mp);
15758 
15759 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15760 		    ipst->ips_ipv4firewall_physical_in,
15761 		    ill, NULL, ipha, mp, mp, 0, ipst);
15762 
15763 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15764 
15765 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15766 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15767 
15768 		if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire, mp,
15769 		    0, q, ip_ring)) != NULL) {
15770 			if ((curr_sqp = GET_SQUEUE(mp)) == target_sqp) {
15771 				ADD_TO_CHAIN(ahead, atail, acnt, mp);
15772 			} else {
15773 				SQUEUE_ENTER(curr_sqp, mp, mp, 1,
15774 				    SQ_FILL, SQTAG_IP_INPUT);
15775 			}
15776 		}
15777 	}
15778 
15779 	if (ire != NULL)
15780 		ire_refrele(ire);
15781 
15782 	if (uhead != NULL)
15783 		ip_input(ill, ip_ring, uhead, NULL);
15784 
15785 	if (ahead != NULL) {
15786 		*last = atail;
15787 		*cnt = acnt;
15788 		return (ahead);
15789 	}
15790 
15791 	return (NULL);
15792 #undef  rptr
15793 }
15794 
15795 static void
15796 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15797     t_uscalar_t err)
15798 {
15799 	if (dl_err == DL_SYSERR) {
15800 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15801 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15802 		    ill->ill_name, dl_primstr(prim), err);
15803 		return;
15804 	}
15805 
15806 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15807 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15808 	    dl_errstr(dl_err));
15809 }
15810 
15811 /*
15812  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15813  * than DL_UNITDATA_IND messages. If we need to process this message
15814  * exclusively, we call qwriter_ip, in which case we also need to call
15815  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15816  */
15817 void
15818 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15819 {
15820 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15821 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15822 	ill_t		*ill = q->q_ptr;
15823 	t_uscalar_t	prim = dloa->dl_primitive;
15824 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
15825 
15826 	ip1dbg(("ip_rput_dlpi"));
15827 
15828 	/*
15829 	 * If we received an ACK but didn't send a request for it, then it
15830 	 * can't be part of any pending operation; discard up-front.
15831 	 */
15832 	switch (prim) {
15833 	case DL_ERROR_ACK:
15834 		reqprim = dlea->dl_error_primitive;
15835 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
15836 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
15837 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
15838 		    dlea->dl_unix_errno));
15839 		break;
15840 	case DL_OK_ACK:
15841 		reqprim = dloa->dl_correct_primitive;
15842 		break;
15843 	case DL_INFO_ACK:
15844 		reqprim = DL_INFO_REQ;
15845 		break;
15846 	case DL_BIND_ACK:
15847 		reqprim = DL_BIND_REQ;
15848 		break;
15849 	case DL_PHYS_ADDR_ACK:
15850 		reqprim = DL_PHYS_ADDR_REQ;
15851 		break;
15852 	case DL_NOTIFY_ACK:
15853 		reqprim = DL_NOTIFY_REQ;
15854 		break;
15855 	case DL_CONTROL_ACK:
15856 		reqprim = DL_CONTROL_REQ;
15857 		break;
15858 	case DL_CAPABILITY_ACK:
15859 		reqprim = DL_CAPABILITY_REQ;
15860 		break;
15861 	}
15862 
15863 	if (prim != DL_NOTIFY_IND) {
15864 		if (reqprim == DL_PRIM_INVAL ||
15865 		    !ill_dlpi_pending(ill, reqprim)) {
15866 			/* Not a DLPI message we support or expected */
15867 			freemsg(mp);
15868 			return;
15869 		}
15870 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
15871 		    dl_primstr(reqprim)));
15872 	}
15873 
15874 	switch (reqprim) {
15875 	case DL_UNBIND_REQ:
15876 		/*
15877 		 * NOTE: we mark the unbind as complete even if we got a
15878 		 * DL_ERROR_ACK, since there's not much else we can do.
15879 		 */
15880 		mutex_enter(&ill->ill_lock);
15881 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15882 		cv_signal(&ill->ill_cv);
15883 		mutex_exit(&ill->ill_lock);
15884 		break;
15885 
15886 	case DL_ENABMULTI_REQ:
15887 		if (prim == DL_OK_ACK) {
15888 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15889 				ill->ill_dlpi_multicast_state = IDS_OK;
15890 		}
15891 		break;
15892 	}
15893 
15894 	/*
15895 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
15896 	 * need to become writer to continue to process it.  Because an
15897 	 * exclusive operation doesn't complete until replies to all queued
15898 	 * DLPI messages have been received, we know we're in the middle of an
15899 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
15900 	 *
15901 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15902 	 * Since this is on the ill stream we unconditionally bump up the
15903 	 * refcount without doing ILL_CAN_LOOKUP().
15904 	 */
15905 	ill_refhold(ill);
15906 	if (prim == DL_NOTIFY_IND)
15907 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15908 	else
15909 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15910 }
15911 
15912 /*
15913  * Handling of DLPI messages that require exclusive access to the ipsq.
15914  *
15915  * Need to do ill_pending_mp_release on ioctl completion, which could
15916  * happen here. (along with mi_copy_done)
15917  */
15918 /* ARGSUSED */
15919 static void
15920 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15921 {
15922 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15923 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15924 	int		err = 0;
15925 	ill_t		*ill;
15926 	ipif_t		*ipif = NULL;
15927 	mblk_t		*mp1 = NULL;
15928 	conn_t		*connp = NULL;
15929 	t_uscalar_t	paddrreq;
15930 	mblk_t		*mp_hw;
15931 	boolean_t	success;
15932 	boolean_t	ioctl_aborted = B_FALSE;
15933 	boolean_t	log = B_TRUE;
15934 	ip_stack_t		*ipst;
15935 
15936 	ip1dbg(("ip_rput_dlpi_writer .."));
15937 	ill = (ill_t *)q->q_ptr;
15938 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15939 
15940 	ASSERT(IAM_WRITER_ILL(ill));
15941 
15942 	ipst = ill->ill_ipst;
15943 
15944 	/*
15945 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15946 	 * both are null or non-null. However we can assert that only
15947 	 * after grabbing the ipsq_lock. So we don't make any assertion
15948 	 * here and in other places in the code.
15949 	 */
15950 	ipif = ipsq->ipsq_pending_ipif;
15951 	/*
15952 	 * The current ioctl could have been aborted by the user and a new
15953 	 * ioctl to bring up another ill could have started. We could still
15954 	 * get a response from the driver later.
15955 	 */
15956 	if (ipif != NULL && ipif->ipif_ill != ill)
15957 		ioctl_aborted = B_TRUE;
15958 
15959 	switch (dloa->dl_primitive) {
15960 	case DL_ERROR_ACK:
15961 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15962 		    dl_primstr(dlea->dl_error_primitive)));
15963 
15964 		switch (dlea->dl_error_primitive) {
15965 		case DL_DISABMULTI_REQ:
15966 			if (!ill->ill_isv6)
15967 				ipsq_current_finish(ipsq);
15968 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15969 			break;
15970 		case DL_PROMISCON_REQ:
15971 		case DL_PROMISCOFF_REQ:
15972 		case DL_UNBIND_REQ:
15973 		case DL_ATTACH_REQ:
15974 		case DL_INFO_REQ:
15975 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15976 			break;
15977 		case DL_NOTIFY_REQ:
15978 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15979 			log = B_FALSE;
15980 			break;
15981 		case DL_PHYS_ADDR_REQ:
15982 			/*
15983 			 * For IPv6 only, there are two additional
15984 			 * phys_addr_req's sent to the driver to get the
15985 			 * IPv6 token and lla. This allows IP to acquire
15986 			 * the hardware address format for a given interface
15987 			 * without having built in knowledge of the hardware
15988 			 * address. ill_phys_addr_pend keeps track of the last
15989 			 * DL_PAR sent so we know which response we are
15990 			 * dealing with. ill_dlpi_done will update
15991 			 * ill_phys_addr_pend when it sends the next req.
15992 			 * We don't complete the IOCTL until all three DL_PARs
15993 			 * have been attempted, so set *_len to 0 and break.
15994 			 */
15995 			paddrreq = ill->ill_phys_addr_pend;
15996 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15997 			if (paddrreq == DL_IPV6_TOKEN) {
15998 				ill->ill_token_length = 0;
15999 				log = B_FALSE;
16000 				break;
16001 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16002 				ill->ill_nd_lla_len = 0;
16003 				log = B_FALSE;
16004 				break;
16005 			}
16006 			/*
16007 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
16008 			 * We presumably have an IOCTL hanging out waiting
16009 			 * for completion. Find it and complete the IOCTL
16010 			 * with the error noted.
16011 			 * However, ill_dl_phys was called on an ill queue
16012 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
16013 			 * set. But the ioctl is known to be pending on ill_wq.
16014 			 */
16015 			if (!ill->ill_ifname_pending)
16016 				break;
16017 			ill->ill_ifname_pending = 0;
16018 			if (!ioctl_aborted)
16019 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16020 			if (mp1 != NULL) {
16021 				/*
16022 				 * This operation (SIOCSLIFNAME) must have
16023 				 * happened on the ill. Assert there is no conn
16024 				 */
16025 				ASSERT(connp == NULL);
16026 				q = ill->ill_wq;
16027 			}
16028 			break;
16029 		case DL_BIND_REQ:
16030 			ill_dlpi_done(ill, DL_BIND_REQ);
16031 			if (ill->ill_ifname_pending)
16032 				break;
16033 			/*
16034 			 * Something went wrong with the bind.  We presumably
16035 			 * have an IOCTL hanging out waiting for completion.
16036 			 * Find it, take down the interface that was coming
16037 			 * up, and complete the IOCTL with the error noted.
16038 			 */
16039 			if (!ioctl_aborted)
16040 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16041 			if (mp1 != NULL) {
16042 				/*
16043 				 * This operation (SIOCSLIFFLAGS) must have
16044 				 * happened from a conn.
16045 				 */
16046 				ASSERT(connp != NULL);
16047 				q = CONNP_TO_WQ(connp);
16048 				if (ill->ill_move_in_progress) {
16049 					ILL_CLEAR_MOVE(ill);
16050 				}
16051 				(void) ipif_down(ipif, NULL, NULL);
16052 				/* error is set below the switch */
16053 			}
16054 			break;
16055 		case DL_ENABMULTI_REQ:
16056 			if (!ill->ill_isv6)
16057 				ipsq_current_finish(ipsq);
16058 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
16059 
16060 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
16061 				ill->ill_dlpi_multicast_state = IDS_FAILED;
16062 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
16063 				ipif_t *ipif;
16064 
16065 				printf("ip: joining multicasts failed (%d)"
16066 				    " on %s - will use link layer "
16067 				    "broadcasts for multicast\n",
16068 				    dlea->dl_errno, ill->ill_name);
16069 
16070 				/*
16071 				 * Set up the multicast mapping alone.
16072 				 * writer, so ok to access ill->ill_ipif
16073 				 * without any lock.
16074 				 */
16075 				ipif = ill->ill_ipif;
16076 				mutex_enter(&ill->ill_phyint->phyint_lock);
16077 				ill->ill_phyint->phyint_flags |=
16078 				    PHYI_MULTI_BCAST;
16079 				mutex_exit(&ill->ill_phyint->phyint_lock);
16080 
16081 				if (!ill->ill_isv6) {
16082 					(void) ipif_arp_setup_multicast(ipif,
16083 					    NULL);
16084 				} else {
16085 					(void) ipif_ndp_setup_multicast(ipif,
16086 					    NULL);
16087 				}
16088 			}
16089 			freemsg(mp);	/* Don't want to pass this up */
16090 			return;
16091 		case DL_CONTROL_REQ:
16092 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
16093 			    "DL_CONTROL_REQ\n"));
16094 			ill_dlpi_done(ill, dlea->dl_error_primitive);
16095 			freemsg(mp);
16096 			return;
16097 		case DL_CAPABILITY_REQ:
16098 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
16099 			    "DL_CAPABILITY REQ\n"));
16100 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
16101 				ill->ill_dlpi_capab_state = IDCS_FAILED;
16102 			ill_capability_done(ill);
16103 			freemsg(mp);
16104 			return;
16105 		}
16106 		/*
16107 		 * Note the error for IOCTL completion (mp1 is set when
16108 		 * ready to complete ioctl). If ill_ifname_pending_err is
16109 		 * set, an error occured during plumbing (ill_ifname_pending),
16110 		 * so we want to report that error.
16111 		 *
16112 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
16113 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
16114 		 * expected to get errack'd if the driver doesn't support
16115 		 * these flags (e.g. ethernet). log will be set to B_FALSE
16116 		 * if these error conditions are encountered.
16117 		 */
16118 		if (mp1 != NULL) {
16119 			if (ill->ill_ifname_pending_err != 0)  {
16120 				err = ill->ill_ifname_pending_err;
16121 				ill->ill_ifname_pending_err = 0;
16122 			} else {
16123 				err = dlea->dl_unix_errno ?
16124 				    dlea->dl_unix_errno : ENXIO;
16125 			}
16126 		/*
16127 		 * If we're plumbing an interface and an error hasn't already
16128 		 * been saved, set ill_ifname_pending_err to the error passed
16129 		 * up. Ignore the error if log is B_FALSE (see comment above).
16130 		 */
16131 		} else if (log && ill->ill_ifname_pending &&
16132 		    ill->ill_ifname_pending_err == 0) {
16133 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
16134 			    dlea->dl_unix_errno : ENXIO;
16135 		}
16136 
16137 		if (log)
16138 			ip_dlpi_error(ill, dlea->dl_error_primitive,
16139 			    dlea->dl_errno, dlea->dl_unix_errno);
16140 		break;
16141 	case DL_CAPABILITY_ACK:
16142 		ill_capability_ack(ill, mp);
16143 		/*
16144 		 * The message has been handed off to ill_capability_ack
16145 		 * and must not be freed below
16146 		 */
16147 		mp = NULL;
16148 		break;
16149 
16150 	case DL_CONTROL_ACK:
16151 		/* We treat all of these as "fire and forget" */
16152 		ill_dlpi_done(ill, DL_CONTROL_REQ);
16153 		break;
16154 	case DL_INFO_ACK:
16155 		/* Call a routine to handle this one. */
16156 		ill_dlpi_done(ill, DL_INFO_REQ);
16157 		ip_ll_subnet_defaults(ill, mp);
16158 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
16159 		return;
16160 	case DL_BIND_ACK:
16161 		/*
16162 		 * We should have an IOCTL waiting on this unless
16163 		 * sent by ill_dl_phys, in which case just return
16164 		 */
16165 		ill_dlpi_done(ill, DL_BIND_REQ);
16166 		if (ill->ill_ifname_pending)
16167 			break;
16168 
16169 		if (!ioctl_aborted)
16170 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16171 		if (mp1 == NULL)
16172 			break;
16173 		/*
16174 		 * Because mp1 was added by ill_dl_up(), and it always
16175 		 * passes a valid connp, connp must be valid here.
16176 		 */
16177 		ASSERT(connp != NULL);
16178 		q = CONNP_TO_WQ(connp);
16179 
16180 		/*
16181 		 * We are exclusive. So nothing can change even after
16182 		 * we get the pending mp. If need be we can put it back
16183 		 * and restart, as in calling ipif_arp_up()  below.
16184 		 */
16185 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
16186 
16187 		mutex_enter(&ill->ill_lock);
16188 		ill->ill_dl_up = 1;
16189 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
16190 		mutex_exit(&ill->ill_lock);
16191 
16192 		/*
16193 		 * Now bring up the resolver; when that is complete, we'll
16194 		 * create IREs.  Note that we intentionally mirror what
16195 		 * ipif_up() would have done, because we got here by way of
16196 		 * ill_dl_up(), which stopped ipif_up()'s processing.
16197 		 */
16198 		if (ill->ill_isv6) {
16199 			/*
16200 			 * v6 interfaces.
16201 			 * Unlike ARP which has to do another bind
16202 			 * and attach, once we get here we are
16203 			 * done with NDP. Except in the case of
16204 			 * ILLF_XRESOLV, in which case we send an
16205 			 * AR_INTERFACE_UP to the external resolver.
16206 			 * If all goes well, the ioctl will complete
16207 			 * in ip_rput(). If there's an error, we
16208 			 * complete it here.
16209 			 */
16210 			if ((err = ipif_ndp_up(ipif)) == 0) {
16211 				if (ill->ill_flags & ILLF_XRESOLV) {
16212 					mutex_enter(&connp->conn_lock);
16213 					mutex_enter(&ill->ill_lock);
16214 					success = ipsq_pending_mp_add(
16215 					    connp, ipif, q, mp1, 0);
16216 					mutex_exit(&ill->ill_lock);
16217 					mutex_exit(&connp->conn_lock);
16218 					if (success) {
16219 						err = ipif_resolver_up(ipif,
16220 						    Res_act_initial);
16221 						if (err == EINPROGRESS) {
16222 							freemsg(mp);
16223 							return;
16224 						}
16225 						ASSERT(err != 0);
16226 						mp1 = ipsq_pending_mp_get(ipsq,
16227 						    &connp);
16228 						ASSERT(mp1 != NULL);
16229 					} else {
16230 						/* conn has started closing */
16231 						err = EINTR;
16232 					}
16233 				} else { /* Non XRESOLV interface */
16234 					(void) ipif_resolver_up(ipif,
16235 					    Res_act_initial);
16236 					err = ipif_up_done_v6(ipif);
16237 				}
16238 			}
16239 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
16240 			/*
16241 			 * ARP and other v4 external resolvers.
16242 			 * Leave the pending mblk intact so that
16243 			 * the ioctl completes in ip_rput().
16244 			 */
16245 			mutex_enter(&connp->conn_lock);
16246 			mutex_enter(&ill->ill_lock);
16247 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
16248 			mutex_exit(&ill->ill_lock);
16249 			mutex_exit(&connp->conn_lock);
16250 			if (success) {
16251 				err = ipif_resolver_up(ipif, Res_act_initial);
16252 				if (err == EINPROGRESS) {
16253 					freemsg(mp);
16254 					return;
16255 				}
16256 				ASSERT(err != 0);
16257 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16258 			} else {
16259 				/* The conn has started closing */
16260 				err = EINTR;
16261 			}
16262 		} else {
16263 			/*
16264 			 * This one is complete. Reply to pending ioctl.
16265 			 */
16266 			(void) ipif_resolver_up(ipif, Res_act_initial);
16267 			err = ipif_up_done(ipif);
16268 		}
16269 
16270 		if ((err == 0) && (ill->ill_up_ipifs)) {
16271 			err = ill_up_ipifs(ill, q, mp1);
16272 			if (err == EINPROGRESS) {
16273 				freemsg(mp);
16274 				return;
16275 			}
16276 		}
16277 
16278 		if (ill->ill_up_ipifs) {
16279 			ill_group_cleanup(ill);
16280 		}
16281 
16282 		break;
16283 	case DL_NOTIFY_IND: {
16284 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16285 		ire_t *ire;
16286 		boolean_t need_ire_walk_v4 = B_FALSE;
16287 		boolean_t need_ire_walk_v6 = B_FALSE;
16288 
16289 		switch (notify->dl_notification) {
16290 		case DL_NOTE_PHYS_ADDR:
16291 			err = ill_set_phys_addr(ill, mp);
16292 			break;
16293 
16294 		case DL_NOTE_FASTPATH_FLUSH:
16295 			ill_fastpath_flush(ill);
16296 			break;
16297 
16298 		case DL_NOTE_SDU_SIZE:
16299 			/*
16300 			 * Change the MTU size of the interface, of all
16301 			 * attached ipif's, and of all relevant ire's.  The
16302 			 * new value's a uint32_t at notify->dl_data.
16303 			 * Mtu change Vs. new ire creation - protocol below.
16304 			 *
16305 			 * a Mark the ipif as IPIF_CHANGING.
16306 			 * b Set the new mtu in the ipif.
16307 			 * c Change the ire_max_frag on all affected ires
16308 			 * d Unmark the IPIF_CHANGING
16309 			 *
16310 			 * To see how the protocol works, assume an interface
16311 			 * route is also being added simultaneously by
16312 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16313 			 * the ire. If the ire is created before step a,
16314 			 * it will be cleaned up by step c. If the ire is
16315 			 * created after step d, it will see the new value of
16316 			 * ipif_mtu. Any attempt to create the ire between
16317 			 * steps a to d will fail because of the IPIF_CHANGING
16318 			 * flag. Note that ire_create() is passed a pointer to
16319 			 * the ipif_mtu, and not the value. During ire_add
16320 			 * under the bucket lock, the ire_max_frag of the
16321 			 * new ire being created is set from the ipif/ire from
16322 			 * which it is being derived.
16323 			 */
16324 			mutex_enter(&ill->ill_lock);
16325 			ill->ill_max_frag = (uint_t)notify->dl_data;
16326 
16327 			/*
16328 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
16329 			 * leave it alone
16330 			 */
16331 			if (ill->ill_mtu_userspecified) {
16332 				mutex_exit(&ill->ill_lock);
16333 				break;
16334 			}
16335 			ill->ill_max_mtu = ill->ill_max_frag;
16336 			if (ill->ill_isv6) {
16337 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16338 					ill->ill_max_mtu = IPV6_MIN_MTU;
16339 			} else {
16340 				if (ill->ill_max_mtu < IP_MIN_MTU)
16341 					ill->ill_max_mtu = IP_MIN_MTU;
16342 			}
16343 			for (ipif = ill->ill_ipif; ipif != NULL;
16344 			    ipif = ipif->ipif_next) {
16345 				/*
16346 				 * Don't override the mtu if the user
16347 				 * has explicitly set it.
16348 				 */
16349 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16350 					continue;
16351 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16352 				if (ipif->ipif_isv6)
16353 					ire = ipif_to_ire_v6(ipif);
16354 				else
16355 					ire = ipif_to_ire(ipif);
16356 				if (ire != NULL) {
16357 					ire->ire_max_frag = ipif->ipif_mtu;
16358 					ire_refrele(ire);
16359 				}
16360 				if (ipif->ipif_flags & IPIF_UP) {
16361 					if (ill->ill_isv6)
16362 						need_ire_walk_v6 = B_TRUE;
16363 					else
16364 						need_ire_walk_v4 = B_TRUE;
16365 				}
16366 			}
16367 			mutex_exit(&ill->ill_lock);
16368 			if (need_ire_walk_v4)
16369 				ire_walk_v4(ill_mtu_change, (char *)ill,
16370 				    ALL_ZONES, ipst);
16371 			if (need_ire_walk_v6)
16372 				ire_walk_v6(ill_mtu_change, (char *)ill,
16373 				    ALL_ZONES, ipst);
16374 			break;
16375 		case DL_NOTE_LINK_UP:
16376 		case DL_NOTE_LINK_DOWN: {
16377 			/*
16378 			 * We are writer. ill / phyint / ipsq assocs stable.
16379 			 * The RUNNING flag reflects the state of the link.
16380 			 */
16381 			phyint_t *phyint = ill->ill_phyint;
16382 			uint64_t new_phyint_flags;
16383 			boolean_t changed = B_FALSE;
16384 			boolean_t went_up;
16385 
16386 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16387 			mutex_enter(&phyint->phyint_lock);
16388 			new_phyint_flags = went_up ?
16389 			    phyint->phyint_flags | PHYI_RUNNING :
16390 			    phyint->phyint_flags & ~PHYI_RUNNING;
16391 			if (new_phyint_flags != phyint->phyint_flags) {
16392 				phyint->phyint_flags = new_phyint_flags;
16393 				changed = B_TRUE;
16394 			}
16395 			mutex_exit(&phyint->phyint_lock);
16396 			/*
16397 			 * ill_restart_dad handles the DAD restart and routing
16398 			 * socket notification logic.
16399 			 */
16400 			if (changed) {
16401 				ill_restart_dad(phyint->phyint_illv4, went_up);
16402 				ill_restart_dad(phyint->phyint_illv6, went_up);
16403 			}
16404 			break;
16405 		}
16406 		case DL_NOTE_PROMISC_ON_PHYS:
16407 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16408 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16409 			mutex_enter(&ill->ill_lock);
16410 			ill->ill_promisc_on_phys = B_TRUE;
16411 			mutex_exit(&ill->ill_lock);
16412 			break;
16413 		case DL_NOTE_PROMISC_OFF_PHYS:
16414 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16415 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16416 			mutex_enter(&ill->ill_lock);
16417 			ill->ill_promisc_on_phys = B_FALSE;
16418 			mutex_exit(&ill->ill_lock);
16419 			break;
16420 		case DL_NOTE_CAPAB_RENEG:
16421 			/*
16422 			 * Something changed on the driver side.
16423 			 * It wants us to renegotiate the capabilities
16424 			 * on this ill. One possible cause is the aggregation
16425 			 * interface under us where a port got added or
16426 			 * went away.
16427 			 *
16428 			 * If the capability negotiation is already done
16429 			 * or is in progress, reset the capabilities and
16430 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16431 			 * so that when the ack comes back, we can start
16432 			 * the renegotiation process.
16433 			 *
16434 			 * Note that if ill_capab_reneg is already B_TRUE
16435 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16436 			 * the capability resetting request has been sent
16437 			 * and the renegotiation has not been started yet;
16438 			 * nothing needs to be done in this case.
16439 			 */
16440 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
16441 			ill_capability_reset(ill, B_TRUE);
16442 			ipsq_current_finish(ipsq);
16443 			break;
16444 		default:
16445 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16446 			    "type 0x%x for DL_NOTIFY_IND\n",
16447 			    notify->dl_notification));
16448 			break;
16449 		}
16450 
16451 		/*
16452 		 * As this is an asynchronous operation, we
16453 		 * should not call ill_dlpi_done
16454 		 */
16455 		break;
16456 	}
16457 	case DL_NOTIFY_ACK: {
16458 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16459 
16460 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16461 			ill->ill_note_link = 1;
16462 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16463 		break;
16464 	}
16465 	case DL_PHYS_ADDR_ACK: {
16466 		/*
16467 		 * As part of plumbing the interface via SIOCSLIFNAME,
16468 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16469 		 * whose answers we receive here.  As each answer is received,
16470 		 * we call ill_dlpi_done() to dispatch the next request as
16471 		 * we're processing the current one.  Once all answers have
16472 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16473 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16474 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16475 		 * available, but we know the ioctl is pending on ill_wq.)
16476 		 */
16477 		uint_t paddrlen, paddroff;
16478 
16479 		paddrreq = ill->ill_phys_addr_pend;
16480 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16481 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16482 
16483 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16484 		if (paddrreq == DL_IPV6_TOKEN) {
16485 			/*
16486 			 * bcopy to low-order bits of ill_token
16487 			 *
16488 			 * XXX Temporary hack - currently, all known tokens
16489 			 * are 64 bits, so I'll cheat for the moment.
16490 			 */
16491 			bcopy(mp->b_rptr + paddroff,
16492 			    &ill->ill_token.s6_addr32[2], paddrlen);
16493 			ill->ill_token_length = paddrlen;
16494 			break;
16495 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16496 			ASSERT(ill->ill_nd_lla_mp == NULL);
16497 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16498 			mp = NULL;
16499 			break;
16500 		}
16501 
16502 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16503 		ASSERT(ill->ill_phys_addr_mp == NULL);
16504 		if (!ill->ill_ifname_pending)
16505 			break;
16506 		ill->ill_ifname_pending = 0;
16507 		if (!ioctl_aborted)
16508 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16509 		if (mp1 != NULL) {
16510 			ASSERT(connp == NULL);
16511 			q = ill->ill_wq;
16512 		}
16513 		/*
16514 		 * If any error acks received during the plumbing sequence,
16515 		 * ill_ifname_pending_err will be set. Break out and send up
16516 		 * the error to the pending ioctl.
16517 		 */
16518 		if (ill->ill_ifname_pending_err != 0) {
16519 			err = ill->ill_ifname_pending_err;
16520 			ill->ill_ifname_pending_err = 0;
16521 			break;
16522 		}
16523 
16524 		ill->ill_phys_addr_mp = mp;
16525 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16526 		mp = NULL;
16527 
16528 		/*
16529 		 * If paddrlen is zero, the DLPI provider doesn't support
16530 		 * physical addresses.  The other two tests were historical
16531 		 * workarounds for bugs in our former PPP implementation, but
16532 		 * now other things have grown dependencies on them -- e.g.,
16533 		 * the tun module specifies a dl_addr_length of zero in its
16534 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16535 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16536 		 * but only after careful testing ensures that all dependent
16537 		 * broken DLPI providers have been fixed.
16538 		 */
16539 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16540 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16541 			ill->ill_phys_addr = NULL;
16542 		} else if (paddrlen != ill->ill_phys_addr_length) {
16543 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16544 			    paddrlen, ill->ill_phys_addr_length));
16545 			err = EINVAL;
16546 			break;
16547 		}
16548 
16549 		if (ill->ill_nd_lla_mp == NULL) {
16550 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16551 				err = ENOMEM;
16552 				break;
16553 			}
16554 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16555 		}
16556 
16557 		/*
16558 		 * Set the interface token.  If the zeroth interface address
16559 		 * is unspecified, then set it to the link local address.
16560 		 */
16561 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16562 			(void) ill_setdefaulttoken(ill);
16563 
16564 		ASSERT(ill->ill_ipif->ipif_id == 0);
16565 		if (ipif != NULL &&
16566 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16567 			(void) ipif_setlinklocal(ipif);
16568 		}
16569 		break;
16570 	}
16571 	case DL_OK_ACK:
16572 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16573 		    dl_primstr((int)dloa->dl_correct_primitive),
16574 		    dloa->dl_correct_primitive));
16575 		switch (dloa->dl_correct_primitive) {
16576 		case DL_ENABMULTI_REQ:
16577 		case DL_DISABMULTI_REQ:
16578 			if (!ill->ill_isv6)
16579 				ipsq_current_finish(ipsq);
16580 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16581 			break;
16582 		case DL_PROMISCON_REQ:
16583 		case DL_PROMISCOFF_REQ:
16584 		case DL_UNBIND_REQ:
16585 		case DL_ATTACH_REQ:
16586 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16587 			break;
16588 		}
16589 		break;
16590 	default:
16591 		break;
16592 	}
16593 
16594 	freemsg(mp);
16595 	if (mp1 != NULL) {
16596 		/*
16597 		 * The operation must complete without EINPROGRESS
16598 		 * since ipsq_pending_mp_get() has removed the mblk
16599 		 * from ipsq_pending_mp.  Otherwise, the operation
16600 		 * will be stuck forever in the ipsq.
16601 		 */
16602 		ASSERT(err != EINPROGRESS);
16603 
16604 		switch (ipsq->ipsq_current_ioctl) {
16605 		case 0:
16606 			ipsq_current_finish(ipsq);
16607 			break;
16608 
16609 		case SIOCLIFADDIF:
16610 		case SIOCSLIFNAME:
16611 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16612 			break;
16613 
16614 		default:
16615 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16616 			break;
16617 		}
16618 	}
16619 }
16620 
16621 /*
16622  * ip_rput_other is called by ip_rput to handle messages modifying the global
16623  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16624  */
16625 /* ARGSUSED */
16626 void
16627 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16628 {
16629 	ill_t		*ill;
16630 	struct iocblk	*iocp;
16631 	mblk_t		*mp1;
16632 	conn_t		*connp = NULL;
16633 
16634 	ip1dbg(("ip_rput_other "));
16635 	ill = (ill_t *)q->q_ptr;
16636 	/*
16637 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16638 	 * in which case ipsq is NULL.
16639 	 */
16640 	if (ipsq != NULL) {
16641 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16642 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16643 	}
16644 
16645 	switch (mp->b_datap->db_type) {
16646 	case M_ERROR:
16647 	case M_HANGUP:
16648 		/*
16649 		 * The device has a problem.  We force the ILL down.  It can
16650 		 * be brought up again manually using SIOCSIFFLAGS (via
16651 		 * ifconfig or equivalent).
16652 		 */
16653 		ASSERT(ipsq != NULL);
16654 		if (mp->b_rptr < mp->b_wptr)
16655 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16656 		if (ill->ill_error == 0)
16657 			ill->ill_error = ENXIO;
16658 		if (!ill_down_start(q, mp))
16659 			return;
16660 		ipif_all_down_tail(ipsq, q, mp, NULL);
16661 		break;
16662 	case M_IOCACK:
16663 		iocp = (struct iocblk *)mp->b_rptr;
16664 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16665 		switch (iocp->ioc_cmd) {
16666 		case SIOCSTUNPARAM:
16667 		case OSIOCSTUNPARAM:
16668 			ASSERT(ipsq != NULL);
16669 			/*
16670 			 * Finish socket ioctl passed through to tun.
16671 			 * We should have an IOCTL waiting on this.
16672 			 */
16673 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16674 			if (ill->ill_isv6) {
16675 				struct iftun_req *ta;
16676 
16677 				/*
16678 				 * if a source or destination is
16679 				 * being set, try and set the link
16680 				 * local address for the tunnel
16681 				 */
16682 				ta = (struct iftun_req *)mp->b_cont->
16683 				    b_cont->b_rptr;
16684 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16685 					ipif_set_tun_llink(ill, ta);
16686 				}
16687 
16688 			}
16689 			if (mp1 != NULL) {
16690 				/*
16691 				 * Now copy back the b_next/b_prev used by
16692 				 * mi code for the mi_copy* functions.
16693 				 * See ip_sioctl_tunparam() for the reason.
16694 				 * Also protect against missing b_cont.
16695 				 */
16696 				if (mp->b_cont != NULL) {
16697 					mp->b_cont->b_next =
16698 					    mp1->b_cont->b_next;
16699 					mp->b_cont->b_prev =
16700 					    mp1->b_cont->b_prev;
16701 				}
16702 				inet_freemsg(mp1);
16703 				ASSERT(connp != NULL);
16704 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16705 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16706 			} else {
16707 				ASSERT(connp == NULL);
16708 				putnext(q, mp);
16709 			}
16710 			break;
16711 		case SIOCGTUNPARAM:
16712 		case OSIOCGTUNPARAM:
16713 			/*
16714 			 * This is really M_IOCDATA from the tunnel driver.
16715 			 * convert back and complete the ioctl.
16716 			 * We should have an IOCTL waiting on this.
16717 			 */
16718 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16719 			if (mp1) {
16720 				/*
16721 				 * Now copy back the b_next/b_prev used by
16722 				 * mi code for the mi_copy* functions.
16723 				 * See ip_sioctl_tunparam() for the reason.
16724 				 * Also protect against missing b_cont.
16725 				 */
16726 				if (mp->b_cont != NULL) {
16727 					mp->b_cont->b_next =
16728 					    mp1->b_cont->b_next;
16729 					mp->b_cont->b_prev =
16730 					    mp1->b_cont->b_prev;
16731 				}
16732 				inet_freemsg(mp1);
16733 				if (iocp->ioc_error == 0)
16734 					mp->b_datap->db_type = M_IOCDATA;
16735 				ASSERT(connp != NULL);
16736 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16737 				    iocp->ioc_error, COPYOUT, NULL);
16738 			} else {
16739 				ASSERT(connp == NULL);
16740 				putnext(q, mp);
16741 			}
16742 			break;
16743 		default:
16744 			break;
16745 		}
16746 		break;
16747 	case M_IOCNAK:
16748 		iocp = (struct iocblk *)mp->b_rptr;
16749 
16750 		switch (iocp->ioc_cmd) {
16751 			int mode;
16752 
16753 		case DL_IOC_HDR_INFO:
16754 			/*
16755 			 * If this was the first attempt turn of the
16756 			 * fastpath probing.
16757 			 */
16758 			mutex_enter(&ill->ill_lock);
16759 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16760 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16761 				mutex_exit(&ill->ill_lock);
16762 				ill_fastpath_nack(ill);
16763 				ip1dbg(("ip_rput: DLPI fastpath off on "
16764 				    "interface %s\n",
16765 				    ill->ill_name));
16766 			} else {
16767 				mutex_exit(&ill->ill_lock);
16768 			}
16769 			freemsg(mp);
16770 			break;
16771 		case SIOCSTUNPARAM:
16772 		case OSIOCSTUNPARAM:
16773 			ASSERT(ipsq != NULL);
16774 			/*
16775 			 * Finish socket ioctl passed through to tun
16776 			 * We should have an IOCTL waiting on this.
16777 			 */
16778 			/* FALLTHRU */
16779 		case SIOCGTUNPARAM:
16780 		case OSIOCGTUNPARAM:
16781 			/*
16782 			 * This is really M_IOCDATA from the tunnel driver.
16783 			 * convert back and complete the ioctl.
16784 			 * We should have an IOCTL waiting on this.
16785 			 */
16786 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16787 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16788 				mp1 = ill_pending_mp_get(ill, &connp,
16789 				    iocp->ioc_id);
16790 				mode = COPYOUT;
16791 				ipsq = NULL;
16792 			} else {
16793 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16794 				mode = NO_COPYOUT;
16795 			}
16796 			if (mp1 != NULL) {
16797 				/*
16798 				 * Now copy back the b_next/b_prev used by
16799 				 * mi code for the mi_copy* functions.
16800 				 * See ip_sioctl_tunparam() for the reason.
16801 				 * Also protect against missing b_cont.
16802 				 */
16803 				if (mp->b_cont != NULL) {
16804 					mp->b_cont->b_next =
16805 					    mp1->b_cont->b_next;
16806 					mp->b_cont->b_prev =
16807 					    mp1->b_cont->b_prev;
16808 				}
16809 				inet_freemsg(mp1);
16810 				if (iocp->ioc_error == 0)
16811 					iocp->ioc_error = EINVAL;
16812 				ASSERT(connp != NULL);
16813 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16814 				    iocp->ioc_error, mode, ipsq);
16815 			} else {
16816 				ASSERT(connp == NULL);
16817 				putnext(q, mp);
16818 			}
16819 			break;
16820 		default:
16821 			break;
16822 		}
16823 	default:
16824 		break;
16825 	}
16826 }
16827 
16828 /*
16829  * NOTE : This function does not ire_refrele the ire argument passed in.
16830  *
16831  * IPQoS notes
16832  * IP policy is invoked twice for a forwarded packet, once on the read side
16833  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16834  * enabled. An additional parameter, in_ill, has been added for this purpose.
16835  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16836  * because ip_mroute drops this information.
16837  *
16838  */
16839 void
16840 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16841 {
16842 	uint32_t	old_pkt_len;
16843 	uint32_t	pkt_len;
16844 	queue_t	*q;
16845 	uint32_t	sum;
16846 #define	rptr	((uchar_t *)ipha)
16847 	uint32_t	max_frag;
16848 	uint32_t	ill_index;
16849 	ill_t		*out_ill;
16850 	mib2_ipIfStatsEntry_t *mibptr;
16851 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16852 
16853 	/* Get the ill_index of the incoming ILL */
16854 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16855 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16856 
16857 	/* Initiate Read side IPPF processing */
16858 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16859 		ip_process(IPP_FWD_IN, &mp, ill_index);
16860 		if (mp == NULL) {
16861 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16862 			    "during IPPF processing\n"));
16863 			return;
16864 		}
16865 	}
16866 
16867 	/* Adjust the checksum to reflect the ttl decrement. */
16868 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16869 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16870 
16871 	if (ipha->ipha_ttl-- <= 1) {
16872 		if (ip_csum_hdr(ipha)) {
16873 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16874 			goto drop_pkt;
16875 		}
16876 		/*
16877 		 * Note: ire_stq this will be NULL for multicast
16878 		 * datagrams using the long path through arp (the IRE
16879 		 * is not an IRE_CACHE). This should not cause
16880 		 * problems since we don't generate ICMP errors for
16881 		 * multicast packets.
16882 		 */
16883 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16884 		q = ire->ire_stq;
16885 		if (q != NULL) {
16886 			/* Sent by forwarding path, and router is global zone */
16887 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16888 			    GLOBAL_ZONEID, ipst);
16889 		} else
16890 			freemsg(mp);
16891 		return;
16892 	}
16893 
16894 	/*
16895 	 * Don't forward if the interface is down
16896 	 */
16897 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16898 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16899 		ip2dbg(("ip_rput_forward:interface is down\n"));
16900 		goto drop_pkt;
16901 	}
16902 
16903 	/* Get the ill_index of the outgoing ILL */
16904 	out_ill = ire_to_ill(ire);
16905 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16906 
16907 	DTRACE_PROBE4(ip4__forwarding__start,
16908 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16909 
16910 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16911 	    ipst->ips_ipv4firewall_forwarding,
16912 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16913 
16914 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16915 
16916 	if (mp == NULL)
16917 		return;
16918 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16919 
16920 	if (is_system_labeled()) {
16921 		mblk_t *mp1;
16922 
16923 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16924 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16925 			goto drop_pkt;
16926 		}
16927 		/* Size may have changed */
16928 		mp = mp1;
16929 		ipha = (ipha_t *)mp->b_rptr;
16930 		pkt_len = ntohs(ipha->ipha_length);
16931 	}
16932 
16933 	/* Check if there are options to update */
16934 	if (!IS_SIMPLE_IPH(ipha)) {
16935 		if (ip_csum_hdr(ipha)) {
16936 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16937 			goto drop_pkt;
16938 		}
16939 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16940 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16941 			return;
16942 		}
16943 
16944 		ipha->ipha_hdr_checksum = 0;
16945 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16946 	}
16947 	max_frag = ire->ire_max_frag;
16948 	if (pkt_len > max_frag) {
16949 		/*
16950 		 * It needs fragging on its way out.  We haven't
16951 		 * verified the header checksum yet.  Since we
16952 		 * are going to put a surely good checksum in the
16953 		 * outgoing header, we have to make sure that it
16954 		 * was good coming in.
16955 		 */
16956 		if (ip_csum_hdr(ipha)) {
16957 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16958 			goto drop_pkt;
16959 		}
16960 		/* Initiate Write side IPPF processing */
16961 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16962 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16963 			if (mp == NULL) {
16964 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16965 				    " during IPPF processing\n"));
16966 				return;
16967 			}
16968 		}
16969 		/*
16970 		 * Handle labeled packet resizing.
16971 		 *
16972 		 * If we have added a label, inform ip_wput_frag() of its
16973 		 * effect on the MTU for ICMP messages.
16974 		 */
16975 		if (pkt_len > old_pkt_len) {
16976 			uint32_t secopt_size;
16977 
16978 			secopt_size = pkt_len - old_pkt_len;
16979 			if (secopt_size < max_frag)
16980 				max_frag -= secopt_size;
16981 		}
16982 
16983 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0,
16984 		    GLOBAL_ZONEID, ipst, NULL);
16985 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16986 		return;
16987 	}
16988 
16989 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16990 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16991 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16992 	    ipst->ips_ipv4firewall_physical_out,
16993 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16994 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16995 	if (mp == NULL)
16996 		return;
16997 
16998 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16999 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
17000 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE, NULL);
17001 	/* ip_xmit_v4 always consumes the packet */
17002 	return;
17003 
17004 drop_pkt:;
17005 	ip1dbg(("ip_rput_forward: drop pkt\n"));
17006 	freemsg(mp);
17007 #undef	rptr
17008 }
17009 
17010 void
17011 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
17012 {
17013 	ire_t	*ire;
17014 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
17015 
17016 	ASSERT(!ipif->ipif_isv6);
17017 	/*
17018 	 * Find an IRE which matches the destination and the outgoing
17019 	 * queue in the cache table. All we need is an IRE_CACHE which
17020 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
17021 	 * then it is enough to have some IRE_CACHE in the group.
17022 	 */
17023 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
17024 		dst = ipif->ipif_pp_dst_addr;
17025 
17026 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
17027 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
17028 	if (ire == NULL) {
17029 		/*
17030 		 * Mark this packet to make it be delivered to
17031 		 * ip_rput_forward after the new ire has been
17032 		 * created.
17033 		 */
17034 		mp->b_prev = NULL;
17035 		mp->b_next = mp;
17036 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
17037 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
17038 	} else {
17039 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
17040 		IRE_REFRELE(ire);
17041 	}
17042 }
17043 
17044 /* Update any source route, record route or timestamp options */
17045 static int
17046 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
17047 {
17048 	ipoptp_t	opts;
17049 	uchar_t		*opt;
17050 	uint8_t		optval;
17051 	uint8_t		optlen;
17052 	ipaddr_t	dst;
17053 	uint32_t	ts;
17054 	ire_t		*dst_ire = NULL;
17055 	ire_t		*tmp_ire = NULL;
17056 	timestruc_t	now;
17057 
17058 	ip2dbg(("ip_rput_forward_options\n"));
17059 	dst = ipha->ipha_dst;
17060 	for (optval = ipoptp_first(&opts, ipha);
17061 	    optval != IPOPT_EOL;
17062 	    optval = ipoptp_next(&opts)) {
17063 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17064 		opt = opts.ipoptp_cur;
17065 		optlen = opts.ipoptp_len;
17066 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
17067 		    optval, opts.ipoptp_len));
17068 		switch (optval) {
17069 			uint32_t off;
17070 		case IPOPT_SSRR:
17071 		case IPOPT_LSRR:
17072 			/* Check if adminstratively disabled */
17073 			if (!ipst->ips_ip_forward_src_routed) {
17074 				if (ire->ire_stq != NULL) {
17075 					/*
17076 					 * Sent by forwarding path, and router
17077 					 * is global zone
17078 					 */
17079 					icmp_unreachable(ire->ire_stq, mp,
17080 					    ICMP_SOURCE_ROUTE_FAILED,
17081 					    GLOBAL_ZONEID, ipst);
17082 				} else {
17083 					ip0dbg(("ip_rput_forward_options: "
17084 					    "unable to send unreach\n"));
17085 					freemsg(mp);
17086 				}
17087 				return (-1);
17088 			}
17089 
17090 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17091 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17092 			if (dst_ire == NULL) {
17093 				/*
17094 				 * Must be partial since ip_rput_options
17095 				 * checked for strict.
17096 				 */
17097 				break;
17098 			}
17099 			off = opt[IPOPT_OFFSET];
17100 			off--;
17101 		redo_srr:
17102 			if (optlen < IP_ADDR_LEN ||
17103 			    off > optlen - IP_ADDR_LEN) {
17104 				/* End of source route */
17105 				ip1dbg((
17106 				    "ip_rput_forward_options: end of SR\n"));
17107 				ire_refrele(dst_ire);
17108 				break;
17109 			}
17110 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17111 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17112 			    IP_ADDR_LEN);
17113 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
17114 			    ntohl(dst)));
17115 
17116 			/*
17117 			 * Check if our address is present more than
17118 			 * once as consecutive hops in source route.
17119 			 */
17120 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17121 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17122 			if (tmp_ire != NULL) {
17123 				ire_refrele(tmp_ire);
17124 				off += IP_ADDR_LEN;
17125 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17126 				goto redo_srr;
17127 			}
17128 			ipha->ipha_dst = dst;
17129 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17130 			ire_refrele(dst_ire);
17131 			break;
17132 		case IPOPT_RR:
17133 			off = opt[IPOPT_OFFSET];
17134 			off--;
17135 			if (optlen < IP_ADDR_LEN ||
17136 			    off > optlen - IP_ADDR_LEN) {
17137 				/* No more room - ignore */
17138 				ip1dbg((
17139 				    "ip_rput_forward_options: end of RR\n"));
17140 				break;
17141 			}
17142 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17143 			    IP_ADDR_LEN);
17144 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17145 			break;
17146 		case IPOPT_TS:
17147 			/* Insert timestamp if there is room */
17148 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17149 			case IPOPT_TS_TSONLY:
17150 				off = IPOPT_TS_TIMELEN;
17151 				break;
17152 			case IPOPT_TS_PRESPEC:
17153 			case IPOPT_TS_PRESPEC_RFC791:
17154 				/* Verify that the address matched */
17155 				off = opt[IPOPT_OFFSET] - 1;
17156 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17157 				dst_ire = ire_ctable_lookup(dst, 0,
17158 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
17159 				    MATCH_IRE_TYPE, ipst);
17160 				if (dst_ire == NULL) {
17161 					/* Not for us */
17162 					break;
17163 				}
17164 				ire_refrele(dst_ire);
17165 				/* FALLTHRU */
17166 			case IPOPT_TS_TSANDADDR:
17167 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17168 				break;
17169 			default:
17170 				/*
17171 				 * ip_*put_options should have already
17172 				 * dropped this packet.
17173 				 */
17174 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
17175 				    "unknown IT - bug in ip_rput_options?\n");
17176 				return (0);	/* Keep "lint" happy */
17177 			}
17178 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17179 				/* Increase overflow counter */
17180 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17181 				opt[IPOPT_POS_OV_FLG] =
17182 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17183 				    (off << 4));
17184 				break;
17185 			}
17186 			off = opt[IPOPT_OFFSET] - 1;
17187 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17188 			case IPOPT_TS_PRESPEC:
17189 			case IPOPT_TS_PRESPEC_RFC791:
17190 			case IPOPT_TS_TSANDADDR:
17191 				bcopy(&ire->ire_src_addr,
17192 				    (char *)opt + off, IP_ADDR_LEN);
17193 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17194 				/* FALLTHRU */
17195 			case IPOPT_TS_TSONLY:
17196 				off = opt[IPOPT_OFFSET] - 1;
17197 				/* Compute # of milliseconds since midnight */
17198 				gethrestime(&now);
17199 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17200 				    now.tv_nsec / (NANOSEC / MILLISEC);
17201 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17202 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17203 				break;
17204 			}
17205 			break;
17206 		}
17207 	}
17208 	return (0);
17209 }
17210 
17211 /*
17212  * This is called after processing at least one of AH/ESP headers.
17213  *
17214  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
17215  * the actual, physical interface on which the packet was received,
17216  * but, when ip_strict_dst_multihoming is set to 1, could be the
17217  * interface which had the ipha_dst configured when the packet went
17218  * through ip_rput. The ill_index corresponding to the recv_ill
17219  * is saved in ipsec_in_rill_index
17220  *
17221  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
17222  * cannot assume "ire" points to valid data for any IPv6 cases.
17223  */
17224 void
17225 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
17226 {
17227 	mblk_t *mp;
17228 	ipaddr_t dst;
17229 	in6_addr_t *v6dstp;
17230 	ipha_t *ipha;
17231 	ip6_t *ip6h;
17232 	ipsec_in_t *ii;
17233 	boolean_t ill_need_rele = B_FALSE;
17234 	boolean_t rill_need_rele = B_FALSE;
17235 	boolean_t ire_need_rele = B_FALSE;
17236 	netstack_t	*ns;
17237 	ip_stack_t	*ipst;
17238 
17239 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
17240 	ASSERT(ii->ipsec_in_ill_index != 0);
17241 	ns = ii->ipsec_in_ns;
17242 	ASSERT(ii->ipsec_in_ns != NULL);
17243 	ipst = ns->netstack_ip;
17244 
17245 	mp = ipsec_mp->b_cont;
17246 	ASSERT(mp != NULL);
17247 
17248 
17249 	if (ill == NULL) {
17250 		ASSERT(recv_ill == NULL);
17251 		/*
17252 		 * We need to get the original queue on which ip_rput_local
17253 		 * or ip_rput_data_v6 was called.
17254 		 */
17255 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
17256 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
17257 		ill_need_rele = B_TRUE;
17258 
17259 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
17260 			recv_ill = ill_lookup_on_ifindex(
17261 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
17262 			    NULL, NULL, NULL, NULL, ipst);
17263 			rill_need_rele = B_TRUE;
17264 		} else {
17265 			recv_ill = ill;
17266 		}
17267 
17268 		if ((ill == NULL) || (recv_ill == NULL)) {
17269 			ip0dbg(("ip_fanout_proto_again: interface "
17270 			    "disappeared\n"));
17271 			if (ill != NULL)
17272 				ill_refrele(ill);
17273 			if (recv_ill != NULL)
17274 				ill_refrele(recv_ill);
17275 			freemsg(ipsec_mp);
17276 			return;
17277 		}
17278 	}
17279 
17280 	ASSERT(ill != NULL && recv_ill != NULL);
17281 
17282 	if (mp->b_datap->db_type == M_CTL) {
17283 		/*
17284 		 * AH/ESP is returning the ICMP message after
17285 		 * removing their headers. Fanout again till
17286 		 * it gets to the right protocol.
17287 		 */
17288 		if (ii->ipsec_in_v4) {
17289 			icmph_t *icmph;
17290 			int iph_hdr_length;
17291 			int hdr_length;
17292 
17293 			ipha = (ipha_t *)mp->b_rptr;
17294 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17295 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17296 			ipha = (ipha_t *)&icmph[1];
17297 			hdr_length = IPH_HDR_LENGTH(ipha);
17298 			/*
17299 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17300 			 * Reset the type to M_DATA.
17301 			 */
17302 			mp->b_datap->db_type = M_DATA;
17303 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17304 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17305 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17306 		} else {
17307 			icmp6_t *icmp6;
17308 			int hdr_length;
17309 
17310 			ip6h = (ip6_t *)mp->b_rptr;
17311 			/* Don't call hdr_length_v6() unless you have to. */
17312 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17313 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17314 			else
17315 				hdr_length = IPV6_HDR_LEN;
17316 
17317 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17318 			/*
17319 			 * icmp_inbound_error_fanout_v6 may need to do
17320 			 * pullupmsg.  Reset the type to M_DATA.
17321 			 */
17322 			mp->b_datap->db_type = M_DATA;
17323 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17324 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
17325 		}
17326 		if (ill_need_rele)
17327 			ill_refrele(ill);
17328 		if (rill_need_rele)
17329 			ill_refrele(recv_ill);
17330 		return;
17331 	}
17332 
17333 	if (ii->ipsec_in_v4) {
17334 		ipha = (ipha_t *)mp->b_rptr;
17335 		dst = ipha->ipha_dst;
17336 		if (CLASSD(dst)) {
17337 			/*
17338 			 * Multicast has to be delivered to all streams.
17339 			 */
17340 			dst = INADDR_BROADCAST;
17341 		}
17342 
17343 		if (ire == NULL) {
17344 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17345 			    MBLK_GETLABEL(mp), ipst);
17346 			if (ire == NULL) {
17347 				if (ill_need_rele)
17348 					ill_refrele(ill);
17349 				if (rill_need_rele)
17350 					ill_refrele(recv_ill);
17351 				ip1dbg(("ip_fanout_proto_again: "
17352 				    "IRE not found"));
17353 				freemsg(ipsec_mp);
17354 				return;
17355 			}
17356 			ire_need_rele = B_TRUE;
17357 		}
17358 
17359 		switch (ipha->ipha_protocol) {
17360 			case IPPROTO_UDP:
17361 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17362 				    recv_ill);
17363 				if (ire_need_rele)
17364 					ire_refrele(ire);
17365 				break;
17366 			case IPPROTO_TCP:
17367 				if (!ire_need_rele)
17368 					IRE_REFHOLD(ire);
17369 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17370 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17371 				IRE_REFRELE(ire);
17372 				if (mp != NULL) {
17373 
17374 					SQUEUE_ENTER(GET_SQUEUE(mp), mp,
17375 					    mp, 1, SQ_PROCESS,
17376 					    SQTAG_IP_PROTO_AGAIN);
17377 				}
17378 				break;
17379 			case IPPROTO_SCTP:
17380 				if (!ire_need_rele)
17381 					IRE_REFHOLD(ire);
17382 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17383 				    ipsec_mp, 0, ill->ill_rq, dst);
17384 				break;
17385 			default:
17386 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17387 				    recv_ill, 0);
17388 				if (ire_need_rele)
17389 					ire_refrele(ire);
17390 				break;
17391 		}
17392 	} else {
17393 		uint32_t rput_flags = 0;
17394 
17395 		ip6h = (ip6_t *)mp->b_rptr;
17396 		v6dstp = &ip6h->ip6_dst;
17397 		/*
17398 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17399 		 * address.
17400 		 *
17401 		 * Currently, we don't store that state in the IPSEC_IN
17402 		 * message, and we may need to.
17403 		 */
17404 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17405 		    IP6_IN_LLMCAST : 0);
17406 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17407 		    NULL, NULL);
17408 	}
17409 	if (ill_need_rele)
17410 		ill_refrele(ill);
17411 	if (rill_need_rele)
17412 		ill_refrele(recv_ill);
17413 }
17414 
17415 /*
17416  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17417  * returns 'true' if there are still fragments left on the queue, in
17418  * which case we restart the timer.
17419  */
17420 void
17421 ill_frag_timer(void *arg)
17422 {
17423 	ill_t	*ill = (ill_t *)arg;
17424 	boolean_t frag_pending;
17425 	ip_stack_t	*ipst = ill->ill_ipst;
17426 
17427 	mutex_enter(&ill->ill_lock);
17428 	ASSERT(!ill->ill_fragtimer_executing);
17429 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17430 		ill->ill_frag_timer_id = 0;
17431 		mutex_exit(&ill->ill_lock);
17432 		return;
17433 	}
17434 	ill->ill_fragtimer_executing = 1;
17435 	mutex_exit(&ill->ill_lock);
17436 
17437 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17438 
17439 	/*
17440 	 * Restart the timer, if we have fragments pending or if someone
17441 	 * wanted us to be scheduled again.
17442 	 */
17443 	mutex_enter(&ill->ill_lock);
17444 	ill->ill_fragtimer_executing = 0;
17445 	ill->ill_frag_timer_id = 0;
17446 	if (frag_pending || ill->ill_fragtimer_needrestart)
17447 		ill_frag_timer_start(ill);
17448 	mutex_exit(&ill->ill_lock);
17449 }
17450 
17451 void
17452 ill_frag_timer_start(ill_t *ill)
17453 {
17454 	ip_stack_t	*ipst = ill->ill_ipst;
17455 
17456 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17457 
17458 	/* If the ill is closing or opening don't proceed */
17459 	if (ill->ill_state_flags & ILL_CONDEMNED)
17460 		return;
17461 
17462 	if (ill->ill_fragtimer_executing) {
17463 		/*
17464 		 * ill_frag_timer is currently executing. Just record the
17465 		 * the fact that we want the timer to be restarted.
17466 		 * ill_frag_timer will post a timeout before it returns,
17467 		 * ensuring it will be called again.
17468 		 */
17469 		ill->ill_fragtimer_needrestart = 1;
17470 		return;
17471 	}
17472 
17473 	if (ill->ill_frag_timer_id == 0) {
17474 		/*
17475 		 * The timer is neither running nor is the timeout handler
17476 		 * executing. Post a timeout so that ill_frag_timer will be
17477 		 * called
17478 		 */
17479 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17480 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17481 		ill->ill_fragtimer_needrestart = 0;
17482 	}
17483 }
17484 
17485 /*
17486  * This routine is needed for loopback when forwarding multicasts.
17487  *
17488  * IPQoS Notes:
17489  * IPPF processing is done in fanout routines.
17490  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17491  * processing for IPsec packets is done when it comes back in clear.
17492  * NOTE : The callers of this function need to do the ire_refrele for the
17493  *	  ire that is being passed in.
17494  */
17495 void
17496 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17497     ill_t *recv_ill, uint32_t esp_udp_ports)
17498 {
17499 	boolean_t esp_in_udp_packet = (esp_udp_ports != 0);
17500 	ill_t	*ill = (ill_t *)q->q_ptr;
17501 	uint32_t	sum;
17502 	uint32_t	u1;
17503 	uint32_t	u2;
17504 	int		hdr_length;
17505 	boolean_t	mctl_present;
17506 	mblk_t		*first_mp = mp;
17507 	mblk_t		*hada_mp = NULL;
17508 	ipha_t		*inner_ipha;
17509 	ip_stack_t	*ipst;
17510 
17511 	ASSERT(recv_ill != NULL);
17512 	ipst = recv_ill->ill_ipst;
17513 
17514 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17515 	    "ip_rput_locl_start: q %p", q);
17516 
17517 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17518 	ASSERT(ill != NULL);
17519 
17520 
17521 #define	rptr	((uchar_t *)ipha)
17522 #define	iphs	((uint16_t *)ipha)
17523 
17524 	/*
17525 	 * no UDP or TCP packet should come here anymore.
17526 	 */
17527 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17528 	    ipha->ipha_protocol != IPPROTO_UDP);
17529 
17530 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17531 	if (mctl_present &&
17532 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17533 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17534 
17535 		/*
17536 		 * It's an IPsec accelerated packet.
17537 		 * Keep a pointer to the data attributes around until
17538 		 * we allocate the ipsec_info_t.
17539 		 */
17540 		IPSECHW_DEBUG(IPSECHW_PKT,
17541 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17542 		hada_mp = first_mp;
17543 		hada_mp->b_cont = NULL;
17544 		/*
17545 		 * Since it is accelerated, it comes directly from
17546 		 * the ill and the data attributes is followed by
17547 		 * the packet data.
17548 		 */
17549 		ASSERT(mp->b_datap->db_type != M_CTL);
17550 		first_mp = mp;
17551 		mctl_present = B_FALSE;
17552 	}
17553 
17554 	/*
17555 	 * IF M_CTL is not present, then ipsec_in_is_secure
17556 	 * should return B_TRUE. There is a case where loopback
17557 	 * packets has an M_CTL in the front with all the
17558 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17559 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17560 	 * packets never comes here, it is safe to ASSERT the
17561 	 * following.
17562 	 */
17563 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17564 
17565 	/*
17566 	 * Also, we should never have an mctl_present if this is an
17567 	 * ESP-in-UDP packet.
17568 	 */
17569 	ASSERT(!mctl_present || !esp_in_udp_packet);
17570 
17571 
17572 	/* u1 is # words of IP options */
17573 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17574 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17575 
17576 	/*
17577 	 * Don't verify header checksum if we just removed UDP header or
17578 	 * packet is coming back from AH/ESP.
17579 	 */
17580 	if (!esp_in_udp_packet && !mctl_present) {
17581 		if (u1) {
17582 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17583 				if (hada_mp != NULL)
17584 					freemsg(hada_mp);
17585 				return;
17586 			}
17587 		} else {
17588 			/* Check the IP header checksum.  */
17589 #define	uph	((uint16_t *)ipha)
17590 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17591 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17592 #undef  uph
17593 			/* finish doing IP checksum */
17594 			sum = (sum & 0xFFFF) + (sum >> 16);
17595 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17596 			if (sum && sum != 0xFFFF) {
17597 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17598 				goto drop_pkt;
17599 			}
17600 		}
17601 	}
17602 
17603 	/*
17604 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17605 	 * might be called more than once for secure packets, count only
17606 	 * the first time.
17607 	 */
17608 	if (!mctl_present) {
17609 		UPDATE_IB_PKT_COUNT(ire);
17610 		ire->ire_last_used_time = lbolt;
17611 	}
17612 
17613 	/* Check for fragmentation offset. */
17614 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17615 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17616 	if (u1) {
17617 		/*
17618 		 * We re-assemble fragments before we do the AH/ESP
17619 		 * processing. Thus, M_CTL should not be present
17620 		 * while we are re-assembling.
17621 		 */
17622 		ASSERT(!mctl_present);
17623 		ASSERT(first_mp == mp);
17624 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17625 			return;
17626 		}
17627 		/*
17628 		 * Make sure that first_mp points back to mp as
17629 		 * the mp we came in with could have changed in
17630 		 * ip_rput_fragment().
17631 		 */
17632 		ipha = (ipha_t *)mp->b_rptr;
17633 		first_mp = mp;
17634 	}
17635 
17636 	/*
17637 	 * Clear hardware checksumming flag as it is currently only
17638 	 * used by TCP and UDP.
17639 	 */
17640 	DB_CKSUMFLAGS(mp) = 0;
17641 
17642 	/* Now we have a complete datagram, destined for this machine. */
17643 	u1 = IPH_HDR_LENGTH(ipha);
17644 	switch (ipha->ipha_protocol) {
17645 	case IPPROTO_ICMP: {
17646 		ire_t		*ire_zone;
17647 		ilm_t		*ilm;
17648 		mblk_t		*mp1;
17649 		zoneid_t	last_zoneid;
17650 
17651 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17652 			ASSERT(ire->ire_type == IRE_BROADCAST);
17653 			/*
17654 			 * Inactive/Failed interfaces are not supposed to
17655 			 * respond to the multicast packets.
17656 			 */
17657 			if (ill_is_probeonly(ill)) {
17658 				freemsg(first_mp);
17659 				return;
17660 			}
17661 
17662 			/*
17663 			 * In the multicast case, applications may have joined
17664 			 * the group from different zones, so we need to deliver
17665 			 * the packet to each of them. Loop through the
17666 			 * multicast memberships structures (ilm) on the receive
17667 			 * ill and send a copy of the packet up each matching
17668 			 * one. However, we don't do this for multicasts sent on
17669 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17670 			 * they must stay in the sender's zone.
17671 			 *
17672 			 * ilm_add_v6() ensures that ilms in the same zone are
17673 			 * contiguous in the ill_ilm list. We use this property
17674 			 * to avoid sending duplicates needed when two
17675 			 * applications in the same zone join the same group on
17676 			 * different logical interfaces: we ignore the ilm if
17677 			 * its zoneid is the same as the last matching one.
17678 			 * In addition, the sending of the packet for
17679 			 * ire_zoneid is delayed until all of the other ilms
17680 			 * have been exhausted.
17681 			 */
17682 			last_zoneid = -1;
17683 			ILM_WALKER_HOLD(recv_ill);
17684 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17685 			    ilm = ilm->ilm_next) {
17686 				if ((ilm->ilm_flags & ILM_DELETED) ||
17687 				    ipha->ipha_dst != ilm->ilm_addr ||
17688 				    ilm->ilm_zoneid == last_zoneid ||
17689 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17690 				    ilm->ilm_zoneid == ALL_ZONES ||
17691 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17692 					continue;
17693 				mp1 = ip_copymsg(first_mp);
17694 				if (mp1 == NULL)
17695 					continue;
17696 				icmp_inbound(q, mp1, B_TRUE, ill,
17697 				    0, sum, mctl_present, B_TRUE,
17698 				    recv_ill, ilm->ilm_zoneid);
17699 				last_zoneid = ilm->ilm_zoneid;
17700 			}
17701 			ILM_WALKER_RELE(recv_ill);
17702 		} else if (ire->ire_type == IRE_BROADCAST) {
17703 			/*
17704 			 * In the broadcast case, there may be many zones
17705 			 * which need a copy of the packet delivered to them.
17706 			 * There is one IRE_BROADCAST per broadcast address
17707 			 * and per zone; we walk those using a helper function.
17708 			 * In addition, the sending of the packet for ire is
17709 			 * delayed until all of the other ires have been
17710 			 * processed.
17711 			 */
17712 			IRB_REFHOLD(ire->ire_bucket);
17713 			ire_zone = NULL;
17714 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17715 			    ire)) != NULL) {
17716 				mp1 = ip_copymsg(first_mp);
17717 				if (mp1 == NULL)
17718 					continue;
17719 
17720 				UPDATE_IB_PKT_COUNT(ire_zone);
17721 				ire_zone->ire_last_used_time = lbolt;
17722 				icmp_inbound(q, mp1, B_TRUE, ill,
17723 				    0, sum, mctl_present, B_TRUE,
17724 				    recv_ill, ire_zone->ire_zoneid);
17725 			}
17726 			IRB_REFRELE(ire->ire_bucket);
17727 		}
17728 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17729 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17730 		    ire->ire_zoneid);
17731 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17732 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17733 		return;
17734 	}
17735 	case IPPROTO_IGMP:
17736 		/*
17737 		 * If we are not willing to accept IGMP packets in clear,
17738 		 * then check with global policy.
17739 		 */
17740 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17741 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17742 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17743 			if (first_mp == NULL)
17744 				return;
17745 		}
17746 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17747 			freemsg(first_mp);
17748 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17749 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17750 			return;
17751 		}
17752 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17753 			/* Bad packet - discarded by igmp_input */
17754 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17755 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17756 			if (mctl_present)
17757 				freeb(first_mp);
17758 			return;
17759 		}
17760 		/*
17761 		 * igmp_input() may have returned the pulled up message.
17762 		 * So first_mp and ipha need to be reinitialized.
17763 		 */
17764 		ipha = (ipha_t *)mp->b_rptr;
17765 		if (mctl_present)
17766 			first_mp->b_cont = mp;
17767 		else
17768 			first_mp = mp;
17769 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17770 		    connf_head != NULL) {
17771 			/* No user-level listener for IGMP packets */
17772 			goto drop_pkt;
17773 		}
17774 		/* deliver to local raw users */
17775 		break;
17776 	case IPPROTO_PIM:
17777 		/*
17778 		 * If we are not willing to accept PIM packets in clear,
17779 		 * then check with global policy.
17780 		 */
17781 		if (ipst->ips_pim_accept_clear_messages == 0) {
17782 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17783 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17784 			if (first_mp == NULL)
17785 				return;
17786 		}
17787 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17788 			freemsg(first_mp);
17789 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17790 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17791 			return;
17792 		}
17793 		if (pim_input(q, mp, ill) != 0) {
17794 			/* Bad packet - discarded by pim_input */
17795 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17796 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17797 			if (mctl_present)
17798 				freeb(first_mp);
17799 			return;
17800 		}
17801 
17802 		/*
17803 		 * pim_input() may have pulled up the message so ipha needs to
17804 		 * be reinitialized.
17805 		 */
17806 		ipha = (ipha_t *)mp->b_rptr;
17807 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17808 		    connf_head != NULL) {
17809 			/* No user-level listener for PIM packets */
17810 			goto drop_pkt;
17811 		}
17812 		/* deliver to local raw users */
17813 		break;
17814 	case IPPROTO_ENCAP:
17815 		/*
17816 		 * Handle self-encapsulated packets (IP-in-IP where
17817 		 * the inner addresses == the outer addresses).
17818 		 */
17819 		hdr_length = IPH_HDR_LENGTH(ipha);
17820 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17821 		    mp->b_wptr) {
17822 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17823 			    sizeof (ipha_t) - mp->b_rptr)) {
17824 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17825 				freemsg(first_mp);
17826 				return;
17827 			}
17828 			ipha = (ipha_t *)mp->b_rptr;
17829 		}
17830 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17831 		/*
17832 		 * Check the sanity of the inner IP header.
17833 		 */
17834 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17835 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17836 			freemsg(first_mp);
17837 			return;
17838 		}
17839 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17840 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17841 			freemsg(first_mp);
17842 			return;
17843 		}
17844 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17845 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17846 			ipsec_in_t *ii;
17847 
17848 			/*
17849 			 * Self-encapsulated tunnel packet. Remove
17850 			 * the outer IP header and fanout again.
17851 			 * We also need to make sure that the inner
17852 			 * header is pulled up until options.
17853 			 */
17854 			mp->b_rptr = (uchar_t *)inner_ipha;
17855 			ipha = inner_ipha;
17856 			hdr_length = IPH_HDR_LENGTH(ipha);
17857 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17858 				if (!pullupmsg(mp, (uchar_t *)ipha +
17859 				    + hdr_length - mp->b_rptr)) {
17860 					freemsg(first_mp);
17861 					return;
17862 				}
17863 				ipha = (ipha_t *)mp->b_rptr;
17864 			}
17865 			if (hdr_length > sizeof (ipha_t)) {
17866 				/* We got options on the inner packet. */
17867 				ipaddr_t dst = ipha->ipha_dst;
17868 
17869 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17870 				    -1) {
17871 					/* Bad options! */
17872 					return;
17873 				}
17874 				if (dst != ipha->ipha_dst) {
17875 					/*
17876 					 * Someone put a source-route in
17877 					 * the inside header of a self-
17878 					 * encapsulated packet.  Drop it
17879 					 * with extreme prejudice and let
17880 					 * the sender know.
17881 					 */
17882 					icmp_unreachable(q, first_mp,
17883 					    ICMP_SOURCE_ROUTE_FAILED,
17884 					    recv_ill->ill_zoneid, ipst);
17885 					return;
17886 				}
17887 			}
17888 			if (!mctl_present) {
17889 				ASSERT(first_mp == mp);
17890 				/*
17891 				 * This means that somebody is sending
17892 				 * Self-encapsualted packets without AH/ESP.
17893 				 * If AH/ESP was present, we would have already
17894 				 * allocated the first_mp.
17895 				 *
17896 				 * Send this packet to find a tunnel endpoint.
17897 				 * if I can't find one, an ICMP
17898 				 * PROTOCOL_UNREACHABLE will get sent.
17899 				 */
17900 				goto fanout;
17901 			}
17902 			/*
17903 			 * We generally store the ill_index if we need to
17904 			 * do IPsec processing as we lose the ill queue when
17905 			 * we come back. But in this case, we never should
17906 			 * have to store the ill_index here as it should have
17907 			 * been stored previously when we processed the
17908 			 * AH/ESP header in this routine or for non-ipsec
17909 			 * cases, we still have the queue. But for some bad
17910 			 * packets from the wire, we can get to IPsec after
17911 			 * this and we better store the index for that case.
17912 			 */
17913 			ill = (ill_t *)q->q_ptr;
17914 			ii = (ipsec_in_t *)first_mp->b_rptr;
17915 			ii->ipsec_in_ill_index =
17916 			    ill->ill_phyint->phyint_ifindex;
17917 			ii->ipsec_in_rill_index =
17918 			    recv_ill->ill_phyint->phyint_ifindex;
17919 			if (ii->ipsec_in_decaps) {
17920 				/*
17921 				 * This packet is self-encapsulated multiple
17922 				 * times. We don't want to recurse infinitely.
17923 				 * To keep it simple, drop the packet.
17924 				 */
17925 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17926 				freemsg(first_mp);
17927 				return;
17928 			}
17929 			ii->ipsec_in_decaps = B_TRUE;
17930 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17931 			    ire);
17932 			return;
17933 		}
17934 		break;
17935 	case IPPROTO_AH:
17936 	case IPPROTO_ESP: {
17937 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17938 
17939 		/*
17940 		 * Fast path for AH/ESP. If this is the first time
17941 		 * we are sending a datagram to AH/ESP, allocate
17942 		 * a IPSEC_IN message and prepend it. Otherwise,
17943 		 * just fanout.
17944 		 */
17945 
17946 		int ipsec_rc;
17947 		ipsec_in_t *ii;
17948 		netstack_t *ns = ipst->ips_netstack;
17949 
17950 		IP_STAT(ipst, ipsec_proto_ahesp);
17951 		if (!mctl_present) {
17952 			ASSERT(first_mp == mp);
17953 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17954 			if (first_mp == NULL) {
17955 				ip1dbg(("ip_proto_input: IPSEC_IN "
17956 				    "allocation failure.\n"));
17957 				freemsg(hada_mp); /* okay ifnull */
17958 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17959 				freemsg(mp);
17960 				return;
17961 			}
17962 			/*
17963 			 * Store the ill_index so that when we come back
17964 			 * from IPsec we ride on the same queue.
17965 			 */
17966 			ill = (ill_t *)q->q_ptr;
17967 			ii = (ipsec_in_t *)first_mp->b_rptr;
17968 			ii->ipsec_in_ill_index =
17969 			    ill->ill_phyint->phyint_ifindex;
17970 			ii->ipsec_in_rill_index =
17971 			    recv_ill->ill_phyint->phyint_ifindex;
17972 			first_mp->b_cont = mp;
17973 			/*
17974 			 * Cache hardware acceleration info.
17975 			 */
17976 			if (hada_mp != NULL) {
17977 				IPSECHW_DEBUG(IPSECHW_PKT,
17978 				    ("ip_rput_local: caching data attr.\n"));
17979 				ii->ipsec_in_accelerated = B_TRUE;
17980 				ii->ipsec_in_da = hada_mp;
17981 				hada_mp = NULL;
17982 			}
17983 		} else {
17984 			ii = (ipsec_in_t *)first_mp->b_rptr;
17985 		}
17986 
17987 		ii->ipsec_in_esp_udp_ports = esp_udp_ports;
17988 
17989 		if (!ipsec_loaded(ipss)) {
17990 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17991 			    ire->ire_zoneid, ipst);
17992 			return;
17993 		}
17994 
17995 		ns = ipst->ips_netstack;
17996 		/* select inbound SA and have IPsec process the pkt */
17997 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17998 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17999 			boolean_t esp_in_udp_sa;
18000 			if (esph == NULL)
18001 				return;
18002 			ASSERT(ii->ipsec_in_esp_sa != NULL);
18003 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
18004 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
18005 			    IPSA_F_NATT) != 0);
18006 			/*
18007 			 * The following is a fancy, but quick, way of saying:
18008 			 * ESP-in-UDP SA and Raw ESP packet --> drop
18009 			 *    OR
18010 			 * ESP SA and ESP-in-UDP packet --> drop
18011 			 */
18012 			if (esp_in_udp_sa != esp_in_udp_packet) {
18013 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
18014 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
18015 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
18016 				    &ns->netstack_ipsec->ipsec_dropper);
18017 				return;
18018 			}
18019 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
18020 			    first_mp, esph);
18021 		} else {
18022 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
18023 			if (ah == NULL)
18024 				return;
18025 			ASSERT(ii->ipsec_in_ah_sa != NULL);
18026 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
18027 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
18028 			    first_mp, ah);
18029 		}
18030 
18031 		switch (ipsec_rc) {
18032 		case IPSEC_STATUS_SUCCESS:
18033 			break;
18034 		case IPSEC_STATUS_FAILED:
18035 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
18036 			/* FALLTHRU */
18037 		case IPSEC_STATUS_PENDING:
18038 			return;
18039 		}
18040 		/* we're done with IPsec processing, send it up */
18041 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
18042 		return;
18043 	}
18044 	default:
18045 		break;
18046 	}
18047 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
18048 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
18049 		    ire->ire_zoneid));
18050 		goto drop_pkt;
18051 	}
18052 	/*
18053 	 * Handle protocols with which IP is less intimate.  There
18054 	 * can be more than one stream bound to a particular
18055 	 * protocol.  When this is the case, each one gets a copy
18056 	 * of any incoming packets.
18057 	 */
18058 fanout:
18059 	ip_fanout_proto(q, first_mp, ill, ipha,
18060 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
18061 	    B_TRUE, recv_ill, ire->ire_zoneid);
18062 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
18063 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
18064 	return;
18065 
18066 drop_pkt:
18067 	freemsg(first_mp);
18068 	if (hada_mp != NULL)
18069 		freeb(hada_mp);
18070 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
18071 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
18072 #undef	rptr
18073 #undef  iphs
18074 
18075 }
18076 
18077 /*
18078  * Update any source route, record route or timestamp options.
18079  * Check that we are at end of strict source route.
18080  * The options have already been checked for sanity in ip_rput_options().
18081  */
18082 static boolean_t
18083 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
18084     ip_stack_t *ipst)
18085 {
18086 	ipoptp_t	opts;
18087 	uchar_t		*opt;
18088 	uint8_t		optval;
18089 	uint8_t		optlen;
18090 	ipaddr_t	dst;
18091 	uint32_t	ts;
18092 	ire_t		*dst_ire;
18093 	timestruc_t	now;
18094 	zoneid_t	zoneid;
18095 	ill_t		*ill;
18096 
18097 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
18098 
18099 	ip2dbg(("ip_rput_local_options\n"));
18100 
18101 	for (optval = ipoptp_first(&opts, ipha);
18102 	    optval != IPOPT_EOL;
18103 	    optval = ipoptp_next(&opts)) {
18104 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
18105 		opt = opts.ipoptp_cur;
18106 		optlen = opts.ipoptp_len;
18107 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
18108 		    optval, optlen));
18109 		switch (optval) {
18110 			uint32_t off;
18111 		case IPOPT_SSRR:
18112 		case IPOPT_LSRR:
18113 			off = opt[IPOPT_OFFSET];
18114 			off--;
18115 			if (optlen < IP_ADDR_LEN ||
18116 			    off > optlen - IP_ADDR_LEN) {
18117 				/* End of source route */
18118 				ip1dbg(("ip_rput_local_options: end of SR\n"));
18119 				break;
18120 			}
18121 			/*
18122 			 * This will only happen if two consecutive entries
18123 			 * in the source route contains our address or if
18124 			 * it is a packet with a loose source route which
18125 			 * reaches us before consuming the whole source route
18126 			 */
18127 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
18128 			if (optval == IPOPT_SSRR) {
18129 				goto bad_src_route;
18130 			}
18131 			/*
18132 			 * Hack: instead of dropping the packet truncate the
18133 			 * source route to what has been used by filling the
18134 			 * rest with IPOPT_NOP.
18135 			 */
18136 			opt[IPOPT_OLEN] = (uint8_t)off;
18137 			while (off < optlen) {
18138 				opt[off++] = IPOPT_NOP;
18139 			}
18140 			break;
18141 		case IPOPT_RR:
18142 			off = opt[IPOPT_OFFSET];
18143 			off--;
18144 			if (optlen < IP_ADDR_LEN ||
18145 			    off > optlen - IP_ADDR_LEN) {
18146 				/* No more room - ignore */
18147 				ip1dbg((
18148 				    "ip_rput_local_options: end of RR\n"));
18149 				break;
18150 			}
18151 			bcopy(&ire->ire_src_addr, (char *)opt + off,
18152 			    IP_ADDR_LEN);
18153 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
18154 			break;
18155 		case IPOPT_TS:
18156 			/* Insert timestamp if there is romm */
18157 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18158 			case IPOPT_TS_TSONLY:
18159 				off = IPOPT_TS_TIMELEN;
18160 				break;
18161 			case IPOPT_TS_PRESPEC:
18162 			case IPOPT_TS_PRESPEC_RFC791:
18163 				/* Verify that the address matched */
18164 				off = opt[IPOPT_OFFSET] - 1;
18165 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18166 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
18167 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
18168 				    ipst);
18169 				if (dst_ire == NULL) {
18170 					/* Not for us */
18171 					break;
18172 				}
18173 				ire_refrele(dst_ire);
18174 				/* FALLTHRU */
18175 			case IPOPT_TS_TSANDADDR:
18176 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18177 				break;
18178 			default:
18179 				/*
18180 				 * ip_*put_options should have already
18181 				 * dropped this packet.
18182 				 */
18183 				cmn_err(CE_PANIC, "ip_rput_local_options: "
18184 				    "unknown IT - bug in ip_rput_options?\n");
18185 				return (B_TRUE);	/* Keep "lint" happy */
18186 			}
18187 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
18188 				/* Increase overflow counter */
18189 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
18190 				opt[IPOPT_POS_OV_FLG] =
18191 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
18192 				    (off << 4));
18193 				break;
18194 			}
18195 			off = opt[IPOPT_OFFSET] - 1;
18196 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18197 			case IPOPT_TS_PRESPEC:
18198 			case IPOPT_TS_PRESPEC_RFC791:
18199 			case IPOPT_TS_TSANDADDR:
18200 				bcopy(&ire->ire_src_addr, (char *)opt + off,
18201 				    IP_ADDR_LEN);
18202 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
18203 				/* FALLTHRU */
18204 			case IPOPT_TS_TSONLY:
18205 				off = opt[IPOPT_OFFSET] - 1;
18206 				/* Compute # of milliseconds since midnight */
18207 				gethrestime(&now);
18208 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
18209 				    now.tv_nsec / (NANOSEC / MILLISEC);
18210 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
18211 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
18212 				break;
18213 			}
18214 			break;
18215 		}
18216 	}
18217 	return (B_TRUE);
18218 
18219 bad_src_route:
18220 	q = WR(q);
18221 	if (q->q_next != NULL)
18222 		ill = q->q_ptr;
18223 	else
18224 		ill = NULL;
18225 
18226 	/* make sure we clear any indication of a hardware checksum */
18227 	DB_CKSUMFLAGS(mp) = 0;
18228 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
18229 	if (zoneid == ALL_ZONES)
18230 		freemsg(mp);
18231 	else
18232 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18233 	return (B_FALSE);
18234 
18235 }
18236 
18237 /*
18238  * Process IP options in an inbound packet.  If an option affects the
18239  * effective destination address, return the next hop address via dstp.
18240  * Returns -1 if something fails in which case an ICMP error has been sent
18241  * and mp freed.
18242  */
18243 static int
18244 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
18245     ip_stack_t *ipst)
18246 {
18247 	ipoptp_t	opts;
18248 	uchar_t		*opt;
18249 	uint8_t		optval;
18250 	uint8_t		optlen;
18251 	ipaddr_t	dst;
18252 	intptr_t	code = 0;
18253 	ire_t		*ire = NULL;
18254 	zoneid_t	zoneid;
18255 	ill_t		*ill;
18256 
18257 	ip2dbg(("ip_rput_options\n"));
18258 	dst = ipha->ipha_dst;
18259 	for (optval = ipoptp_first(&opts, ipha);
18260 	    optval != IPOPT_EOL;
18261 	    optval = ipoptp_next(&opts)) {
18262 		opt = opts.ipoptp_cur;
18263 		optlen = opts.ipoptp_len;
18264 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
18265 		    optval, optlen));
18266 		/*
18267 		 * Note: we need to verify the checksum before we
18268 		 * modify anything thus this routine only extracts the next
18269 		 * hop dst from any source route.
18270 		 */
18271 		switch (optval) {
18272 			uint32_t off;
18273 		case IPOPT_SSRR:
18274 		case IPOPT_LSRR:
18275 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18276 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18277 			if (ire == NULL) {
18278 				if (optval == IPOPT_SSRR) {
18279 					ip1dbg(("ip_rput_options: not next"
18280 					    " strict source route 0x%x\n",
18281 					    ntohl(dst)));
18282 					code = (char *)&ipha->ipha_dst -
18283 					    (char *)ipha;
18284 					goto param_prob; /* RouterReq's */
18285 				}
18286 				ip2dbg(("ip_rput_options: "
18287 				    "not next source route 0x%x\n",
18288 				    ntohl(dst)));
18289 				break;
18290 			}
18291 			ire_refrele(ire);
18292 
18293 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18294 				ip1dbg((
18295 				    "ip_rput_options: bad option offset\n"));
18296 				code = (char *)&opt[IPOPT_OLEN] -
18297 				    (char *)ipha;
18298 				goto param_prob;
18299 			}
18300 			off = opt[IPOPT_OFFSET];
18301 			off--;
18302 		redo_srr:
18303 			if (optlen < IP_ADDR_LEN ||
18304 			    off > optlen - IP_ADDR_LEN) {
18305 				/* End of source route */
18306 				ip1dbg(("ip_rput_options: end of SR\n"));
18307 				break;
18308 			}
18309 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18310 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18311 			    ntohl(dst)));
18312 
18313 			/*
18314 			 * Check if our address is present more than
18315 			 * once as consecutive hops in source route.
18316 			 * XXX verify per-interface ip_forwarding
18317 			 * for source route?
18318 			 */
18319 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18320 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18321 
18322 			if (ire != NULL) {
18323 				ire_refrele(ire);
18324 				off += IP_ADDR_LEN;
18325 				goto redo_srr;
18326 			}
18327 
18328 			if (dst == htonl(INADDR_LOOPBACK)) {
18329 				ip1dbg(("ip_rput_options: loopback addr in "
18330 				    "source route!\n"));
18331 				goto bad_src_route;
18332 			}
18333 			/*
18334 			 * For strict: verify that dst is directly
18335 			 * reachable.
18336 			 */
18337 			if (optval == IPOPT_SSRR) {
18338 				ire = ire_ftable_lookup(dst, 0, 0,
18339 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18340 				    MBLK_GETLABEL(mp),
18341 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18342 				if (ire == NULL) {
18343 					ip1dbg(("ip_rput_options: SSRR not "
18344 					    "directly reachable: 0x%x\n",
18345 					    ntohl(dst)));
18346 					goto bad_src_route;
18347 				}
18348 				ire_refrele(ire);
18349 			}
18350 			/*
18351 			 * Defer update of the offset and the record route
18352 			 * until the packet is forwarded.
18353 			 */
18354 			break;
18355 		case IPOPT_RR:
18356 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18357 				ip1dbg((
18358 				    "ip_rput_options: bad option offset\n"));
18359 				code = (char *)&opt[IPOPT_OLEN] -
18360 				    (char *)ipha;
18361 				goto param_prob;
18362 			}
18363 			break;
18364 		case IPOPT_TS:
18365 			/*
18366 			 * Verify that length >= 5 and that there is either
18367 			 * room for another timestamp or that the overflow
18368 			 * counter is not maxed out.
18369 			 */
18370 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18371 			if (optlen < IPOPT_MINLEN_IT) {
18372 				goto param_prob;
18373 			}
18374 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18375 				ip1dbg((
18376 				    "ip_rput_options: bad option offset\n"));
18377 				code = (char *)&opt[IPOPT_OFFSET] -
18378 				    (char *)ipha;
18379 				goto param_prob;
18380 			}
18381 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18382 			case IPOPT_TS_TSONLY:
18383 				off = IPOPT_TS_TIMELEN;
18384 				break;
18385 			case IPOPT_TS_TSANDADDR:
18386 			case IPOPT_TS_PRESPEC:
18387 			case IPOPT_TS_PRESPEC_RFC791:
18388 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18389 				break;
18390 			default:
18391 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18392 				    (char *)ipha;
18393 				goto param_prob;
18394 			}
18395 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18396 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18397 				/*
18398 				 * No room and the overflow counter is 15
18399 				 * already.
18400 				 */
18401 				goto param_prob;
18402 			}
18403 			break;
18404 		}
18405 	}
18406 
18407 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18408 		*dstp = dst;
18409 		return (0);
18410 	}
18411 
18412 	ip1dbg(("ip_rput_options: error processing IP options."));
18413 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18414 
18415 param_prob:
18416 	q = WR(q);
18417 	if (q->q_next != NULL)
18418 		ill = q->q_ptr;
18419 	else
18420 		ill = NULL;
18421 
18422 	/* make sure we clear any indication of a hardware checksum */
18423 	DB_CKSUMFLAGS(mp) = 0;
18424 	/* Don't know whether this is for non-global or global/forwarding */
18425 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18426 	if (zoneid == ALL_ZONES)
18427 		freemsg(mp);
18428 	else
18429 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18430 	return (-1);
18431 
18432 bad_src_route:
18433 	q = WR(q);
18434 	if (q->q_next != NULL)
18435 		ill = q->q_ptr;
18436 	else
18437 		ill = NULL;
18438 
18439 	/* make sure we clear any indication of a hardware checksum */
18440 	DB_CKSUMFLAGS(mp) = 0;
18441 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18442 	if (zoneid == ALL_ZONES)
18443 		freemsg(mp);
18444 	else
18445 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18446 	return (-1);
18447 }
18448 
18449 /*
18450  * IP & ICMP info in >=14 msg's ...
18451  *  - ip fixed part (mib2_ip_t)
18452  *  - icmp fixed part (mib2_icmp_t)
18453  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18454  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18455  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18456  *  - ipRouteAttributeTable (ip 102)	labeled routes
18457  *  - ip multicast membership (ip_member_t)
18458  *  - ip multicast source filtering (ip_grpsrc_t)
18459  *  - igmp fixed part (struct igmpstat)
18460  *  - multicast routing stats (struct mrtstat)
18461  *  - multicast routing vifs (array of struct vifctl)
18462  *  - multicast routing routes (array of struct mfcctl)
18463  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18464  *					One per ill plus one generic
18465  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18466  *					One per ill plus one generic
18467  *  - ipv6RouteEntry			all IPv6 IREs
18468  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18469  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18470  *  - ipv6AddrEntry			all IPv6 ipifs
18471  *  - ipv6 multicast membership (ipv6_member_t)
18472  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18473  *
18474  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18475  *
18476  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18477  * already filled in by the caller.
18478  * Return value of 0 indicates that no messages were sent and caller
18479  * should free mpctl.
18480  */
18481 int
18482 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18483 {
18484 	ip_stack_t *ipst;
18485 	sctp_stack_t *sctps;
18486 
18487 	if (q->q_next != NULL) {
18488 		ipst = ILLQ_TO_IPST(q);
18489 	} else {
18490 		ipst = CONNQ_TO_IPST(q);
18491 	}
18492 	ASSERT(ipst != NULL);
18493 	sctps = ipst->ips_netstack->netstack_sctp;
18494 
18495 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18496 		return (0);
18497 	}
18498 
18499 	/*
18500 	 * For the purposes of the (broken) packet shell use
18501 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18502 	 * to make TCP and UDP appear first in the list of mib items.
18503 	 * TBD: We could expand this and use it in netstat so that
18504 	 * the kernel doesn't have to produce large tables (connections,
18505 	 * routes, etc) when netstat only wants the statistics or a particular
18506 	 * table.
18507 	 */
18508 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18509 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18510 			return (1);
18511 		}
18512 	}
18513 
18514 	if (level != MIB2_TCP) {
18515 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18516 			return (1);
18517 		}
18518 	}
18519 
18520 	if (level != MIB2_UDP) {
18521 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18522 			return (1);
18523 		}
18524 	}
18525 
18526 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18527 	    ipst)) == NULL) {
18528 		return (1);
18529 	}
18530 
18531 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18532 		return (1);
18533 	}
18534 
18535 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18536 		return (1);
18537 	}
18538 
18539 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18540 		return (1);
18541 	}
18542 
18543 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18544 		return (1);
18545 	}
18546 
18547 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18548 		return (1);
18549 	}
18550 
18551 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18552 		return (1);
18553 	}
18554 
18555 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18556 		return (1);
18557 	}
18558 
18559 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18560 		return (1);
18561 	}
18562 
18563 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18564 		return (1);
18565 	}
18566 
18567 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18568 		return (1);
18569 	}
18570 
18571 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18572 		return (1);
18573 	}
18574 
18575 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18576 		return (1);
18577 	}
18578 
18579 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18580 		return (1);
18581 	}
18582 
18583 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18584 		return (1);
18585 	}
18586 
18587 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18588 	if (mpctl == NULL) {
18589 		return (1);
18590 	}
18591 
18592 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18593 		return (1);
18594 	}
18595 	freemsg(mpctl);
18596 	return (1);
18597 }
18598 
18599 
18600 /* Get global (legacy) IPv4 statistics */
18601 static mblk_t *
18602 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18603     ip_stack_t *ipst)
18604 {
18605 	mib2_ip_t		old_ip_mib;
18606 	struct opthdr		*optp;
18607 	mblk_t			*mp2ctl;
18608 
18609 	/*
18610 	 * make a copy of the original message
18611 	 */
18612 	mp2ctl = copymsg(mpctl);
18613 
18614 	/* fixed length IP structure... */
18615 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18616 	optp->level = MIB2_IP;
18617 	optp->name = 0;
18618 	SET_MIB(old_ip_mib.ipForwarding,
18619 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18620 	SET_MIB(old_ip_mib.ipDefaultTTL,
18621 	    (uint32_t)ipst->ips_ip_def_ttl);
18622 	SET_MIB(old_ip_mib.ipReasmTimeout,
18623 	    ipst->ips_ip_g_frag_timeout);
18624 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18625 	    sizeof (mib2_ipAddrEntry_t));
18626 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18627 	    sizeof (mib2_ipRouteEntry_t));
18628 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18629 	    sizeof (mib2_ipNetToMediaEntry_t));
18630 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18631 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18632 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18633 	    sizeof (mib2_ipAttributeEntry_t));
18634 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18635 
18636 	/*
18637 	 * Grab the statistics from the new IP MIB
18638 	 */
18639 	SET_MIB(old_ip_mib.ipInReceives,
18640 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18641 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18642 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18643 	SET_MIB(old_ip_mib.ipForwDatagrams,
18644 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18645 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18646 	    ipmib->ipIfStatsInUnknownProtos);
18647 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18648 	SET_MIB(old_ip_mib.ipInDelivers,
18649 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18650 	SET_MIB(old_ip_mib.ipOutRequests,
18651 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18652 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18653 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18654 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18655 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18656 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18657 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18658 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18659 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18660 
18661 	/* ipRoutingDiscards is not being used */
18662 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18663 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18664 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18665 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18666 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18667 	    ipmib->ipIfStatsReasmDuplicates);
18668 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18669 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18670 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18671 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18672 	SET_MIB(old_ip_mib.rawipInOverflows,
18673 	    ipmib->rawipIfStatsInOverflows);
18674 
18675 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18676 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18677 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18678 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18679 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18680 	    ipmib->ipIfStatsOutSwitchIPVersion);
18681 
18682 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18683 	    (int)sizeof (old_ip_mib))) {
18684 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18685 		    (uint_t)sizeof (old_ip_mib)));
18686 	}
18687 
18688 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18689 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18690 	    (int)optp->level, (int)optp->name, (int)optp->len));
18691 	qreply(q, mpctl);
18692 	return (mp2ctl);
18693 }
18694 
18695 /* Per interface IPv4 statistics */
18696 static mblk_t *
18697 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18698 {
18699 	struct opthdr		*optp;
18700 	mblk_t			*mp2ctl;
18701 	ill_t			*ill;
18702 	ill_walk_context_t	ctx;
18703 	mblk_t			*mp_tail = NULL;
18704 	mib2_ipIfStatsEntry_t	global_ip_mib;
18705 
18706 	/*
18707 	 * Make a copy of the original message
18708 	 */
18709 	mp2ctl = copymsg(mpctl);
18710 
18711 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18712 	optp->level = MIB2_IP;
18713 	optp->name = MIB2_IP_TRAFFIC_STATS;
18714 	/* Include "unknown interface" ip_mib */
18715 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18716 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18717 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18718 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18719 	    (ipst->ips_ip_g_forward ? 1 : 2));
18720 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18721 	    (uint32_t)ipst->ips_ip_def_ttl);
18722 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18723 	    sizeof (mib2_ipIfStatsEntry_t));
18724 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18725 	    sizeof (mib2_ipAddrEntry_t));
18726 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18727 	    sizeof (mib2_ipRouteEntry_t));
18728 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18729 	    sizeof (mib2_ipNetToMediaEntry_t));
18730 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18731 	    sizeof (ip_member_t));
18732 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18733 	    sizeof (ip_grpsrc_t));
18734 
18735 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18736 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18737 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18738 		    "failed to allocate %u bytes\n",
18739 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18740 	}
18741 
18742 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18743 
18744 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18745 	ill = ILL_START_WALK_V4(&ctx, ipst);
18746 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18747 		ill->ill_ip_mib->ipIfStatsIfIndex =
18748 		    ill->ill_phyint->phyint_ifindex;
18749 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18750 		    (ipst->ips_ip_g_forward ? 1 : 2));
18751 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18752 		    (uint32_t)ipst->ips_ip_def_ttl);
18753 
18754 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18755 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18756 		    (char *)ill->ill_ip_mib,
18757 		    (int)sizeof (*ill->ill_ip_mib))) {
18758 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18759 			    "failed to allocate %u bytes\n",
18760 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18761 		}
18762 	}
18763 	rw_exit(&ipst->ips_ill_g_lock);
18764 
18765 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18766 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18767 	    "level %d, name %d, len %d\n",
18768 	    (int)optp->level, (int)optp->name, (int)optp->len));
18769 	qreply(q, mpctl);
18770 
18771 	if (mp2ctl == NULL)
18772 		return (NULL);
18773 
18774 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18775 }
18776 
18777 /* Global IPv4 ICMP statistics */
18778 static mblk_t *
18779 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18780 {
18781 	struct opthdr		*optp;
18782 	mblk_t			*mp2ctl;
18783 
18784 	/*
18785 	 * Make a copy of the original message
18786 	 */
18787 	mp2ctl = copymsg(mpctl);
18788 
18789 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18790 	optp->level = MIB2_ICMP;
18791 	optp->name = 0;
18792 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18793 	    (int)sizeof (ipst->ips_icmp_mib))) {
18794 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18795 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18796 	}
18797 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18798 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18799 	    (int)optp->level, (int)optp->name, (int)optp->len));
18800 	qreply(q, mpctl);
18801 	return (mp2ctl);
18802 }
18803 
18804 /* Global IPv4 IGMP statistics */
18805 static mblk_t *
18806 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18807 {
18808 	struct opthdr		*optp;
18809 	mblk_t			*mp2ctl;
18810 
18811 	/*
18812 	 * make a copy of the original message
18813 	 */
18814 	mp2ctl = copymsg(mpctl);
18815 
18816 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18817 	optp->level = EXPER_IGMP;
18818 	optp->name = 0;
18819 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18820 	    (int)sizeof (ipst->ips_igmpstat))) {
18821 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18822 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18823 	}
18824 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18825 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18826 	    (int)optp->level, (int)optp->name, (int)optp->len));
18827 	qreply(q, mpctl);
18828 	return (mp2ctl);
18829 }
18830 
18831 /* Global IPv4 Multicast Routing statistics */
18832 static mblk_t *
18833 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18834 {
18835 	struct opthdr		*optp;
18836 	mblk_t			*mp2ctl;
18837 
18838 	/*
18839 	 * make a copy of the original message
18840 	 */
18841 	mp2ctl = copymsg(mpctl);
18842 
18843 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18844 	optp->level = EXPER_DVMRP;
18845 	optp->name = 0;
18846 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18847 		ip0dbg(("ip_mroute_stats: failed\n"));
18848 	}
18849 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18850 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18851 	    (int)optp->level, (int)optp->name, (int)optp->len));
18852 	qreply(q, mpctl);
18853 	return (mp2ctl);
18854 }
18855 
18856 /* IPv4 address information */
18857 static mblk_t *
18858 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18859 {
18860 	struct opthdr		*optp;
18861 	mblk_t			*mp2ctl;
18862 	mblk_t			*mp_tail = NULL;
18863 	ill_t			*ill;
18864 	ipif_t			*ipif;
18865 	uint_t			bitval;
18866 	mib2_ipAddrEntry_t	mae;
18867 	zoneid_t		zoneid;
18868 	ill_walk_context_t ctx;
18869 
18870 	/*
18871 	 * make a copy of the original message
18872 	 */
18873 	mp2ctl = copymsg(mpctl);
18874 
18875 	/* ipAddrEntryTable */
18876 
18877 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18878 	optp->level = MIB2_IP;
18879 	optp->name = MIB2_IP_ADDR;
18880 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18881 
18882 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18883 	ill = ILL_START_WALK_V4(&ctx, ipst);
18884 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18885 		for (ipif = ill->ill_ipif; ipif != NULL;
18886 		    ipif = ipif->ipif_next) {
18887 			if (ipif->ipif_zoneid != zoneid &&
18888 			    ipif->ipif_zoneid != ALL_ZONES)
18889 				continue;
18890 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18891 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18892 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18893 
18894 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18895 			    OCTET_LENGTH);
18896 			mae.ipAdEntIfIndex.o_length =
18897 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18898 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18899 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18900 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18901 			mae.ipAdEntInfo.ae_subnet_len =
18902 			    ip_mask_to_plen(ipif->ipif_net_mask);
18903 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18904 			for (bitval = 1;
18905 			    bitval &&
18906 			    !(bitval & ipif->ipif_brd_addr);
18907 			    bitval <<= 1)
18908 				noop;
18909 			mae.ipAdEntBcastAddr = bitval;
18910 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18911 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18912 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18913 			mae.ipAdEntInfo.ae_broadcast_addr =
18914 			    ipif->ipif_brd_addr;
18915 			mae.ipAdEntInfo.ae_pp_dst_addr =
18916 			    ipif->ipif_pp_dst_addr;
18917 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18918 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18919 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18920 
18921 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18922 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18923 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18924 				    "allocate %u bytes\n",
18925 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18926 			}
18927 		}
18928 	}
18929 	rw_exit(&ipst->ips_ill_g_lock);
18930 
18931 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18932 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18933 	    (int)optp->level, (int)optp->name, (int)optp->len));
18934 	qreply(q, mpctl);
18935 	return (mp2ctl);
18936 }
18937 
18938 /* IPv6 address information */
18939 static mblk_t *
18940 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18941 {
18942 	struct opthdr		*optp;
18943 	mblk_t			*mp2ctl;
18944 	mblk_t			*mp_tail = NULL;
18945 	ill_t			*ill;
18946 	ipif_t			*ipif;
18947 	mib2_ipv6AddrEntry_t	mae6;
18948 	zoneid_t		zoneid;
18949 	ill_walk_context_t	ctx;
18950 
18951 	/*
18952 	 * make a copy of the original message
18953 	 */
18954 	mp2ctl = copymsg(mpctl);
18955 
18956 	/* ipv6AddrEntryTable */
18957 
18958 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18959 	optp->level = MIB2_IP6;
18960 	optp->name = MIB2_IP6_ADDR;
18961 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18962 
18963 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18964 	ill = ILL_START_WALK_V6(&ctx, ipst);
18965 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18966 		for (ipif = ill->ill_ipif; ipif != NULL;
18967 		    ipif = ipif->ipif_next) {
18968 			if (ipif->ipif_zoneid != zoneid &&
18969 			    ipif->ipif_zoneid != ALL_ZONES)
18970 				continue;
18971 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18972 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18973 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18974 
18975 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18976 			    OCTET_LENGTH);
18977 			mae6.ipv6AddrIfIndex.o_length =
18978 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18979 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18980 			mae6.ipv6AddrPfxLength =
18981 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18982 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18983 			mae6.ipv6AddrInfo.ae_subnet_len =
18984 			    mae6.ipv6AddrPfxLength;
18985 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18986 
18987 			/* Type: stateless(1), stateful(2), unknown(3) */
18988 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18989 				mae6.ipv6AddrType = 1;
18990 			else
18991 				mae6.ipv6AddrType = 2;
18992 			/* Anycast: true(1), false(2) */
18993 			if (ipif->ipif_flags & IPIF_ANYCAST)
18994 				mae6.ipv6AddrAnycastFlag = 1;
18995 			else
18996 				mae6.ipv6AddrAnycastFlag = 2;
18997 
18998 			/*
18999 			 * Address status: preferred(1), deprecated(2),
19000 			 * invalid(3), inaccessible(4), unknown(5)
19001 			 */
19002 			if (ipif->ipif_flags & IPIF_NOLOCAL)
19003 				mae6.ipv6AddrStatus = 3;
19004 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
19005 				mae6.ipv6AddrStatus = 2;
19006 			else
19007 				mae6.ipv6AddrStatus = 1;
19008 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
19009 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
19010 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
19011 			    ipif->ipif_v6pp_dst_addr;
19012 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
19013 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
19014 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
19015 			mae6.ipv6AddrIdentifier = ill->ill_token;
19016 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
19017 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
19018 			mae6.ipv6AddrRetransmitTime =
19019 			    ill->ill_reachable_retrans_time;
19020 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19021 			    (char *)&mae6,
19022 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
19023 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
19024 				    "allocate %u bytes\n",
19025 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
19026 			}
19027 		}
19028 	}
19029 	rw_exit(&ipst->ips_ill_g_lock);
19030 
19031 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19032 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
19033 	    (int)optp->level, (int)optp->name, (int)optp->len));
19034 	qreply(q, mpctl);
19035 	return (mp2ctl);
19036 }
19037 
19038 /* IPv4 multicast group membership. */
19039 static mblk_t *
19040 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19041 {
19042 	struct opthdr		*optp;
19043 	mblk_t			*mp2ctl;
19044 	ill_t			*ill;
19045 	ipif_t			*ipif;
19046 	ilm_t			*ilm;
19047 	ip_member_t		ipm;
19048 	mblk_t			*mp_tail = NULL;
19049 	ill_walk_context_t	ctx;
19050 	zoneid_t		zoneid;
19051 
19052 	/*
19053 	 * make a copy of the original message
19054 	 */
19055 	mp2ctl = copymsg(mpctl);
19056 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19057 
19058 	/* ipGroupMember table */
19059 	optp = (struct opthdr *)&mpctl->b_rptr[
19060 	    sizeof (struct T_optmgmt_ack)];
19061 	optp->level = MIB2_IP;
19062 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
19063 
19064 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19065 	ill = ILL_START_WALK_V4(&ctx, ipst);
19066 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19067 		ILM_WALKER_HOLD(ill);
19068 		for (ipif = ill->ill_ipif; ipif != NULL;
19069 		    ipif = ipif->ipif_next) {
19070 			if (ipif->ipif_zoneid != zoneid &&
19071 			    ipif->ipif_zoneid != ALL_ZONES)
19072 				continue;	/* not this zone */
19073 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
19074 			    OCTET_LENGTH);
19075 			ipm.ipGroupMemberIfIndex.o_length =
19076 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
19077 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
19078 				ASSERT(ilm->ilm_ipif != NULL);
19079 				ASSERT(ilm->ilm_ill == NULL);
19080 				if (ilm->ilm_ipif != ipif)
19081 					continue;
19082 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
19083 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
19084 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
19085 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19086 				    (char *)&ipm, (int)sizeof (ipm))) {
19087 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
19088 					    "failed to allocate %u bytes\n",
19089 					    (uint_t)sizeof (ipm)));
19090 				}
19091 			}
19092 		}
19093 		ILM_WALKER_RELE(ill);
19094 	}
19095 	rw_exit(&ipst->ips_ill_g_lock);
19096 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19097 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19098 	    (int)optp->level, (int)optp->name, (int)optp->len));
19099 	qreply(q, mpctl);
19100 	return (mp2ctl);
19101 }
19102 
19103 /* IPv6 multicast group membership. */
19104 static mblk_t *
19105 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19106 {
19107 	struct opthdr		*optp;
19108 	mblk_t			*mp2ctl;
19109 	ill_t			*ill;
19110 	ilm_t			*ilm;
19111 	ipv6_member_t		ipm6;
19112 	mblk_t			*mp_tail = NULL;
19113 	ill_walk_context_t	ctx;
19114 	zoneid_t		zoneid;
19115 
19116 	/*
19117 	 * make a copy of the original message
19118 	 */
19119 	mp2ctl = copymsg(mpctl);
19120 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19121 
19122 	/* ip6GroupMember table */
19123 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19124 	optp->level = MIB2_IP6;
19125 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
19126 
19127 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19128 	ill = ILL_START_WALK_V6(&ctx, ipst);
19129 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19130 		ILM_WALKER_HOLD(ill);
19131 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
19132 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
19133 			ASSERT(ilm->ilm_ipif == NULL);
19134 			ASSERT(ilm->ilm_ill != NULL);
19135 			if (ilm->ilm_zoneid != zoneid)
19136 				continue;	/* not this zone */
19137 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
19138 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
19139 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
19140 			if (!snmp_append_data2(mpctl->b_cont,
19141 			    &mp_tail,
19142 			    (char *)&ipm6, (int)sizeof (ipm6))) {
19143 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
19144 				    "failed to allocate %u bytes\n",
19145 				    (uint_t)sizeof (ipm6)));
19146 			}
19147 		}
19148 		ILM_WALKER_RELE(ill);
19149 	}
19150 	rw_exit(&ipst->ips_ill_g_lock);
19151 
19152 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19153 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19154 	    (int)optp->level, (int)optp->name, (int)optp->len));
19155 	qreply(q, mpctl);
19156 	return (mp2ctl);
19157 }
19158 
19159 /* IP multicast filtered sources */
19160 static mblk_t *
19161 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19162 {
19163 	struct opthdr		*optp;
19164 	mblk_t			*mp2ctl;
19165 	ill_t			*ill;
19166 	ipif_t			*ipif;
19167 	ilm_t			*ilm;
19168 	ip_grpsrc_t		ips;
19169 	mblk_t			*mp_tail = NULL;
19170 	ill_walk_context_t	ctx;
19171 	zoneid_t		zoneid;
19172 	int			i;
19173 	slist_t			*sl;
19174 
19175 	/*
19176 	 * make a copy of the original message
19177 	 */
19178 	mp2ctl = copymsg(mpctl);
19179 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19180 
19181 	/* ipGroupSource table */
19182 	optp = (struct opthdr *)&mpctl->b_rptr[
19183 	    sizeof (struct T_optmgmt_ack)];
19184 	optp->level = MIB2_IP;
19185 	optp->name = EXPER_IP_GROUP_SOURCES;
19186 
19187 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19188 	ill = ILL_START_WALK_V4(&ctx, ipst);
19189 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19190 		ILM_WALKER_HOLD(ill);
19191 		for (ipif = ill->ill_ipif; ipif != NULL;
19192 		    ipif = ipif->ipif_next) {
19193 			if (ipif->ipif_zoneid != zoneid)
19194 				continue;	/* not this zone */
19195 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
19196 			    OCTET_LENGTH);
19197 			ips.ipGroupSourceIfIndex.o_length =
19198 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
19199 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
19200 				ASSERT(ilm->ilm_ipif != NULL);
19201 				ASSERT(ilm->ilm_ill == NULL);
19202 				sl = ilm->ilm_filter;
19203 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
19204 					continue;
19205 				ips.ipGroupSourceGroup = ilm->ilm_addr;
19206 				for (i = 0; i < sl->sl_numsrc; i++) {
19207 					if (!IN6_IS_ADDR_V4MAPPED(
19208 					    &sl->sl_addr[i]))
19209 						continue;
19210 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
19211 					    ips.ipGroupSourceAddress);
19212 					if (snmp_append_data2(mpctl->b_cont,
19213 					    &mp_tail, (char *)&ips,
19214 					    (int)sizeof (ips)) == 0) {
19215 						ip1dbg(("ip_snmp_get_mib2_"
19216 						    "ip_group_src: failed to "
19217 						    "allocate %u bytes\n",
19218 						    (uint_t)sizeof (ips)));
19219 					}
19220 				}
19221 			}
19222 		}
19223 		ILM_WALKER_RELE(ill);
19224 	}
19225 	rw_exit(&ipst->ips_ill_g_lock);
19226 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19227 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19228 	    (int)optp->level, (int)optp->name, (int)optp->len));
19229 	qreply(q, mpctl);
19230 	return (mp2ctl);
19231 }
19232 
19233 /* IPv6 multicast filtered sources. */
19234 static mblk_t *
19235 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19236 {
19237 	struct opthdr		*optp;
19238 	mblk_t			*mp2ctl;
19239 	ill_t			*ill;
19240 	ilm_t			*ilm;
19241 	ipv6_grpsrc_t		ips6;
19242 	mblk_t			*mp_tail = NULL;
19243 	ill_walk_context_t	ctx;
19244 	zoneid_t		zoneid;
19245 	int			i;
19246 	slist_t			*sl;
19247 
19248 	/*
19249 	 * make a copy of the original message
19250 	 */
19251 	mp2ctl = copymsg(mpctl);
19252 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19253 
19254 	/* ip6GroupMember table */
19255 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19256 	optp->level = MIB2_IP6;
19257 	optp->name = EXPER_IP6_GROUP_SOURCES;
19258 
19259 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19260 	ill = ILL_START_WALK_V6(&ctx, ipst);
19261 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19262 		ILM_WALKER_HOLD(ill);
19263 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
19264 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
19265 			ASSERT(ilm->ilm_ipif == NULL);
19266 			ASSERT(ilm->ilm_ill != NULL);
19267 			sl = ilm->ilm_filter;
19268 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
19269 				continue;
19270 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
19271 			for (i = 0; i < sl->sl_numsrc; i++) {
19272 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
19273 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19274 				    (char *)&ips6, (int)sizeof (ips6))) {
19275 					ip1dbg(("ip_snmp_get_mib2_ip6_"
19276 					    "group_src: failed to allocate "
19277 					    "%u bytes\n",
19278 					    (uint_t)sizeof (ips6)));
19279 				}
19280 			}
19281 		}
19282 		ILM_WALKER_RELE(ill);
19283 	}
19284 	rw_exit(&ipst->ips_ill_g_lock);
19285 
19286 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19287 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19288 	    (int)optp->level, (int)optp->name, (int)optp->len));
19289 	qreply(q, mpctl);
19290 	return (mp2ctl);
19291 }
19292 
19293 /* Multicast routing virtual interface table. */
19294 static mblk_t *
19295 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19296 {
19297 	struct opthdr		*optp;
19298 	mblk_t			*mp2ctl;
19299 
19300 	/*
19301 	 * make a copy of the original message
19302 	 */
19303 	mp2ctl = copymsg(mpctl);
19304 
19305 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19306 	optp->level = EXPER_DVMRP;
19307 	optp->name = EXPER_DVMRP_VIF;
19308 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
19309 		ip0dbg(("ip_mroute_vif: failed\n"));
19310 	}
19311 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19312 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19313 	    (int)optp->level, (int)optp->name, (int)optp->len));
19314 	qreply(q, mpctl);
19315 	return (mp2ctl);
19316 }
19317 
19318 /* Multicast routing table. */
19319 static mblk_t *
19320 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19321 {
19322 	struct opthdr		*optp;
19323 	mblk_t			*mp2ctl;
19324 
19325 	/*
19326 	 * make a copy of the original message
19327 	 */
19328 	mp2ctl = copymsg(mpctl);
19329 
19330 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19331 	optp->level = EXPER_DVMRP;
19332 	optp->name = EXPER_DVMRP_MRT;
19333 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19334 		ip0dbg(("ip_mroute_mrt: failed\n"));
19335 	}
19336 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19337 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19338 	    (int)optp->level, (int)optp->name, (int)optp->len));
19339 	qreply(q, mpctl);
19340 	return (mp2ctl);
19341 }
19342 
19343 /*
19344  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19345  * in one IRE walk.
19346  */
19347 static mblk_t *
19348 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19349 {
19350 	struct opthdr	*optp;
19351 	mblk_t		*mp2ctl;	/* Returned */
19352 	mblk_t		*mp3ctl;	/* nettomedia */
19353 	mblk_t		*mp4ctl;	/* routeattrs */
19354 	iproutedata_t	ird;
19355 	zoneid_t	zoneid;
19356 
19357 	/*
19358 	 * make copies of the original message
19359 	 *	- mp2ctl is returned unchanged to the caller for his use
19360 	 *	- mpctl is sent upstream as ipRouteEntryTable
19361 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19362 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19363 	 */
19364 	mp2ctl = copymsg(mpctl);
19365 	mp3ctl = copymsg(mpctl);
19366 	mp4ctl = copymsg(mpctl);
19367 	if (mp3ctl == NULL || mp4ctl == NULL) {
19368 		freemsg(mp4ctl);
19369 		freemsg(mp3ctl);
19370 		freemsg(mp2ctl);
19371 		freemsg(mpctl);
19372 		return (NULL);
19373 	}
19374 
19375 	bzero(&ird, sizeof (ird));
19376 
19377 	ird.ird_route.lp_head = mpctl->b_cont;
19378 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19379 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19380 
19381 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19382 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19383 
19384 	/* ipRouteEntryTable in mpctl */
19385 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19386 	optp->level = MIB2_IP;
19387 	optp->name = MIB2_IP_ROUTE;
19388 	optp->len = msgdsize(ird.ird_route.lp_head);
19389 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19390 	    (int)optp->level, (int)optp->name, (int)optp->len));
19391 	qreply(q, mpctl);
19392 
19393 	/* ipNetToMediaEntryTable in mp3ctl */
19394 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19395 	optp->level = MIB2_IP;
19396 	optp->name = MIB2_IP_MEDIA;
19397 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19398 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19399 	    (int)optp->level, (int)optp->name, (int)optp->len));
19400 	qreply(q, mp3ctl);
19401 
19402 	/* ipRouteAttributeTable in mp4ctl */
19403 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19404 	optp->level = MIB2_IP;
19405 	optp->name = EXPER_IP_RTATTR;
19406 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19407 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19408 	    (int)optp->level, (int)optp->name, (int)optp->len));
19409 	if (optp->len == 0)
19410 		freemsg(mp4ctl);
19411 	else
19412 		qreply(q, mp4ctl);
19413 
19414 	return (mp2ctl);
19415 }
19416 
19417 /*
19418  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19419  * ipv6NetToMediaEntryTable in an NDP walk.
19420  */
19421 static mblk_t *
19422 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19423 {
19424 	struct opthdr	*optp;
19425 	mblk_t		*mp2ctl;	/* Returned */
19426 	mblk_t		*mp3ctl;	/* nettomedia */
19427 	mblk_t		*mp4ctl;	/* routeattrs */
19428 	iproutedata_t	ird;
19429 	zoneid_t	zoneid;
19430 
19431 	/*
19432 	 * make copies of the original message
19433 	 *	- mp2ctl is returned unchanged to the caller for his use
19434 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19435 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19436 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19437 	 */
19438 	mp2ctl = copymsg(mpctl);
19439 	mp3ctl = copymsg(mpctl);
19440 	mp4ctl = copymsg(mpctl);
19441 	if (mp3ctl == NULL || mp4ctl == NULL) {
19442 		freemsg(mp4ctl);
19443 		freemsg(mp3ctl);
19444 		freemsg(mp2ctl);
19445 		freemsg(mpctl);
19446 		return (NULL);
19447 	}
19448 
19449 	bzero(&ird, sizeof (ird));
19450 
19451 	ird.ird_route.lp_head = mpctl->b_cont;
19452 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19453 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19454 
19455 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19456 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19457 
19458 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19459 	optp->level = MIB2_IP6;
19460 	optp->name = MIB2_IP6_ROUTE;
19461 	optp->len = msgdsize(ird.ird_route.lp_head);
19462 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19463 	    (int)optp->level, (int)optp->name, (int)optp->len));
19464 	qreply(q, mpctl);
19465 
19466 	/* ipv6NetToMediaEntryTable in mp3ctl */
19467 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19468 
19469 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19470 	optp->level = MIB2_IP6;
19471 	optp->name = MIB2_IP6_MEDIA;
19472 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19473 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19474 	    (int)optp->level, (int)optp->name, (int)optp->len));
19475 	qreply(q, mp3ctl);
19476 
19477 	/* ipv6RouteAttributeTable in mp4ctl */
19478 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19479 	optp->level = MIB2_IP6;
19480 	optp->name = EXPER_IP_RTATTR;
19481 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19482 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19483 	    (int)optp->level, (int)optp->name, (int)optp->len));
19484 	if (optp->len == 0)
19485 		freemsg(mp4ctl);
19486 	else
19487 		qreply(q, mp4ctl);
19488 
19489 	return (mp2ctl);
19490 }
19491 
19492 /*
19493  * IPv6 mib: One per ill
19494  */
19495 static mblk_t *
19496 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19497 {
19498 	struct opthdr		*optp;
19499 	mblk_t			*mp2ctl;
19500 	ill_t			*ill;
19501 	ill_walk_context_t	ctx;
19502 	mblk_t			*mp_tail = NULL;
19503 
19504 	/*
19505 	 * Make a copy of the original message
19506 	 */
19507 	mp2ctl = copymsg(mpctl);
19508 
19509 	/* fixed length IPv6 structure ... */
19510 
19511 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19512 	optp->level = MIB2_IP6;
19513 	optp->name = 0;
19514 	/* Include "unknown interface" ip6_mib */
19515 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19516 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19517 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19518 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19519 	    ipst->ips_ipv6_forward ? 1 : 2);
19520 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19521 	    ipst->ips_ipv6_def_hops);
19522 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19523 	    sizeof (mib2_ipIfStatsEntry_t));
19524 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19525 	    sizeof (mib2_ipv6AddrEntry_t));
19526 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19527 	    sizeof (mib2_ipv6RouteEntry_t));
19528 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19529 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19530 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19531 	    sizeof (ipv6_member_t));
19532 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19533 	    sizeof (ipv6_grpsrc_t));
19534 
19535 	/*
19536 	 * Synchronize 64- and 32-bit counters
19537 	 */
19538 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19539 	    ipIfStatsHCInReceives);
19540 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19541 	    ipIfStatsHCInDelivers);
19542 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19543 	    ipIfStatsHCOutRequests);
19544 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19545 	    ipIfStatsHCOutForwDatagrams);
19546 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19547 	    ipIfStatsHCOutMcastPkts);
19548 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19549 	    ipIfStatsHCInMcastPkts);
19550 
19551 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19552 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19553 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19554 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19555 	}
19556 
19557 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19558 	ill = ILL_START_WALK_V6(&ctx, ipst);
19559 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19560 		ill->ill_ip_mib->ipIfStatsIfIndex =
19561 		    ill->ill_phyint->phyint_ifindex;
19562 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19563 		    ipst->ips_ipv6_forward ? 1 : 2);
19564 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19565 		    ill->ill_max_hops);
19566 
19567 		/*
19568 		 * Synchronize 64- and 32-bit counters
19569 		 */
19570 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19571 		    ipIfStatsHCInReceives);
19572 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19573 		    ipIfStatsHCInDelivers);
19574 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19575 		    ipIfStatsHCOutRequests);
19576 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19577 		    ipIfStatsHCOutForwDatagrams);
19578 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19579 		    ipIfStatsHCOutMcastPkts);
19580 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19581 		    ipIfStatsHCInMcastPkts);
19582 
19583 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19584 		    (char *)ill->ill_ip_mib,
19585 		    (int)sizeof (*ill->ill_ip_mib))) {
19586 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19587 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19588 		}
19589 	}
19590 	rw_exit(&ipst->ips_ill_g_lock);
19591 
19592 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19593 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19594 	    (int)optp->level, (int)optp->name, (int)optp->len));
19595 	qreply(q, mpctl);
19596 	return (mp2ctl);
19597 }
19598 
19599 /*
19600  * ICMPv6 mib: One per ill
19601  */
19602 static mblk_t *
19603 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19604 {
19605 	struct opthdr		*optp;
19606 	mblk_t			*mp2ctl;
19607 	ill_t			*ill;
19608 	ill_walk_context_t	ctx;
19609 	mblk_t			*mp_tail = NULL;
19610 	/*
19611 	 * Make a copy of the original message
19612 	 */
19613 	mp2ctl = copymsg(mpctl);
19614 
19615 	/* fixed length ICMPv6 structure ... */
19616 
19617 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19618 	optp->level = MIB2_ICMP6;
19619 	optp->name = 0;
19620 	/* Include "unknown interface" icmp6_mib */
19621 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19622 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19623 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19624 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19625 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19626 	    (char *)&ipst->ips_icmp6_mib,
19627 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19628 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19629 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19630 	}
19631 
19632 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19633 	ill = ILL_START_WALK_V6(&ctx, ipst);
19634 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19635 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19636 		    ill->ill_phyint->phyint_ifindex;
19637 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19638 		    (char *)ill->ill_icmp6_mib,
19639 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19640 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19641 			    "%u bytes\n",
19642 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19643 		}
19644 	}
19645 	rw_exit(&ipst->ips_ill_g_lock);
19646 
19647 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19648 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19649 	    (int)optp->level, (int)optp->name, (int)optp->len));
19650 	qreply(q, mpctl);
19651 	return (mp2ctl);
19652 }
19653 
19654 /*
19655  * ire_walk routine to create both ipRouteEntryTable and
19656  * ipRouteAttributeTable in one IRE walk
19657  */
19658 static void
19659 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19660 {
19661 	ill_t				*ill;
19662 	ipif_t				*ipif;
19663 	mib2_ipRouteEntry_t		*re;
19664 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19665 	ipaddr_t			gw_addr;
19666 	tsol_ire_gw_secattr_t		*attrp;
19667 	tsol_gc_t			*gc = NULL;
19668 	tsol_gcgrp_t			*gcgrp = NULL;
19669 	uint_t				sacnt = 0;
19670 	int				i;
19671 
19672 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19673 
19674 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19675 		return;
19676 
19677 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19678 		mutex_enter(&attrp->igsa_lock);
19679 		if ((gc = attrp->igsa_gc) != NULL) {
19680 			gcgrp = gc->gc_grp;
19681 			ASSERT(gcgrp != NULL);
19682 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19683 			sacnt = 1;
19684 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19685 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19686 			gc = gcgrp->gcgrp_head;
19687 			sacnt = gcgrp->gcgrp_count;
19688 		}
19689 		mutex_exit(&attrp->igsa_lock);
19690 
19691 		/* do nothing if there's no gc to report */
19692 		if (gc == NULL) {
19693 			ASSERT(sacnt == 0);
19694 			if (gcgrp != NULL) {
19695 				/* we might as well drop the lock now */
19696 				rw_exit(&gcgrp->gcgrp_rwlock);
19697 				gcgrp = NULL;
19698 			}
19699 			attrp = NULL;
19700 		}
19701 
19702 		ASSERT(gc == NULL || (gcgrp != NULL &&
19703 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19704 	}
19705 	ASSERT(sacnt == 0 || gc != NULL);
19706 
19707 	if (sacnt != 0 &&
19708 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19709 		kmem_free(re, sizeof (*re));
19710 		rw_exit(&gcgrp->gcgrp_rwlock);
19711 		return;
19712 	}
19713 
19714 	/*
19715 	 * Return all IRE types for route table... let caller pick and choose
19716 	 */
19717 	re->ipRouteDest = ire->ire_addr;
19718 	ipif = ire->ire_ipif;
19719 	re->ipRouteIfIndex.o_length = 0;
19720 	if (ire->ire_type == IRE_CACHE) {
19721 		ill = (ill_t *)ire->ire_stq->q_ptr;
19722 		re->ipRouteIfIndex.o_length =
19723 		    ill->ill_name_length == 0 ? 0 :
19724 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19725 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19726 		    re->ipRouteIfIndex.o_length);
19727 	} else if (ipif != NULL) {
19728 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19729 		re->ipRouteIfIndex.o_length =
19730 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19731 	}
19732 	re->ipRouteMetric1 = -1;
19733 	re->ipRouteMetric2 = -1;
19734 	re->ipRouteMetric3 = -1;
19735 	re->ipRouteMetric4 = -1;
19736 
19737 	gw_addr = ire->ire_gateway_addr;
19738 
19739 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19740 		re->ipRouteNextHop = ire->ire_src_addr;
19741 	else
19742 		re->ipRouteNextHop = gw_addr;
19743 	/* indirect(4), direct(3), or invalid(2) */
19744 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19745 		re->ipRouteType = 2;
19746 	else
19747 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19748 	re->ipRouteProto = -1;
19749 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19750 	re->ipRouteMask = ire->ire_mask;
19751 	re->ipRouteMetric5 = -1;
19752 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19753 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19754 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19755 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19756 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19757 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19758 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19759 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19760 
19761 	if (ire->ire_flags & RTF_DYNAMIC) {
19762 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19763 	} else {
19764 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19765 	}
19766 
19767 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19768 	    (char *)re, (int)sizeof (*re))) {
19769 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19770 		    (uint_t)sizeof (*re)));
19771 	}
19772 
19773 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19774 		iaeptr->iae_routeidx = ird->ird_idx;
19775 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19776 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19777 	}
19778 
19779 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19780 	    (char *)iae, sacnt * sizeof (*iae))) {
19781 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19782 		    (unsigned)(sacnt * sizeof (*iae))));
19783 	}
19784 
19785 	/* bump route index for next pass */
19786 	ird->ird_idx++;
19787 
19788 	kmem_free(re, sizeof (*re));
19789 	if (sacnt != 0)
19790 		kmem_free(iae, sacnt * sizeof (*iae));
19791 
19792 	if (gcgrp != NULL)
19793 		rw_exit(&gcgrp->gcgrp_rwlock);
19794 }
19795 
19796 /*
19797  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19798  */
19799 static void
19800 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19801 {
19802 	ill_t				*ill;
19803 	ipif_t				*ipif;
19804 	mib2_ipv6RouteEntry_t		*re;
19805 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19806 	in6_addr_t			gw_addr_v6;
19807 	tsol_ire_gw_secattr_t		*attrp;
19808 	tsol_gc_t			*gc = NULL;
19809 	tsol_gcgrp_t			*gcgrp = NULL;
19810 	uint_t				sacnt = 0;
19811 	int				i;
19812 
19813 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19814 
19815 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19816 		return;
19817 
19818 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19819 		mutex_enter(&attrp->igsa_lock);
19820 		if ((gc = attrp->igsa_gc) != NULL) {
19821 			gcgrp = gc->gc_grp;
19822 			ASSERT(gcgrp != NULL);
19823 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19824 			sacnt = 1;
19825 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19826 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19827 			gc = gcgrp->gcgrp_head;
19828 			sacnt = gcgrp->gcgrp_count;
19829 		}
19830 		mutex_exit(&attrp->igsa_lock);
19831 
19832 		/* do nothing if there's no gc to report */
19833 		if (gc == NULL) {
19834 			ASSERT(sacnt == 0);
19835 			if (gcgrp != NULL) {
19836 				/* we might as well drop the lock now */
19837 				rw_exit(&gcgrp->gcgrp_rwlock);
19838 				gcgrp = NULL;
19839 			}
19840 			attrp = NULL;
19841 		}
19842 
19843 		ASSERT(gc == NULL || (gcgrp != NULL &&
19844 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19845 	}
19846 	ASSERT(sacnt == 0 || gc != NULL);
19847 
19848 	if (sacnt != 0 &&
19849 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19850 		kmem_free(re, sizeof (*re));
19851 		rw_exit(&gcgrp->gcgrp_rwlock);
19852 		return;
19853 	}
19854 
19855 	/*
19856 	 * Return all IRE types for route table... let caller pick and choose
19857 	 */
19858 	re->ipv6RouteDest = ire->ire_addr_v6;
19859 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19860 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19861 	re->ipv6RouteIfIndex.o_length = 0;
19862 	ipif = ire->ire_ipif;
19863 	if (ire->ire_type == IRE_CACHE) {
19864 		ill = (ill_t *)ire->ire_stq->q_ptr;
19865 		re->ipv6RouteIfIndex.o_length =
19866 		    ill->ill_name_length == 0 ? 0 :
19867 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19868 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19869 		    re->ipv6RouteIfIndex.o_length);
19870 	} else if (ipif != NULL) {
19871 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19872 		re->ipv6RouteIfIndex.o_length =
19873 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19874 	}
19875 
19876 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19877 
19878 	mutex_enter(&ire->ire_lock);
19879 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19880 	mutex_exit(&ire->ire_lock);
19881 
19882 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19883 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19884 	else
19885 		re->ipv6RouteNextHop = gw_addr_v6;
19886 
19887 	/* remote(4), local(3), or discard(2) */
19888 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19889 		re->ipv6RouteType = 2;
19890 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19891 		re->ipv6RouteType = 3;
19892 	else
19893 		re->ipv6RouteType = 4;
19894 
19895 	re->ipv6RouteProtocol	= -1;
19896 	re->ipv6RoutePolicy	= 0;
19897 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19898 	re->ipv6RouteNextHopRDI	= 0;
19899 	re->ipv6RouteWeight	= 0;
19900 	re->ipv6RouteMetric	= 0;
19901 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19902 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19903 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19904 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19905 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19906 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19907 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19908 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19909 
19910 	if (ire->ire_flags & RTF_DYNAMIC) {
19911 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19912 	} else {
19913 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19914 	}
19915 
19916 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19917 	    (char *)re, (int)sizeof (*re))) {
19918 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19919 		    (uint_t)sizeof (*re)));
19920 	}
19921 
19922 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19923 		iaeptr->iae_routeidx = ird->ird_idx;
19924 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19925 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19926 	}
19927 
19928 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19929 	    (char *)iae, sacnt * sizeof (*iae))) {
19930 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19931 		    (unsigned)(sacnt * sizeof (*iae))));
19932 	}
19933 
19934 	/* bump route index for next pass */
19935 	ird->ird_idx++;
19936 
19937 	kmem_free(re, sizeof (*re));
19938 	if (sacnt != 0)
19939 		kmem_free(iae, sacnt * sizeof (*iae));
19940 
19941 	if (gcgrp != NULL)
19942 		rw_exit(&gcgrp->gcgrp_rwlock);
19943 }
19944 
19945 /*
19946  * ndp_walk routine to create ipv6NetToMediaEntryTable
19947  */
19948 static int
19949 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19950 {
19951 	ill_t				*ill;
19952 	mib2_ipv6NetToMediaEntry_t	ntme;
19953 	dl_unitdata_req_t		*dl;
19954 
19955 	ill = nce->nce_ill;
19956 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19957 		return (0);
19958 
19959 	/*
19960 	 * Neighbor cache entry attached to IRE with on-link
19961 	 * destination.
19962 	 */
19963 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19964 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19965 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19966 	    (nce->nce_res_mp != NULL)) {
19967 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19968 		ntme.ipv6NetToMediaPhysAddress.o_length =
19969 		    dl->dl_dest_addr_length;
19970 	} else {
19971 		ntme.ipv6NetToMediaPhysAddress.o_length =
19972 		    ill->ill_phys_addr_length;
19973 	}
19974 	if (nce->nce_res_mp != NULL) {
19975 		bcopy((char *)nce->nce_res_mp->b_rptr +
19976 		    NCE_LL_ADDR_OFFSET(ill),
19977 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19978 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19979 	} else {
19980 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19981 		    ill->ill_phys_addr_length);
19982 	}
19983 	/*
19984 	 * Note: Returns ND_* states. Should be:
19985 	 * reachable(1), stale(2), delay(3), probe(4),
19986 	 * invalid(5), unknown(6)
19987 	 */
19988 	ntme.ipv6NetToMediaState = nce->nce_state;
19989 	ntme.ipv6NetToMediaLastUpdated = 0;
19990 
19991 	/* other(1), dynamic(2), static(3), local(4) */
19992 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19993 		ntme.ipv6NetToMediaType = 4;
19994 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19995 		ntme.ipv6NetToMediaType = 1;
19996 	} else {
19997 		ntme.ipv6NetToMediaType = 2;
19998 	}
19999 
20000 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
20001 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
20002 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
20003 		    (uint_t)sizeof (ntme)));
20004 	}
20005 	return (0);
20006 }
20007 
20008 /*
20009  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
20010  */
20011 /* ARGSUSED */
20012 int
20013 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
20014 {
20015 	switch (level) {
20016 	case MIB2_IP:
20017 	case MIB2_ICMP:
20018 		switch (name) {
20019 		default:
20020 			break;
20021 		}
20022 		return (1);
20023 	default:
20024 		return (1);
20025 	}
20026 }
20027 
20028 /*
20029  * When there exists both a 64- and 32-bit counter of a particular type
20030  * (i.e., InReceives), only the 64-bit counters are added.
20031  */
20032 void
20033 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
20034 {
20035 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
20036 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
20037 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
20038 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
20039 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
20040 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
20041 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
20042 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
20043 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
20044 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
20045 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
20046 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
20047 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
20048 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
20049 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
20050 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
20051 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
20052 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
20053 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
20054 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
20055 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
20056 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
20057 	    o2->ipIfStatsInWrongIPVersion);
20058 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
20059 	    o2->ipIfStatsInWrongIPVersion);
20060 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
20061 	    o2->ipIfStatsOutSwitchIPVersion);
20062 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
20063 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
20064 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
20065 	    o2->ipIfStatsHCInForwDatagrams);
20066 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
20067 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
20068 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
20069 	    o2->ipIfStatsHCOutForwDatagrams);
20070 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
20071 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
20072 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
20073 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
20074 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
20075 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
20076 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
20077 	    o2->ipIfStatsHCOutMcastOctets);
20078 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
20079 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
20080 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
20081 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
20082 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
20083 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
20084 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
20085 }
20086 
20087 void
20088 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
20089 {
20090 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
20091 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
20092 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
20093 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
20094 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
20095 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
20096 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
20097 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
20098 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
20099 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
20100 	    o2->ipv6IfIcmpInRouterSolicits);
20101 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
20102 	    o2->ipv6IfIcmpInRouterAdvertisements);
20103 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
20104 	    o2->ipv6IfIcmpInNeighborSolicits);
20105 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
20106 	    o2->ipv6IfIcmpInNeighborAdvertisements);
20107 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
20108 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
20109 	    o2->ipv6IfIcmpInGroupMembQueries);
20110 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
20111 	    o2->ipv6IfIcmpInGroupMembResponses);
20112 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
20113 	    o2->ipv6IfIcmpInGroupMembReductions);
20114 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
20115 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
20116 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
20117 	    o2->ipv6IfIcmpOutDestUnreachs);
20118 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
20119 	    o2->ipv6IfIcmpOutAdminProhibs);
20120 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
20121 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
20122 	    o2->ipv6IfIcmpOutParmProblems);
20123 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
20124 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
20125 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
20126 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
20127 	    o2->ipv6IfIcmpOutRouterSolicits);
20128 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
20129 	    o2->ipv6IfIcmpOutRouterAdvertisements);
20130 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
20131 	    o2->ipv6IfIcmpOutNeighborSolicits);
20132 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
20133 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
20134 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
20135 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
20136 	    o2->ipv6IfIcmpOutGroupMembQueries);
20137 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
20138 	    o2->ipv6IfIcmpOutGroupMembResponses);
20139 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
20140 	    o2->ipv6IfIcmpOutGroupMembReductions);
20141 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
20142 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
20143 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
20144 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
20145 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
20146 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
20147 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
20148 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
20149 	    o2->ipv6IfIcmpInGroupMembTotal);
20150 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
20151 	    o2->ipv6IfIcmpInGroupMembBadQueries);
20152 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
20153 	    o2->ipv6IfIcmpInGroupMembBadReports);
20154 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
20155 	    o2->ipv6IfIcmpInGroupMembOurReports);
20156 }
20157 
20158 /*
20159  * Called before the options are updated to check if this packet will
20160  * be source routed from here.
20161  * This routine assumes that the options are well formed i.e. that they
20162  * have already been checked.
20163  */
20164 static boolean_t
20165 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
20166 {
20167 	ipoptp_t	opts;
20168 	uchar_t		*opt;
20169 	uint8_t		optval;
20170 	uint8_t		optlen;
20171 	ipaddr_t	dst;
20172 	ire_t		*ire;
20173 
20174 	if (IS_SIMPLE_IPH(ipha)) {
20175 		ip2dbg(("not source routed\n"));
20176 		return (B_FALSE);
20177 	}
20178 	dst = ipha->ipha_dst;
20179 	for (optval = ipoptp_first(&opts, ipha);
20180 	    optval != IPOPT_EOL;
20181 	    optval = ipoptp_next(&opts)) {
20182 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
20183 		opt = opts.ipoptp_cur;
20184 		optlen = opts.ipoptp_len;
20185 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
20186 		    optval, optlen));
20187 		switch (optval) {
20188 			uint32_t off;
20189 		case IPOPT_SSRR:
20190 		case IPOPT_LSRR:
20191 			/*
20192 			 * If dst is one of our addresses and there are some
20193 			 * entries left in the source route return (true).
20194 			 */
20195 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
20196 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
20197 			if (ire == NULL) {
20198 				ip2dbg(("ip_source_routed: not next"
20199 				    " source route 0x%x\n",
20200 				    ntohl(dst)));
20201 				return (B_FALSE);
20202 			}
20203 			ire_refrele(ire);
20204 			off = opt[IPOPT_OFFSET];
20205 			off--;
20206 			if (optlen < IP_ADDR_LEN ||
20207 			    off > optlen - IP_ADDR_LEN) {
20208 				/* End of source route */
20209 				ip1dbg(("ip_source_routed: end of SR\n"));
20210 				return (B_FALSE);
20211 			}
20212 			return (B_TRUE);
20213 		}
20214 	}
20215 	ip2dbg(("not source routed\n"));
20216 	return (B_FALSE);
20217 }
20218 
20219 /*
20220  * Check if the packet contains any source route.
20221  */
20222 static boolean_t
20223 ip_source_route_included(ipha_t *ipha)
20224 {
20225 	ipoptp_t	opts;
20226 	uint8_t		optval;
20227 
20228 	if (IS_SIMPLE_IPH(ipha))
20229 		return (B_FALSE);
20230 	for (optval = ipoptp_first(&opts, ipha);
20231 	    optval != IPOPT_EOL;
20232 	    optval = ipoptp_next(&opts)) {
20233 		switch (optval) {
20234 		case IPOPT_SSRR:
20235 		case IPOPT_LSRR:
20236 			return (B_TRUE);
20237 		}
20238 	}
20239 	return (B_FALSE);
20240 }
20241 
20242 /*
20243  * Called when the IRE expiration timer fires.
20244  */
20245 void
20246 ip_trash_timer_expire(void *args)
20247 {
20248 	int			flush_flag = 0;
20249 	ire_expire_arg_t	iea;
20250 	ip_stack_t		*ipst = (ip_stack_t *)args;
20251 
20252 	iea.iea_ipst = ipst;	/* No netstack_hold */
20253 
20254 	/*
20255 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
20256 	 * This lock makes sure that a new invocation of this function
20257 	 * that occurs due to an almost immediate timer firing will not
20258 	 * progress beyond this point until the current invocation is done
20259 	 */
20260 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20261 	ipst->ips_ip_ire_expire_id = 0;
20262 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20263 
20264 	/* Periodic timer */
20265 	if (ipst->ips_ip_ire_arp_time_elapsed >=
20266 	    ipst->ips_ip_ire_arp_interval) {
20267 		/*
20268 		 * Remove all IRE_CACHE entries since they might
20269 		 * contain arp information.
20270 		 */
20271 		flush_flag |= FLUSH_ARP_TIME;
20272 		ipst->ips_ip_ire_arp_time_elapsed = 0;
20273 		IP_STAT(ipst, ip_ire_arp_timer_expired);
20274 	}
20275 	if (ipst->ips_ip_ire_rd_time_elapsed >=
20276 	    ipst->ips_ip_ire_redir_interval) {
20277 		/* Remove all redirects */
20278 		flush_flag |= FLUSH_REDIRECT_TIME;
20279 		ipst->ips_ip_ire_rd_time_elapsed = 0;
20280 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
20281 	}
20282 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
20283 	    ipst->ips_ip_ire_pathmtu_interval) {
20284 		/* Increase path mtu */
20285 		flush_flag |= FLUSH_MTU_TIME;
20286 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20287 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20288 	}
20289 
20290 	/*
20291 	 * Optimize for the case when there are no redirects in the
20292 	 * ftable, that is, no need to walk the ftable in that case.
20293 	 */
20294 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20295 		iea.iea_flush_flag = flush_flag;
20296 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20297 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20298 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20299 		    NULL, ALL_ZONES, ipst);
20300 	}
20301 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20302 	    ipst->ips_ip_redirect_cnt > 0) {
20303 		iea.iea_flush_flag = flush_flag;
20304 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20305 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20306 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20307 	}
20308 	if (flush_flag & FLUSH_MTU_TIME) {
20309 		/*
20310 		 * Walk all IPv6 IRE's and update them
20311 		 * Note that ARP and redirect timers are not
20312 		 * needed since NUD handles stale entries.
20313 		 */
20314 		flush_flag = FLUSH_MTU_TIME;
20315 		iea.iea_flush_flag = flush_flag;
20316 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20317 		    ALL_ZONES, ipst);
20318 	}
20319 
20320 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20321 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20322 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20323 
20324 	/*
20325 	 * Hold the lock to serialize timeout calls and prevent
20326 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20327 	 * for the timer to fire and a new invocation of this function
20328 	 * to start before the return value of timeout has been stored
20329 	 * in ip_ire_expire_id by the current invocation.
20330 	 */
20331 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20332 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20333 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20334 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20335 }
20336 
20337 /*
20338  * Called by the memory allocator subsystem directly, when the system
20339  * is running low on memory.
20340  */
20341 /* ARGSUSED */
20342 void
20343 ip_trash_ire_reclaim(void *args)
20344 {
20345 	netstack_handle_t nh;
20346 	netstack_t *ns;
20347 
20348 	netstack_next_init(&nh);
20349 	while ((ns = netstack_next(&nh)) != NULL) {
20350 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20351 		netstack_rele(ns);
20352 	}
20353 	netstack_next_fini(&nh);
20354 }
20355 
20356 static void
20357 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20358 {
20359 	ire_cache_count_t icc;
20360 	ire_cache_reclaim_t icr;
20361 	ncc_cache_count_t ncc;
20362 	nce_cache_reclaim_t ncr;
20363 	uint_t delete_cnt;
20364 	/*
20365 	 * Memory reclaim call back.
20366 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20367 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20368 	 * entries, determine what fraction to free for
20369 	 * each category of IRE_CACHE entries giving absolute priority
20370 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20371 	 * entry will be freed unless all offlink entries are freed).
20372 	 */
20373 	icc.icc_total = 0;
20374 	icc.icc_unused = 0;
20375 	icc.icc_offlink = 0;
20376 	icc.icc_pmtu = 0;
20377 	icc.icc_onlink = 0;
20378 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20379 
20380 	/*
20381 	 * Free NCEs for IPv6 like the onlink ires.
20382 	 */
20383 	ncc.ncc_total = 0;
20384 	ncc.ncc_host = 0;
20385 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20386 
20387 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20388 	    icc.icc_pmtu + icc.icc_onlink);
20389 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20390 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20391 	if (delete_cnt == 0)
20392 		return;
20393 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20394 	/* Always delete all unused offlink entries */
20395 	icr.icr_ipst = ipst;
20396 	icr.icr_unused = 1;
20397 	if (delete_cnt <= icc.icc_unused) {
20398 		/*
20399 		 * Only need to free unused entries.  In other words,
20400 		 * there are enough unused entries to free to meet our
20401 		 * target number of freed ire cache entries.
20402 		 */
20403 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20404 		ncr.ncr_host = 0;
20405 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20406 		/*
20407 		 * Only need to free unused entries, plus a fraction of offlink
20408 		 * entries.  It follows from the first if statement that
20409 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20410 		 */
20411 		delete_cnt -= icc.icc_unused;
20412 		/* Round up # deleted by truncating fraction */
20413 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20414 		icr.icr_pmtu = icr.icr_onlink = 0;
20415 		ncr.ncr_host = 0;
20416 	} else if (delete_cnt <=
20417 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20418 		/*
20419 		 * Free all unused and offlink entries, plus a fraction of
20420 		 * pmtu entries.  It follows from the previous if statement
20421 		 * that icc_pmtu is non-zero, and that
20422 		 * delete_cnt != icc_unused + icc_offlink.
20423 		 */
20424 		icr.icr_offlink = 1;
20425 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20426 		/* Round up # deleted by truncating fraction */
20427 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20428 		icr.icr_onlink = 0;
20429 		ncr.ncr_host = 0;
20430 	} else {
20431 		/*
20432 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20433 		 * of onlink entries.  If we're here, then we know that
20434 		 * icc_onlink is non-zero, and that
20435 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20436 		 */
20437 		icr.icr_offlink = icr.icr_pmtu = 1;
20438 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20439 		    icc.icc_pmtu;
20440 		/* Round up # deleted by truncating fraction */
20441 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20442 		/* Using the same delete fraction as for onlink IREs */
20443 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20444 	}
20445 #ifdef DEBUG
20446 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20447 	    "fractions %d/%d/%d/%d\n",
20448 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20449 	    icc.icc_unused, icc.icc_offlink,
20450 	    icc.icc_pmtu, icc.icc_onlink,
20451 	    icr.icr_unused, icr.icr_offlink,
20452 	    icr.icr_pmtu, icr.icr_onlink));
20453 #endif
20454 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20455 	if (ncr.ncr_host != 0)
20456 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20457 		    (uchar_t *)&ncr, ipst);
20458 #ifdef DEBUG
20459 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20460 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20461 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20462 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20463 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20464 	    icc.icc_pmtu, icc.icc_onlink));
20465 #endif
20466 }
20467 
20468 /*
20469  * ip_unbind is called when a copy of an unbind request is received from the
20470  * upper level protocol.  We remove this conn from any fanout hash list it is
20471  * on, and zero out the bind information.  No reply is expected up above.
20472  */
20473 void
20474 ip_unbind(conn_t *connp)
20475 {
20476 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20477 
20478 	if (is_system_labeled() && connp->conn_anon_port) {
20479 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20480 		    connp->conn_mlp_type, connp->conn_ulp,
20481 		    ntohs(connp->conn_lport), B_FALSE);
20482 		connp->conn_anon_port = 0;
20483 	}
20484 	connp->conn_mlp_type = mlptSingle;
20485 
20486 	ipcl_hash_remove(connp);
20487 
20488 }
20489 
20490 /*
20491  * Write side put procedure.  Outbound data, IOCTLs, responses from
20492  * resolvers, etc, come down through here.
20493  *
20494  * arg2 is always a queue_t *.
20495  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20496  * the zoneid.
20497  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20498  */
20499 void
20500 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20501 {
20502 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20503 }
20504 
20505 void
20506 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20507     ip_opt_info_t *infop)
20508 {
20509 	conn_t		*connp = NULL;
20510 	queue_t		*q = (queue_t *)arg2;
20511 	ipha_t		*ipha;
20512 #define	rptr	((uchar_t *)ipha)
20513 	ire_t		*ire = NULL;
20514 	ire_t		*sctp_ire = NULL;
20515 	uint32_t	v_hlen_tos_len;
20516 	ipaddr_t	dst;
20517 	mblk_t		*first_mp = NULL;
20518 	boolean_t	mctl_present;
20519 	ipsec_out_t	*io;
20520 	int		match_flags;
20521 	ill_t		*attach_ill = NULL;
20522 					/* Bind to IPIF_NOFAILOVER ill etc. */
20523 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20524 	ipif_t		*dst_ipif;
20525 	boolean_t	multirt_need_resolve = B_FALSE;
20526 	mblk_t		*copy_mp = NULL;
20527 	int		err;
20528 	zoneid_t	zoneid;
20529 	boolean_t	need_decref = B_FALSE;
20530 	boolean_t	ignore_dontroute = B_FALSE;
20531 	boolean_t	ignore_nexthop = B_FALSE;
20532 	boolean_t	ip_nexthop = B_FALSE;
20533 	ipaddr_t	nexthop_addr;
20534 	ip_stack_t	*ipst;
20535 
20536 #ifdef	_BIG_ENDIAN
20537 #define	V_HLEN	(v_hlen_tos_len >> 24)
20538 #else
20539 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20540 #endif
20541 
20542 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20543 	    "ip_wput_start: q %p", q);
20544 
20545 	/*
20546 	 * ip_wput fast path
20547 	 */
20548 
20549 	/* is packet from ARP ? */
20550 	if (q->q_next != NULL) {
20551 		zoneid = (zoneid_t)(uintptr_t)arg;
20552 		goto qnext;
20553 	}
20554 
20555 	connp = (conn_t *)arg;
20556 	ASSERT(connp != NULL);
20557 	zoneid = connp->conn_zoneid;
20558 	ipst = connp->conn_netstack->netstack_ip;
20559 	ASSERT(ipst != NULL);
20560 
20561 	/* is queue flow controlled? */
20562 	if ((q->q_first != NULL || connp->conn_draining) &&
20563 	    (caller == IP_WPUT)) {
20564 		ASSERT(!need_decref);
20565 		ASSERT(!IP_FLOW_CONTROLLED_ULP(connp->conn_ulp));
20566 		(void) putq(q, mp);
20567 		return;
20568 	}
20569 
20570 	/* Multidata transmit? */
20571 	if (DB_TYPE(mp) == M_MULTIDATA) {
20572 		/*
20573 		 * We should never get here, since all Multidata messages
20574 		 * originating from tcp should have been directed over to
20575 		 * tcp_multisend() in the first place.
20576 		 */
20577 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20578 		freemsg(mp);
20579 		return;
20580 	} else if (DB_TYPE(mp) != M_DATA)
20581 		goto notdata;
20582 
20583 	if (mp->b_flag & MSGHASREF) {
20584 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20585 		mp->b_flag &= ~MSGHASREF;
20586 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20587 		need_decref = B_TRUE;
20588 	}
20589 	ipha = (ipha_t *)mp->b_rptr;
20590 
20591 	/* is IP header non-aligned or mblk smaller than basic IP header */
20592 #ifndef SAFETY_BEFORE_SPEED
20593 	if (!OK_32PTR(rptr) ||
20594 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20595 		goto hdrtoosmall;
20596 #endif
20597 
20598 	ASSERT(OK_32PTR(ipha));
20599 
20600 	/*
20601 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20602 	 * wrong version, we'll catch it again in ip_output_v6.
20603 	 *
20604 	 * Note that this is *only* locally-generated output here, and never
20605 	 * forwarded data, and that we need to deal only with transports that
20606 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20607 	 * label.)
20608 	 */
20609 	if (is_system_labeled() &&
20610 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20611 	    !connp->conn_ulp_labeled) {
20612 		err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20613 		    connp->conn_mac_exempt, ipst);
20614 		ipha = (ipha_t *)mp->b_rptr;
20615 		if (err != 0) {
20616 			first_mp = mp;
20617 			if (err == EINVAL)
20618 				goto icmp_parameter_problem;
20619 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20620 			goto discard_pkt;
20621 		}
20622 	}
20623 
20624 	ASSERT(infop != NULL);
20625 
20626 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20627 		/*
20628 		 * IP_PKTINFO ancillary option is present.
20629 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20630 		 * allows using address of any zone as the source address.
20631 		 */
20632 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20633 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20634 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20635 		if (ire == NULL)
20636 			goto drop_pkt;
20637 		ire_refrele(ire);
20638 		ire = NULL;
20639 	}
20640 
20641 	/*
20642 	 * IP_DONTFAILOVER_IF and IP_BOUND_IF have precedence over ill index
20643 	 * passed in IP_PKTINFO.
20644 	 */
20645 	if (infop->ip_opt_ill_index != 0 &&
20646 	    connp->conn_outgoing_ill == NULL &&
20647 	    connp->conn_nofailover_ill == NULL) {
20648 
20649 		xmit_ill = ill_lookup_on_ifindex(
20650 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20651 		    ipst);
20652 
20653 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20654 			goto drop_pkt;
20655 		/*
20656 		 * check that there is an ipif belonging
20657 		 * to our zone. IPCL_ZONEID is not used because
20658 		 * IP_ALLZONES option is valid only when the ill is
20659 		 * accessible from all zones i.e has a valid ipif in
20660 		 * all zones.
20661 		 */
20662 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20663 			goto drop_pkt;
20664 		}
20665 	}
20666 
20667 	/*
20668 	 * If there is a policy, try to attach an ipsec_out in
20669 	 * the front. At the end, first_mp either points to a
20670 	 * M_DATA message or IPSEC_OUT message linked to a
20671 	 * M_DATA message. We have to do it now as we might
20672 	 * lose the "conn" if we go through ip_newroute.
20673 	 */
20674 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20675 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20676 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20677 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20678 			if (need_decref)
20679 				CONN_DEC_REF(connp);
20680 			return;
20681 		} else {
20682 			ASSERT(mp->b_datap->db_type == M_CTL);
20683 			first_mp = mp;
20684 			mp = mp->b_cont;
20685 			mctl_present = B_TRUE;
20686 		}
20687 	} else {
20688 		first_mp = mp;
20689 		mctl_present = B_FALSE;
20690 	}
20691 
20692 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20693 
20694 	/* is wrong version or IP options present */
20695 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20696 		goto version_hdrlen_check;
20697 	dst = ipha->ipha_dst;
20698 
20699 	if (connp->conn_nofailover_ill != NULL) {
20700 		attach_ill = conn_get_held_ill(connp,
20701 		    &connp->conn_nofailover_ill, &err);
20702 		if (err == ILL_LOOKUP_FAILED) {
20703 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20704 			if (need_decref)
20705 				CONN_DEC_REF(connp);
20706 			freemsg(first_mp);
20707 			return;
20708 		}
20709 	}
20710 
20711 	/* If IP_BOUND_IF has been set, use that ill. */
20712 	if (connp->conn_outgoing_ill != NULL) {
20713 		xmit_ill = conn_get_held_ill(connp,
20714 		    &connp->conn_outgoing_ill, &err);
20715 		if (err == ILL_LOOKUP_FAILED)
20716 			goto drop_pkt;
20717 
20718 		goto send_from_ill;
20719 	}
20720 
20721 	/* is packet multicast? */
20722 	if (CLASSD(dst))
20723 		goto multicast;
20724 
20725 	/*
20726 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20727 	 * takes precedence over conn_dontroute and conn_nexthop_set
20728 	 */
20729 	if (xmit_ill != NULL)
20730 		goto send_from_ill;
20731 
20732 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20733 		/*
20734 		 * If the destination is a broadcast, local, or loopback
20735 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20736 		 * standard path.
20737 		 */
20738 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20739 		if ((ire == NULL) || (ire->ire_type &
20740 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20741 			if (ire != NULL) {
20742 				ire_refrele(ire);
20743 				/* No more access to ire */
20744 				ire = NULL;
20745 			}
20746 			/*
20747 			 * bypass routing checks and go directly to interface.
20748 			 */
20749 			if (connp->conn_dontroute)
20750 				goto dontroute;
20751 
20752 			ASSERT(connp->conn_nexthop_set);
20753 			ip_nexthop = B_TRUE;
20754 			nexthop_addr = connp->conn_nexthop_v4;
20755 			goto send_from_ill;
20756 		}
20757 
20758 		/* Must be a broadcast, a loopback or a local ire */
20759 		ire_refrele(ire);
20760 		/* No more access to ire */
20761 		ire = NULL;
20762 	}
20763 
20764 	if (attach_ill != NULL)
20765 		goto send_from_ill;
20766 
20767 	/*
20768 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20769 	 * this for the tcp global queue and listen end point
20770 	 * as it does not really have a real destination to
20771 	 * talk to.  This is also true for SCTP.
20772 	 */
20773 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20774 	    !connp->conn_fully_bound) {
20775 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20776 		if (ire == NULL)
20777 			goto noirefound;
20778 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20779 		    "ip_wput_end: q %p (%S)", q, "end");
20780 
20781 		/*
20782 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20783 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20784 		 */
20785 		if (ire->ire_flags & RTF_MULTIRT) {
20786 
20787 			/*
20788 			 * Force the TTL of multirouted packets if required.
20789 			 * The TTL of such packets is bounded by the
20790 			 * ip_multirt_ttl ndd variable.
20791 			 */
20792 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20793 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20794 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20795 				    "(was %d), dst 0x%08x\n",
20796 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20797 				    ntohl(ire->ire_addr)));
20798 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20799 			}
20800 			/*
20801 			 * We look at this point if there are pending
20802 			 * unresolved routes. ire_multirt_resolvable()
20803 			 * checks in O(n) that all IRE_OFFSUBNET ire
20804 			 * entries for the packet's destination and
20805 			 * flagged RTF_MULTIRT are currently resolved.
20806 			 * If some remain unresolved, we make a copy
20807 			 * of the current message. It will be used
20808 			 * to initiate additional route resolutions.
20809 			 */
20810 			multirt_need_resolve =
20811 			    ire_multirt_need_resolve(ire->ire_addr,
20812 			    MBLK_GETLABEL(first_mp), ipst);
20813 			ip2dbg(("ip_wput[TCP]: ire %p, "
20814 			    "multirt_need_resolve %d, first_mp %p\n",
20815 			    (void *)ire, multirt_need_resolve,
20816 			    (void *)first_mp));
20817 			if (multirt_need_resolve) {
20818 				copy_mp = copymsg(first_mp);
20819 				if (copy_mp != NULL) {
20820 					MULTIRT_DEBUG_TAG(copy_mp);
20821 				}
20822 			}
20823 		}
20824 
20825 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20826 
20827 		/*
20828 		 * Try to resolve another multiroute if
20829 		 * ire_multirt_need_resolve() deemed it necessary.
20830 		 */
20831 		if (copy_mp != NULL)
20832 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20833 		if (need_decref)
20834 			CONN_DEC_REF(connp);
20835 		return;
20836 	}
20837 
20838 	/*
20839 	 * Access to conn_ire_cache. (protected by conn_lock)
20840 	 *
20841 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20842 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20843 	 * send a packet or two with the IRE_CACHE that is going away.
20844 	 * Access to the ire requires an ire refhold on the ire prior to
20845 	 * its use since an interface unplumb thread may delete the cached
20846 	 * ire and release the refhold at any time.
20847 	 *
20848 	 * Caching an ire in the conn_ire_cache
20849 	 *
20850 	 * o Caching an ire pointer in the conn requires a strict check for
20851 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20852 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20853 	 * in the conn is done after making sure under the bucket lock that the
20854 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20855 	 * caching an ire after the unplumb thread has cleaned up the conn.
20856 	 * If the conn does not send a packet subsequently the unplumb thread
20857 	 * will be hanging waiting for the ire count to drop to zero.
20858 	 *
20859 	 * o We also need to atomically test for a null conn_ire_cache and
20860 	 * set the conn_ire_cache under the the protection of the conn_lock
20861 	 * to avoid races among concurrent threads trying to simultaneously
20862 	 * cache an ire in the conn_ire_cache.
20863 	 */
20864 	mutex_enter(&connp->conn_lock);
20865 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20866 
20867 	if (ire != NULL && ire->ire_addr == dst &&
20868 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20869 
20870 		IRE_REFHOLD(ire);
20871 		mutex_exit(&connp->conn_lock);
20872 
20873 	} else {
20874 		boolean_t cached = B_FALSE;
20875 		connp->conn_ire_cache = NULL;
20876 		mutex_exit(&connp->conn_lock);
20877 		/* Release the old ire */
20878 		if (ire != NULL && sctp_ire == NULL)
20879 			IRE_REFRELE_NOTR(ire);
20880 
20881 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20882 		if (ire == NULL)
20883 			goto noirefound;
20884 		IRE_REFHOLD_NOTR(ire);
20885 
20886 		mutex_enter(&connp->conn_lock);
20887 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20888 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20889 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20890 				if (connp->conn_ulp == IPPROTO_TCP)
20891 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20892 				connp->conn_ire_cache = ire;
20893 				cached = B_TRUE;
20894 			}
20895 			rw_exit(&ire->ire_bucket->irb_lock);
20896 		}
20897 		mutex_exit(&connp->conn_lock);
20898 
20899 		/*
20900 		 * We can continue to use the ire but since it was
20901 		 * not cached, we should drop the extra reference.
20902 		 */
20903 		if (!cached)
20904 			IRE_REFRELE_NOTR(ire);
20905 	}
20906 
20907 
20908 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20909 	    "ip_wput_end: q %p (%S)", q, "end");
20910 
20911 	/*
20912 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20913 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20914 	 */
20915 	if (ire->ire_flags & RTF_MULTIRT) {
20916 
20917 		/*
20918 		 * Force the TTL of multirouted packets if required.
20919 		 * The TTL of such packets is bounded by the
20920 		 * ip_multirt_ttl ndd variable.
20921 		 */
20922 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20923 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20924 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20925 			    "(was %d), dst 0x%08x\n",
20926 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20927 			    ntohl(ire->ire_addr)));
20928 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20929 		}
20930 
20931 		/*
20932 		 * At this point, we check to see if there are any pending
20933 		 * unresolved routes. ire_multirt_resolvable()
20934 		 * checks in O(n) that all IRE_OFFSUBNET ire
20935 		 * entries for the packet's destination and
20936 		 * flagged RTF_MULTIRT are currently resolved.
20937 		 * If some remain unresolved, we make a copy
20938 		 * of the current message. It will be used
20939 		 * to initiate additional route resolutions.
20940 		 */
20941 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20942 		    MBLK_GETLABEL(first_mp), ipst);
20943 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20944 		    "multirt_need_resolve %d, first_mp %p\n",
20945 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20946 		if (multirt_need_resolve) {
20947 			copy_mp = copymsg(first_mp);
20948 			if (copy_mp != NULL) {
20949 				MULTIRT_DEBUG_TAG(copy_mp);
20950 			}
20951 		}
20952 	}
20953 
20954 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20955 
20956 	/*
20957 	 * Try to resolve another multiroute if
20958 	 * ire_multirt_resolvable() deemed it necessary
20959 	 */
20960 	if (copy_mp != NULL)
20961 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20962 	if (need_decref)
20963 		CONN_DEC_REF(connp);
20964 	return;
20965 
20966 qnext:
20967 	/*
20968 	 * Upper Level Protocols pass down complete IP datagrams
20969 	 * as M_DATA messages.	Everything else is a sideshow.
20970 	 *
20971 	 * 1) We could be re-entering ip_wput because of ip_neworute
20972 	 *    in which case we could have a IPSEC_OUT message. We
20973 	 *    need to pass through ip_wput like other datagrams and
20974 	 *    hence cannot branch to ip_wput_nondata.
20975 	 *
20976 	 * 2) ARP, AH, ESP, and other clients who are on the module
20977 	 *    instance of IP stream, give us something to deal with.
20978 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20979 	 *
20980 	 * 3) ICMP replies also could come here.
20981 	 */
20982 	ipst = ILLQ_TO_IPST(q);
20983 
20984 	if (DB_TYPE(mp) != M_DATA) {
20985 notdata:
20986 		if (DB_TYPE(mp) == M_CTL) {
20987 			/*
20988 			 * M_CTL messages are used by ARP, AH and ESP to
20989 			 * communicate with IP. We deal with IPSEC_IN and
20990 			 * IPSEC_OUT here. ip_wput_nondata handles other
20991 			 * cases.
20992 			 */
20993 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20994 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20995 				first_mp = mp->b_cont;
20996 				first_mp->b_flag &= ~MSGHASREF;
20997 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20998 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20999 				CONN_DEC_REF(connp);
21000 				connp = NULL;
21001 			}
21002 			if (ii->ipsec_info_type == IPSEC_IN) {
21003 				/*
21004 				 * Either this message goes back to
21005 				 * IPsec for further processing or to
21006 				 * ULP after policy checks.
21007 				 */
21008 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
21009 				return;
21010 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
21011 				io = (ipsec_out_t *)ii;
21012 				if (io->ipsec_out_proc_begin) {
21013 					/*
21014 					 * IPsec processing has already started.
21015 					 * Complete it.
21016 					 * IPQoS notes: We don't care what is
21017 					 * in ipsec_out_ill_index since this
21018 					 * won't be processed for IPQoS policies
21019 					 * in ipsec_out_process.
21020 					 */
21021 					ipsec_out_process(q, mp, NULL,
21022 					    io->ipsec_out_ill_index);
21023 					return;
21024 				} else {
21025 					connp = (q->q_next != NULL) ?
21026 					    NULL : Q_TO_CONN(q);
21027 					first_mp = mp;
21028 					mp = mp->b_cont;
21029 					mctl_present = B_TRUE;
21030 				}
21031 				zoneid = io->ipsec_out_zoneid;
21032 				ASSERT(zoneid != ALL_ZONES);
21033 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
21034 				/*
21035 				 * It's an IPsec control message requesting
21036 				 * an SADB update to be sent to the IPsec
21037 				 * hardware acceleration capable ills.
21038 				 */
21039 				ipsec_ctl_t *ipsec_ctl =
21040 				    (ipsec_ctl_t *)mp->b_rptr;
21041 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
21042 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
21043 				mblk_t *cmp = mp->b_cont;
21044 
21045 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
21046 				ASSERT(cmp != NULL);
21047 
21048 				freeb(mp);
21049 				ill_ipsec_capab_send_all(satype, cmp, sa,
21050 				    ipst->ips_netstack);
21051 				return;
21052 			} else {
21053 				/*
21054 				 * This must be ARP or special TSOL signaling.
21055 				 */
21056 				ip_wput_nondata(NULL, q, mp, NULL);
21057 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21058 				    "ip_wput_end: q %p (%S)", q, "nondata");
21059 				return;
21060 			}
21061 		} else {
21062 			/*
21063 			 * This must be non-(ARP/AH/ESP) messages.
21064 			 */
21065 			ASSERT(!need_decref);
21066 			ip_wput_nondata(NULL, q, mp, NULL);
21067 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21068 			    "ip_wput_end: q %p (%S)", q, "nondata");
21069 			return;
21070 		}
21071 	} else {
21072 		first_mp = mp;
21073 		mctl_present = B_FALSE;
21074 	}
21075 
21076 	ASSERT(first_mp != NULL);
21077 	/*
21078 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
21079 	 * to make sure that this packet goes out on the same interface it
21080 	 * came in. We handle that here.
21081 	 */
21082 	if (mctl_present) {
21083 		uint_t ifindex;
21084 
21085 		io = (ipsec_out_t *)first_mp->b_rptr;
21086 		if (io->ipsec_out_attach_if || io->ipsec_out_ip_nexthop) {
21087 			/*
21088 			 * We may have lost the conn context if we are
21089 			 * coming here from ip_newroute(). Copy the
21090 			 * nexthop information.
21091 			 */
21092 			if (io->ipsec_out_ip_nexthop) {
21093 				ip_nexthop = B_TRUE;
21094 				nexthop_addr = io->ipsec_out_nexthop_addr;
21095 
21096 				ipha = (ipha_t *)mp->b_rptr;
21097 				dst = ipha->ipha_dst;
21098 				goto send_from_ill;
21099 			} else {
21100 				ASSERT(io->ipsec_out_ill_index != 0);
21101 				ifindex = io->ipsec_out_ill_index;
21102 				attach_ill = ill_lookup_on_ifindex(ifindex,
21103 				    B_FALSE, NULL, NULL, NULL, NULL, ipst);
21104 				if (attach_ill == NULL) {
21105 					ASSERT(xmit_ill == NULL);
21106 					ip1dbg(("ip_output: bad ifindex for "
21107 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
21108 					    ifindex));
21109 					freemsg(first_mp);
21110 					BUMP_MIB(&ipst->ips_ip_mib,
21111 					    ipIfStatsOutDiscards);
21112 					ASSERT(!need_decref);
21113 					return;
21114 				}
21115 			}
21116 		}
21117 	}
21118 
21119 	ASSERT(xmit_ill == NULL);
21120 
21121 	/* We have a complete IP datagram heading outbound. */
21122 	ipha = (ipha_t *)mp->b_rptr;
21123 
21124 #ifndef SPEED_BEFORE_SAFETY
21125 	/*
21126 	 * Make sure we have a full-word aligned message and that at least
21127 	 * a simple IP header is accessible in the first message.  If not,
21128 	 * try a pullup.  For labeled systems we need to always take this
21129 	 * path as M_CTLs are "notdata" but have trailing data to process.
21130 	 */
21131 	if (!OK_32PTR(rptr) ||
21132 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
21133 hdrtoosmall:
21134 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
21135 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21136 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
21137 			if (first_mp == NULL)
21138 				first_mp = mp;
21139 			goto discard_pkt;
21140 		}
21141 
21142 		/* This function assumes that mp points to an IPv4 packet. */
21143 		if (is_system_labeled() && q->q_next == NULL &&
21144 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
21145 		    !connp->conn_ulp_labeled) {
21146 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
21147 			    connp->conn_mac_exempt, ipst);
21148 			ipha = (ipha_t *)mp->b_rptr;
21149 			if (first_mp != NULL)
21150 				first_mp->b_cont = mp;
21151 			if (err != 0) {
21152 				if (first_mp == NULL)
21153 					first_mp = mp;
21154 				if (err == EINVAL)
21155 					goto icmp_parameter_problem;
21156 				ip2dbg(("ip_wput: label check failed (%d)\n",
21157 				    err));
21158 				goto discard_pkt;
21159 			}
21160 		}
21161 
21162 		ipha = (ipha_t *)mp->b_rptr;
21163 		if (first_mp == NULL) {
21164 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
21165 			/*
21166 			 * If we got here because of "goto hdrtoosmall"
21167 			 * We need to attach a IPSEC_OUT.
21168 			 */
21169 			if (connp->conn_out_enforce_policy) {
21170 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
21171 				    NULL, ipha->ipha_protocol,
21172 				    ipst->ips_netstack)) == NULL)) {
21173 					BUMP_MIB(&ipst->ips_ip_mib,
21174 					    ipIfStatsOutDiscards);
21175 					if (need_decref)
21176 						CONN_DEC_REF(connp);
21177 					return;
21178 				} else {
21179 					ASSERT(mp->b_datap->db_type == M_CTL);
21180 					first_mp = mp;
21181 					mp = mp->b_cont;
21182 					mctl_present = B_TRUE;
21183 				}
21184 			} else {
21185 				first_mp = mp;
21186 				mctl_present = B_FALSE;
21187 			}
21188 		}
21189 	}
21190 #endif
21191 
21192 	/* Most of the code below is written for speed, not readability */
21193 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21194 
21195 	/*
21196 	 * If ip_newroute() fails, we're going to need a full
21197 	 * header for the icmp wraparound.
21198 	 */
21199 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
21200 		uint_t	v_hlen;
21201 version_hdrlen_check:
21202 		ASSERT(first_mp != NULL);
21203 		v_hlen = V_HLEN;
21204 		/*
21205 		 * siphon off IPv6 packets coming down from transport
21206 		 * layer modules here.
21207 		 * Note: high-order bit carries NUD reachability confirmation
21208 		 */
21209 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
21210 			/*
21211 			 * FIXME: assume that callers of ip_output* call
21212 			 * the right version?
21213 			 */
21214 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
21215 			ASSERT(xmit_ill == NULL);
21216 			if (attach_ill != NULL)
21217 				ill_refrele(attach_ill);
21218 			if (need_decref)
21219 				mp->b_flag |= MSGHASREF;
21220 			(void) ip_output_v6(arg, first_mp, arg2, caller);
21221 			return;
21222 		}
21223 
21224 		if ((v_hlen >> 4) != IP_VERSION) {
21225 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21226 			    "ip_wput_end: q %p (%S)", q, "badvers");
21227 			goto discard_pkt;
21228 		}
21229 		/*
21230 		 * Is the header length at least 20 bytes?
21231 		 *
21232 		 * Are there enough bytes accessible in the header?  If
21233 		 * not, try a pullup.
21234 		 */
21235 		v_hlen &= 0xF;
21236 		v_hlen <<= 2;
21237 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
21238 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21239 			    "ip_wput_end: q %p (%S)", q, "badlen");
21240 			goto discard_pkt;
21241 		}
21242 		if (v_hlen > (mp->b_wptr - rptr)) {
21243 			if (!pullupmsg(mp, v_hlen)) {
21244 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21245 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
21246 				goto discard_pkt;
21247 			}
21248 			ipha = (ipha_t *)mp->b_rptr;
21249 		}
21250 		/*
21251 		 * Move first entry from any source route into ipha_dst and
21252 		 * verify the options
21253 		 */
21254 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
21255 		    zoneid, ipst)) {
21256 			ASSERT(xmit_ill == NULL);
21257 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21258 			if (attach_ill != NULL)
21259 				ill_refrele(attach_ill);
21260 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21261 			    "ip_wput_end: q %p (%S)", q, "badopts");
21262 			if (need_decref)
21263 				CONN_DEC_REF(connp);
21264 			return;
21265 		}
21266 	}
21267 	dst = ipha->ipha_dst;
21268 
21269 	/*
21270 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
21271 	 * we have to run the packet through ip_newroute which will take
21272 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
21273 	 * a resolver, or assigning a default gateway, etc.
21274 	 */
21275 	if (CLASSD(dst)) {
21276 		ipif_t	*ipif;
21277 		uint32_t setsrc = 0;
21278 
21279 multicast:
21280 		ASSERT(first_mp != NULL);
21281 		ip2dbg(("ip_wput: CLASSD\n"));
21282 		if (connp == NULL) {
21283 			/*
21284 			 * Use the first good ipif on the ill.
21285 			 * XXX Should this ever happen? (Appears
21286 			 * to show up with just ppp and no ethernet due
21287 			 * to in.rdisc.)
21288 			 * However, ire_send should be able to
21289 			 * call ip_wput_ire directly.
21290 			 *
21291 			 * XXX Also, this can happen for ICMP and other packets
21292 			 * with multicast source addresses.  Perhaps we should
21293 			 * fix things so that we drop the packet in question,
21294 			 * but for now, just run with it.
21295 			 */
21296 			ill_t *ill = (ill_t *)q->q_ptr;
21297 
21298 			/*
21299 			 * Don't honor attach_if for this case. If ill
21300 			 * is part of the group, ipif could belong to
21301 			 * any ill and we cannot maintain attach_ill
21302 			 * and ipif_ill same anymore and the assert
21303 			 * below would fail.
21304 			 */
21305 			if (mctl_present && io->ipsec_out_attach_if) {
21306 				io->ipsec_out_ill_index = 0;
21307 				io->ipsec_out_attach_if = B_FALSE;
21308 				ASSERT(attach_ill != NULL);
21309 				ill_refrele(attach_ill);
21310 				attach_ill = NULL;
21311 			}
21312 
21313 			ASSERT(attach_ill == NULL);
21314 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21315 			if (ipif == NULL) {
21316 				if (need_decref)
21317 					CONN_DEC_REF(connp);
21318 				freemsg(first_mp);
21319 				return;
21320 			}
21321 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21322 			    ntohl(dst), ill->ill_name));
21323 		} else {
21324 			/*
21325 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
21326 			 * and IP_MULTICAST_IF.  The block comment above this
21327 			 * function explains the locking mechanism used here.
21328 			 */
21329 			if (xmit_ill == NULL) {
21330 				xmit_ill = conn_get_held_ill(connp,
21331 				    &connp->conn_outgoing_ill, &err);
21332 				if (err == ILL_LOOKUP_FAILED) {
21333 					ip1dbg(("ip_wput: No ill for "
21334 					    "IP_BOUND_IF\n"));
21335 					BUMP_MIB(&ipst->ips_ip_mib,
21336 					    ipIfStatsOutNoRoutes);
21337 					goto drop_pkt;
21338 				}
21339 			}
21340 
21341 			if (xmit_ill == NULL) {
21342 				ipif = conn_get_held_ipif(connp,
21343 				    &connp->conn_multicast_ipif, &err);
21344 				if (err == IPIF_LOOKUP_FAILED) {
21345 					ip1dbg(("ip_wput: No ipif for "
21346 					    "multicast\n"));
21347 					BUMP_MIB(&ipst->ips_ip_mib,
21348 					    ipIfStatsOutNoRoutes);
21349 					goto drop_pkt;
21350 				}
21351 			}
21352 			if (xmit_ill != NULL) {
21353 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21354 				if (ipif == NULL) {
21355 					ip1dbg(("ip_wput: No ipif for "
21356 					    "xmit_ill\n"));
21357 					BUMP_MIB(&ipst->ips_ip_mib,
21358 					    ipIfStatsOutNoRoutes);
21359 					goto drop_pkt;
21360 				}
21361 			} else if (ipif == NULL || ipif->ipif_isv6) {
21362 				/*
21363 				 * We must do this ipif determination here
21364 				 * else we could pass through ip_newroute
21365 				 * and come back here without the conn context.
21366 				 *
21367 				 * Note: we do late binding i.e. we bind to
21368 				 * the interface when the first packet is sent.
21369 				 * For performance reasons we do not rebind on
21370 				 * each packet but keep the binding until the
21371 				 * next IP_MULTICAST_IF option.
21372 				 *
21373 				 * conn_multicast_{ipif,ill} are shared between
21374 				 * IPv4 and IPv6 and AF_INET6 sockets can
21375 				 * send both IPv4 and IPv6 packets. Hence
21376 				 * we have to check that "isv6" matches above.
21377 				 */
21378 				if (ipif != NULL)
21379 					ipif_refrele(ipif);
21380 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21381 				if (ipif == NULL) {
21382 					ip1dbg(("ip_wput: No ipif for "
21383 					    "multicast\n"));
21384 					BUMP_MIB(&ipst->ips_ip_mib,
21385 					    ipIfStatsOutNoRoutes);
21386 					goto drop_pkt;
21387 				}
21388 				err = conn_set_held_ipif(connp,
21389 				    &connp->conn_multicast_ipif, ipif);
21390 				if (err == IPIF_LOOKUP_FAILED) {
21391 					ipif_refrele(ipif);
21392 					ip1dbg(("ip_wput: No ipif for "
21393 					    "multicast\n"));
21394 					BUMP_MIB(&ipst->ips_ip_mib,
21395 					    ipIfStatsOutNoRoutes);
21396 					goto drop_pkt;
21397 				}
21398 			}
21399 		}
21400 		ASSERT(!ipif->ipif_isv6);
21401 		/*
21402 		 * As we may lose the conn by the time we reach ip_wput_ire,
21403 		 * we copy conn_multicast_loop and conn_dontroute on to an
21404 		 * ipsec_out. In case if this datagram goes out secure,
21405 		 * we need the ill_index also. Copy that also into the
21406 		 * ipsec_out.
21407 		 */
21408 		if (mctl_present) {
21409 			io = (ipsec_out_t *)first_mp->b_rptr;
21410 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21411 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21412 		} else {
21413 			ASSERT(mp == first_mp);
21414 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21415 			    BPRI_HI)) == NULL) {
21416 				ipif_refrele(ipif);
21417 				first_mp = mp;
21418 				goto discard_pkt;
21419 			}
21420 			first_mp->b_datap->db_type = M_CTL;
21421 			first_mp->b_wptr += sizeof (ipsec_info_t);
21422 			/* ipsec_out_secure is B_FALSE now */
21423 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21424 			io = (ipsec_out_t *)first_mp->b_rptr;
21425 			io->ipsec_out_type = IPSEC_OUT;
21426 			io->ipsec_out_len = sizeof (ipsec_out_t);
21427 			io->ipsec_out_use_global_policy = B_TRUE;
21428 			io->ipsec_out_ns = ipst->ips_netstack;
21429 			first_mp->b_cont = mp;
21430 			mctl_present = B_TRUE;
21431 		}
21432 		if (attach_ill != NULL) {
21433 			ASSERT(attach_ill == ipif->ipif_ill);
21434 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21435 
21436 			/*
21437 			 * Check if we need an ire that will not be
21438 			 * looked up by anybody else i.e. HIDDEN.
21439 			 */
21440 			if (ill_is_probeonly(attach_ill)) {
21441 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21442 			}
21443 			io->ipsec_out_ill_index =
21444 			    attach_ill->ill_phyint->phyint_ifindex;
21445 			io->ipsec_out_attach_if = B_TRUE;
21446 		} else {
21447 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21448 			io->ipsec_out_ill_index =
21449 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21450 		}
21451 		if (connp != NULL) {
21452 			io->ipsec_out_multicast_loop =
21453 			    connp->conn_multicast_loop;
21454 			io->ipsec_out_dontroute = connp->conn_dontroute;
21455 			io->ipsec_out_zoneid = connp->conn_zoneid;
21456 		}
21457 		/*
21458 		 * If the application uses IP_MULTICAST_IF with
21459 		 * different logical addresses of the same ILL, we
21460 		 * need to make sure that the soruce address of
21461 		 * the packet matches the logical IP address used
21462 		 * in the option. We do it by initializing ipha_src
21463 		 * here. This should keep IPsec also happy as
21464 		 * when we return from IPsec processing, we don't
21465 		 * have to worry about getting the right address on
21466 		 * the packet. Thus it is sufficient to look for
21467 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21468 		 * MATCH_IRE_IPIF.
21469 		 *
21470 		 * NOTE : We need to do it for non-secure case also as
21471 		 * this might go out secure if there is a global policy
21472 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21473 		 * address, the source should be initialized already and
21474 		 * hence we won't be initializing here.
21475 		 *
21476 		 * As we do not have the ire yet, it is possible that
21477 		 * we set the source address here and then later discover
21478 		 * that the ire implies the source address to be assigned
21479 		 * through the RTF_SETSRC flag.
21480 		 * In that case, the setsrc variable will remind us
21481 		 * that overwritting the source address by the one
21482 		 * of the RTF_SETSRC-flagged ire is allowed.
21483 		 */
21484 		if (ipha->ipha_src == INADDR_ANY &&
21485 		    (connp == NULL || !connp->conn_unspec_src)) {
21486 			ipha->ipha_src = ipif->ipif_src_addr;
21487 			setsrc = RTF_SETSRC;
21488 		}
21489 		/*
21490 		 * Find an IRE which matches the destination and the outgoing
21491 		 * queue (i.e. the outgoing interface.)
21492 		 * For loopback use a unicast IP address for
21493 		 * the ire lookup.
21494 		 */
21495 		if (IS_LOOPBACK(ipif->ipif_ill))
21496 			dst = ipif->ipif_lcl_addr;
21497 
21498 		/*
21499 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21500 		 * We don't need to lookup ire in ctable as the packet
21501 		 * needs to be sent to the destination through the specified
21502 		 * ill irrespective of ires in the cache table.
21503 		 */
21504 		ire = NULL;
21505 		if (xmit_ill == NULL) {
21506 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21507 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21508 		}
21509 
21510 		/*
21511 		 * refrele attach_ill as its not needed anymore.
21512 		 */
21513 		if (attach_ill != NULL) {
21514 			ill_refrele(attach_ill);
21515 			attach_ill = NULL;
21516 		}
21517 
21518 		if (ire == NULL) {
21519 			/*
21520 			 * Multicast loopback and multicast forwarding is
21521 			 * done in ip_wput_ire.
21522 			 *
21523 			 * Mark this packet to make it be delivered to
21524 			 * ip_wput_ire after the new ire has been
21525 			 * created.
21526 			 *
21527 			 * The call to ip_newroute_ipif takes into account
21528 			 * the setsrc reminder. In any case, we take care
21529 			 * of the RTF_MULTIRT flag.
21530 			 */
21531 			mp->b_prev = mp->b_next = NULL;
21532 			if (xmit_ill == NULL ||
21533 			    xmit_ill->ill_ipif_up_count > 0) {
21534 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21535 				    setsrc | RTF_MULTIRT, zoneid, infop);
21536 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21537 				    "ip_wput_end: q %p (%S)", q, "noire");
21538 			} else {
21539 				freemsg(first_mp);
21540 			}
21541 			ipif_refrele(ipif);
21542 			if (xmit_ill != NULL)
21543 				ill_refrele(xmit_ill);
21544 			if (need_decref)
21545 				CONN_DEC_REF(connp);
21546 			return;
21547 		}
21548 
21549 		ipif_refrele(ipif);
21550 		ipif = NULL;
21551 		ASSERT(xmit_ill == NULL);
21552 
21553 		/*
21554 		 * Honor the RTF_SETSRC flag for multicast packets,
21555 		 * if allowed by the setsrc reminder.
21556 		 */
21557 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21558 			ipha->ipha_src = ire->ire_src_addr;
21559 		}
21560 
21561 		/*
21562 		 * Unconditionally force the TTL to 1 for
21563 		 * multirouted multicast packets:
21564 		 * multirouted multicast should not cross
21565 		 * multicast routers.
21566 		 */
21567 		if (ire->ire_flags & RTF_MULTIRT) {
21568 			if (ipha->ipha_ttl > 1) {
21569 				ip2dbg(("ip_wput: forcing multicast "
21570 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21571 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21572 				ipha->ipha_ttl = 1;
21573 			}
21574 		}
21575 	} else {
21576 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21577 		if ((ire != NULL) && (ire->ire_type &
21578 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21579 			ignore_dontroute = B_TRUE;
21580 			ignore_nexthop = B_TRUE;
21581 		}
21582 		if (ire != NULL) {
21583 			ire_refrele(ire);
21584 			ire = NULL;
21585 		}
21586 		/*
21587 		 * Guard against coming in from arp in which case conn is NULL.
21588 		 * Also guard against non M_DATA with dontroute set but
21589 		 * destined to local, loopback or broadcast addresses.
21590 		 */
21591 		if (connp != NULL && connp->conn_dontroute &&
21592 		    !ignore_dontroute) {
21593 dontroute:
21594 			/*
21595 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21596 			 * routing protocols from seeing false direct
21597 			 * connectivity.
21598 			 */
21599 			ipha->ipha_ttl = 1;
21600 			/* If suitable ipif not found, drop packet */
21601 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21602 			if (dst_ipif == NULL) {
21603 noroute:
21604 				ip1dbg(("ip_wput: no route for dst using"
21605 				    " SO_DONTROUTE\n"));
21606 				BUMP_MIB(&ipst->ips_ip_mib,
21607 				    ipIfStatsOutNoRoutes);
21608 				mp->b_prev = mp->b_next = NULL;
21609 				if (first_mp == NULL)
21610 					first_mp = mp;
21611 				goto drop_pkt;
21612 			} else {
21613 				/*
21614 				 * If suitable ipif has been found, set
21615 				 * xmit_ill to the corresponding
21616 				 * ipif_ill because we'll be using the
21617 				 * send_from_ill logic below.
21618 				 */
21619 				ASSERT(xmit_ill == NULL);
21620 				xmit_ill = dst_ipif->ipif_ill;
21621 				mutex_enter(&xmit_ill->ill_lock);
21622 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21623 					mutex_exit(&xmit_ill->ill_lock);
21624 					xmit_ill = NULL;
21625 					ipif_refrele(dst_ipif);
21626 					goto noroute;
21627 				}
21628 				ill_refhold_locked(xmit_ill);
21629 				mutex_exit(&xmit_ill->ill_lock);
21630 				ipif_refrele(dst_ipif);
21631 			}
21632 		}
21633 		/*
21634 		 * If we are bound to IPIF_NOFAILOVER address, look for
21635 		 * an IRE_CACHE matching the ill.
21636 		 */
21637 send_from_ill:
21638 		if (attach_ill != NULL) {
21639 			ipif_t	*attach_ipif;
21640 
21641 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21642 
21643 			/*
21644 			 * Check if we need an ire that will not be
21645 			 * looked up by anybody else i.e. HIDDEN.
21646 			 */
21647 			if (ill_is_probeonly(attach_ill)) {
21648 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21649 			}
21650 
21651 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21652 			if (attach_ipif == NULL) {
21653 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21654 				goto discard_pkt;
21655 			}
21656 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21657 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21658 			ipif_refrele(attach_ipif);
21659 		} else if (xmit_ill != NULL) {
21660 			ipif_t *ipif;
21661 
21662 			/*
21663 			 * Mark this packet as originated locally
21664 			 */
21665 			mp->b_prev = mp->b_next = NULL;
21666 
21667 			/*
21668 			 * Could be SO_DONTROUTE case also.
21669 			 * Verify that at least one ipif is up on the ill.
21670 			 */
21671 			if (xmit_ill->ill_ipif_up_count == 0) {
21672 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21673 				    xmit_ill->ill_name));
21674 				goto drop_pkt;
21675 			}
21676 
21677 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21678 			if (ipif == NULL) {
21679 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21680 				    xmit_ill->ill_name));
21681 				goto drop_pkt;
21682 			}
21683 
21684 			/*
21685 			 * Look for a ire that is part of the group,
21686 			 * if found use it else call ip_newroute_ipif.
21687 			 * IPCL_ZONEID is not used for matching because
21688 			 * IP_ALLZONES option is valid only when the
21689 			 * ill is accessible from all zones i.e has a
21690 			 * valid ipif in all zones.
21691 			 */
21692 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21693 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21694 			    MBLK_GETLABEL(mp), match_flags, ipst);
21695 			/*
21696 			 * If an ire exists use it or else create
21697 			 * an ire but don't add it to the cache.
21698 			 * Adding an ire may cause issues with
21699 			 * asymmetric routing.
21700 			 * In case of multiroute always act as if
21701 			 * ire does not exist.
21702 			 */
21703 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21704 				if (ire != NULL)
21705 					ire_refrele(ire);
21706 				ip_newroute_ipif(q, first_mp, ipif,
21707 				    dst, connp, 0, zoneid, infop);
21708 				ipif_refrele(ipif);
21709 				ip1dbg(("ip_output: xmit_ill via %s\n",
21710 				    xmit_ill->ill_name));
21711 				ill_refrele(xmit_ill);
21712 				if (need_decref)
21713 					CONN_DEC_REF(connp);
21714 				return;
21715 			}
21716 			ipif_refrele(ipif);
21717 		} else if (ip_nexthop || (connp != NULL &&
21718 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21719 			if (!ip_nexthop) {
21720 				ip_nexthop = B_TRUE;
21721 				nexthop_addr = connp->conn_nexthop_v4;
21722 			}
21723 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21724 			    MATCH_IRE_GW;
21725 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21726 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21727 		} else {
21728 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21729 			    ipst);
21730 		}
21731 		if (!ire) {
21732 			/*
21733 			 * Make sure we don't load spread if this
21734 			 * is IPIF_NOFAILOVER case.
21735 			 */
21736 			if ((attach_ill != NULL) ||
21737 			    (ip_nexthop && !ignore_nexthop)) {
21738 				if (mctl_present) {
21739 					io = (ipsec_out_t *)first_mp->b_rptr;
21740 					ASSERT(first_mp->b_datap->db_type ==
21741 					    M_CTL);
21742 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21743 				} else {
21744 					ASSERT(mp == first_mp);
21745 					first_mp = allocb(
21746 					    sizeof (ipsec_info_t), BPRI_HI);
21747 					if (first_mp == NULL) {
21748 						first_mp = mp;
21749 						goto discard_pkt;
21750 					}
21751 					first_mp->b_datap->db_type = M_CTL;
21752 					first_mp->b_wptr +=
21753 					    sizeof (ipsec_info_t);
21754 					/* ipsec_out_secure is B_FALSE now */
21755 					bzero(first_mp->b_rptr,
21756 					    sizeof (ipsec_info_t));
21757 					io = (ipsec_out_t *)first_mp->b_rptr;
21758 					io->ipsec_out_type = IPSEC_OUT;
21759 					io->ipsec_out_len =
21760 					    sizeof (ipsec_out_t);
21761 					io->ipsec_out_use_global_policy =
21762 					    B_TRUE;
21763 					io->ipsec_out_ns = ipst->ips_netstack;
21764 					first_mp->b_cont = mp;
21765 					mctl_present = B_TRUE;
21766 				}
21767 				if (attach_ill != NULL) {
21768 					io->ipsec_out_ill_index = attach_ill->
21769 					    ill_phyint->phyint_ifindex;
21770 					io->ipsec_out_attach_if = B_TRUE;
21771 				} else {
21772 					io->ipsec_out_ip_nexthop = ip_nexthop;
21773 					io->ipsec_out_nexthop_addr =
21774 					    nexthop_addr;
21775 				}
21776 			}
21777 noirefound:
21778 			/*
21779 			 * Mark this packet as having originated on
21780 			 * this machine.  This will be noted in
21781 			 * ire_add_then_send, which needs to know
21782 			 * whether to run it back through ip_wput or
21783 			 * ip_rput following successful resolution.
21784 			 */
21785 			mp->b_prev = NULL;
21786 			mp->b_next = NULL;
21787 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21788 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21789 			    "ip_wput_end: q %p (%S)", q, "newroute");
21790 			if (attach_ill != NULL)
21791 				ill_refrele(attach_ill);
21792 			if (xmit_ill != NULL)
21793 				ill_refrele(xmit_ill);
21794 			if (need_decref)
21795 				CONN_DEC_REF(connp);
21796 			return;
21797 		}
21798 	}
21799 
21800 	/* We now know where we are going with it. */
21801 
21802 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21803 	    "ip_wput_end: q %p (%S)", q, "end");
21804 
21805 	/*
21806 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21807 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21808 	 */
21809 	if (ire->ire_flags & RTF_MULTIRT) {
21810 		/*
21811 		 * Force the TTL of multirouted packets if required.
21812 		 * The TTL of such packets is bounded by the
21813 		 * ip_multirt_ttl ndd variable.
21814 		 */
21815 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21816 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21817 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21818 			    "(was %d), dst 0x%08x\n",
21819 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21820 			    ntohl(ire->ire_addr)));
21821 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21822 		}
21823 		/*
21824 		 * At this point, we check to see if there are any pending
21825 		 * unresolved routes. ire_multirt_resolvable()
21826 		 * checks in O(n) that all IRE_OFFSUBNET ire
21827 		 * entries for the packet's destination and
21828 		 * flagged RTF_MULTIRT are currently resolved.
21829 		 * If some remain unresolved, we make a copy
21830 		 * of the current message. It will be used
21831 		 * to initiate additional route resolutions.
21832 		 */
21833 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21834 		    MBLK_GETLABEL(first_mp), ipst);
21835 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21836 		    "multirt_need_resolve %d, first_mp %p\n",
21837 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21838 		if (multirt_need_resolve) {
21839 			copy_mp = copymsg(first_mp);
21840 			if (copy_mp != NULL) {
21841 				MULTIRT_DEBUG_TAG(copy_mp);
21842 			}
21843 		}
21844 	}
21845 
21846 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21847 	/*
21848 	 * Try to resolve another multiroute if
21849 	 * ire_multirt_resolvable() deemed it necessary.
21850 	 * At this point, we need to distinguish
21851 	 * multicasts from other packets. For multicasts,
21852 	 * we call ip_newroute_ipif() and request that both
21853 	 * multirouting and setsrc flags are checked.
21854 	 */
21855 	if (copy_mp != NULL) {
21856 		if (CLASSD(dst)) {
21857 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21858 			if (ipif) {
21859 				ASSERT(infop->ip_opt_ill_index == 0);
21860 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21861 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21862 				ipif_refrele(ipif);
21863 			} else {
21864 				MULTIRT_DEBUG_UNTAG(copy_mp);
21865 				freemsg(copy_mp);
21866 				copy_mp = NULL;
21867 			}
21868 		} else {
21869 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21870 		}
21871 	}
21872 	if (attach_ill != NULL)
21873 		ill_refrele(attach_ill);
21874 	if (xmit_ill != NULL)
21875 		ill_refrele(xmit_ill);
21876 	if (need_decref)
21877 		CONN_DEC_REF(connp);
21878 	return;
21879 
21880 icmp_parameter_problem:
21881 	/* could not have originated externally */
21882 	ASSERT(mp->b_prev == NULL);
21883 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21884 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21885 		/* it's the IP header length that's in trouble */
21886 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21887 		first_mp = NULL;
21888 	}
21889 
21890 discard_pkt:
21891 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21892 drop_pkt:
21893 	ip1dbg(("ip_wput: dropped packet\n"));
21894 	if (ire != NULL)
21895 		ire_refrele(ire);
21896 	if (need_decref)
21897 		CONN_DEC_REF(connp);
21898 	freemsg(first_mp);
21899 	if (attach_ill != NULL)
21900 		ill_refrele(attach_ill);
21901 	if (xmit_ill != NULL)
21902 		ill_refrele(xmit_ill);
21903 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21904 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21905 }
21906 
21907 /*
21908  * If this is a conn_t queue, then we pass in the conn. This includes the
21909  * zoneid.
21910  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21911  * in which case we use the global zoneid since those are all part of
21912  * the global zone.
21913  */
21914 void
21915 ip_wput(queue_t *q, mblk_t *mp)
21916 {
21917 	if (CONN_Q(q))
21918 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21919 	else
21920 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21921 }
21922 
21923 /*
21924  *
21925  * The following rules must be observed when accessing any ipif or ill
21926  * that has been cached in the conn. Typically conn_nofailover_ill,
21927  * conn_outgoing_ill, conn_multicast_ipif and conn_multicast_ill.
21928  *
21929  * Access: The ipif or ill pointed to from the conn can be accessed under
21930  * the protection of the conn_lock or after it has been refheld under the
21931  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21932  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21933  * The reason for this is that a concurrent unplumb could actually be
21934  * cleaning up these cached pointers by walking the conns and might have
21935  * finished cleaning up the conn in question. The macros check that an
21936  * unplumb has not yet started on the ipif or ill.
21937  *
21938  * Caching: An ipif or ill pointer may be cached in the conn only after
21939  * making sure that an unplumb has not started. So the caching is done
21940  * while holding both the conn_lock and the ill_lock and after using the
21941  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21942  * flag before starting the cleanup of conns.
21943  *
21944  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21945  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21946  * or a reference to the ipif or a reference to an ire that references the
21947  * ipif. An ipif does not change its ill except for failover/failback. Since
21948  * failover/failback happens only after bringing down the ipif and making sure
21949  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21950  * the above holds.
21951  */
21952 ipif_t *
21953 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21954 {
21955 	ipif_t	*ipif;
21956 	ill_t	*ill;
21957 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21958 
21959 	*err = 0;
21960 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21961 	mutex_enter(&connp->conn_lock);
21962 	ipif = *ipifp;
21963 	if (ipif != NULL) {
21964 		ill = ipif->ipif_ill;
21965 		mutex_enter(&ill->ill_lock);
21966 		if (IPIF_CAN_LOOKUP(ipif)) {
21967 			ipif_refhold_locked(ipif);
21968 			mutex_exit(&ill->ill_lock);
21969 			mutex_exit(&connp->conn_lock);
21970 			rw_exit(&ipst->ips_ill_g_lock);
21971 			return (ipif);
21972 		} else {
21973 			*err = IPIF_LOOKUP_FAILED;
21974 		}
21975 		mutex_exit(&ill->ill_lock);
21976 	}
21977 	mutex_exit(&connp->conn_lock);
21978 	rw_exit(&ipst->ips_ill_g_lock);
21979 	return (NULL);
21980 }
21981 
21982 ill_t *
21983 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21984 {
21985 	ill_t	*ill;
21986 
21987 	*err = 0;
21988 	mutex_enter(&connp->conn_lock);
21989 	ill = *illp;
21990 	if (ill != NULL) {
21991 		mutex_enter(&ill->ill_lock);
21992 		if (ILL_CAN_LOOKUP(ill)) {
21993 			ill_refhold_locked(ill);
21994 			mutex_exit(&ill->ill_lock);
21995 			mutex_exit(&connp->conn_lock);
21996 			return (ill);
21997 		} else {
21998 			*err = ILL_LOOKUP_FAILED;
21999 		}
22000 		mutex_exit(&ill->ill_lock);
22001 	}
22002 	mutex_exit(&connp->conn_lock);
22003 	return (NULL);
22004 }
22005 
22006 static int
22007 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
22008 {
22009 	ill_t	*ill;
22010 
22011 	ill = ipif->ipif_ill;
22012 	mutex_enter(&connp->conn_lock);
22013 	mutex_enter(&ill->ill_lock);
22014 	if (IPIF_CAN_LOOKUP(ipif)) {
22015 		*ipifp = ipif;
22016 		mutex_exit(&ill->ill_lock);
22017 		mutex_exit(&connp->conn_lock);
22018 		return (0);
22019 	}
22020 	mutex_exit(&ill->ill_lock);
22021 	mutex_exit(&connp->conn_lock);
22022 	return (IPIF_LOOKUP_FAILED);
22023 }
22024 
22025 /*
22026  * This is called if the outbound datagram needs fragmentation.
22027  *
22028  * NOTE : This function does not ire_refrele the ire argument passed in.
22029  */
22030 static void
22031 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
22032     ip_stack_t *ipst, conn_t *connp)
22033 {
22034 	ipha_t		*ipha;
22035 	mblk_t		*mp;
22036 	uint32_t	v_hlen_tos_len;
22037 	uint32_t	max_frag;
22038 	uint32_t	frag_flag;
22039 	boolean_t	dont_use;
22040 
22041 	if (ipsec_mp->b_datap->db_type == M_CTL) {
22042 		mp = ipsec_mp->b_cont;
22043 	} else {
22044 		mp = ipsec_mp;
22045 	}
22046 
22047 	ipha = (ipha_t *)mp->b_rptr;
22048 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22049 
22050 #ifdef	_BIG_ENDIAN
22051 #define	V_HLEN	(v_hlen_tos_len >> 24)
22052 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22053 #else
22054 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22055 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22056 #endif
22057 
22058 #ifndef SPEED_BEFORE_SAFETY
22059 	/*
22060 	 * Check that ipha_length is consistent with
22061 	 * the mblk length
22062 	 */
22063 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
22064 		ip0dbg(("Packet length mismatch: %d, %ld\n",
22065 		    LENGTH, msgdsize(mp)));
22066 		freemsg(ipsec_mp);
22067 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22068 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
22069 		    "packet length mismatch");
22070 		return;
22071 	}
22072 #endif
22073 	/*
22074 	 * Don't use frag_flag if pre-built packet or source
22075 	 * routed or if multicast (since multicast packets do not solicit
22076 	 * ICMP "packet too big" messages). Get the values of
22077 	 * max_frag and frag_flag atomically by acquiring the
22078 	 * ire_lock.
22079 	 */
22080 	mutex_enter(&ire->ire_lock);
22081 	max_frag = ire->ire_max_frag;
22082 	frag_flag = ire->ire_frag_flag;
22083 	mutex_exit(&ire->ire_lock);
22084 
22085 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
22086 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
22087 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
22088 
22089 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
22090 	    (dont_use ? 0 : frag_flag), zoneid, ipst, connp);
22091 }
22092 
22093 /*
22094  * Used for deciding the MSS size for the upper layer. Thus
22095  * we need to check the outbound policy values in the conn.
22096  */
22097 int
22098 conn_ipsec_length(conn_t *connp)
22099 {
22100 	ipsec_latch_t *ipl;
22101 
22102 	ipl = connp->conn_latch;
22103 	if (ipl == NULL)
22104 		return (0);
22105 
22106 	if (ipl->ipl_out_policy == NULL)
22107 		return (0);
22108 
22109 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
22110 }
22111 
22112 /*
22113  * Returns an estimate of the IPsec headers size. This is used if
22114  * we don't want to call into IPsec to get the exact size.
22115  */
22116 int
22117 ipsec_out_extra_length(mblk_t *ipsec_mp)
22118 {
22119 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
22120 	ipsec_action_t *a;
22121 
22122 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
22123 	if (!io->ipsec_out_secure)
22124 		return (0);
22125 
22126 	a = io->ipsec_out_act;
22127 
22128 	if (a == NULL) {
22129 		ASSERT(io->ipsec_out_policy != NULL);
22130 		a = io->ipsec_out_policy->ipsp_act;
22131 	}
22132 	ASSERT(a != NULL);
22133 
22134 	return (a->ipa_ovhd);
22135 }
22136 
22137 /*
22138  * Returns an estimate of the IPsec headers size. This is used if
22139  * we don't want to call into IPsec to get the exact size.
22140  */
22141 int
22142 ipsec_in_extra_length(mblk_t *ipsec_mp)
22143 {
22144 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22145 	ipsec_action_t *a;
22146 
22147 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
22148 
22149 	a = ii->ipsec_in_action;
22150 	return (a == NULL ? 0 : a->ipa_ovhd);
22151 }
22152 
22153 /*
22154  * If there are any source route options, return the true final
22155  * destination. Otherwise, return the destination.
22156  */
22157 ipaddr_t
22158 ip_get_dst(ipha_t *ipha)
22159 {
22160 	ipoptp_t	opts;
22161 	uchar_t		*opt;
22162 	uint8_t		optval;
22163 	uint8_t		optlen;
22164 	ipaddr_t	dst;
22165 	uint32_t off;
22166 
22167 	dst = ipha->ipha_dst;
22168 
22169 	if (IS_SIMPLE_IPH(ipha))
22170 		return (dst);
22171 
22172 	for (optval = ipoptp_first(&opts, ipha);
22173 	    optval != IPOPT_EOL;
22174 	    optval = ipoptp_next(&opts)) {
22175 		opt = opts.ipoptp_cur;
22176 		optlen = opts.ipoptp_len;
22177 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
22178 		switch (optval) {
22179 		case IPOPT_SSRR:
22180 		case IPOPT_LSRR:
22181 			off = opt[IPOPT_OFFSET];
22182 			/*
22183 			 * If one of the conditions is true, it means
22184 			 * end of options and dst already has the right
22185 			 * value.
22186 			 */
22187 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
22188 				off = optlen - IP_ADDR_LEN;
22189 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
22190 			}
22191 			return (dst);
22192 		default:
22193 			break;
22194 		}
22195 	}
22196 
22197 	return (dst);
22198 }
22199 
22200 mblk_t *
22201 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
22202     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
22203 {
22204 	ipsec_out_t	*io;
22205 	mblk_t		*first_mp;
22206 	boolean_t policy_present;
22207 	ip_stack_t	*ipst;
22208 	ipsec_stack_t	*ipss;
22209 
22210 	ASSERT(ire != NULL);
22211 	ipst = ire->ire_ipst;
22212 	ipss = ipst->ips_netstack->netstack_ipsec;
22213 
22214 	first_mp = mp;
22215 	if (mp->b_datap->db_type == M_CTL) {
22216 		io = (ipsec_out_t *)first_mp->b_rptr;
22217 		/*
22218 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
22219 		 *
22220 		 * 1) There is per-socket policy (including cached global
22221 		 *    policy) or a policy on the IP-in-IP tunnel.
22222 		 * 2) There is no per-socket policy, but it is
22223 		 *    a multicast packet that needs to go out
22224 		 *    on a specific interface. This is the case
22225 		 *    where (ip_wput and ip_wput_multicast) attaches
22226 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
22227 		 *
22228 		 * In case (2) we check with global policy to
22229 		 * see if there is a match and set the ill_index
22230 		 * appropriately so that we can lookup the ire
22231 		 * properly in ip_wput_ipsec_out.
22232 		 */
22233 
22234 		/*
22235 		 * ipsec_out_use_global_policy is set to B_FALSE
22236 		 * in ipsec_in_to_out(). Refer to that function for
22237 		 * details.
22238 		 */
22239 		if ((io->ipsec_out_latch == NULL) &&
22240 		    (io->ipsec_out_use_global_policy)) {
22241 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
22242 			    ire, connp, unspec_src, zoneid));
22243 		}
22244 		if (!io->ipsec_out_secure) {
22245 			/*
22246 			 * If this is not a secure packet, drop
22247 			 * the IPSEC_OUT mp and treat it as a clear
22248 			 * packet. This happens when we are sending
22249 			 * a ICMP reply back to a clear packet. See
22250 			 * ipsec_in_to_out() for details.
22251 			 */
22252 			mp = first_mp->b_cont;
22253 			freeb(first_mp);
22254 		}
22255 		return (mp);
22256 	}
22257 	/*
22258 	 * See whether we need to attach a global policy here. We
22259 	 * don't depend on the conn (as it could be null) for deciding
22260 	 * what policy this datagram should go through because it
22261 	 * should have happened in ip_wput if there was some
22262 	 * policy. This normally happens for connections which are not
22263 	 * fully bound preventing us from caching policies in
22264 	 * ip_bind. Packets coming from the TCP listener/global queue
22265 	 * - which are non-hard_bound - could also be affected by
22266 	 * applying policy here.
22267 	 *
22268 	 * If this packet is coming from tcp global queue or listener,
22269 	 * we will be applying policy here.  This may not be *right*
22270 	 * if these packets are coming from the detached connection as
22271 	 * it could have gone in clear before. This happens only if a
22272 	 * TCP connection started when there is no policy and somebody
22273 	 * added policy before it became detached. Thus packets of the
22274 	 * detached connection could go out secure and the other end
22275 	 * would drop it because it will be expecting in clear. The
22276 	 * converse is not true i.e if somebody starts a TCP
22277 	 * connection and deletes the policy, all the packets will
22278 	 * still go out with the policy that existed before deleting
22279 	 * because ip_unbind sends up policy information which is used
22280 	 * by TCP on subsequent ip_wputs. The right solution is to fix
22281 	 * TCP to attach a dummy IPSEC_OUT and set
22282 	 * ipsec_out_use_global_policy to B_FALSE. As this might
22283 	 * affect performance for normal cases, we are not doing it.
22284 	 * Thus, set policy before starting any TCP connections.
22285 	 *
22286 	 * NOTE - We might apply policy even for a hard bound connection
22287 	 * - for which we cached policy in ip_bind - if somebody added
22288 	 * global policy after we inherited the policy in ip_bind.
22289 	 * This means that the packets that were going out in clear
22290 	 * previously would start going secure and hence get dropped
22291 	 * on the other side. To fix this, TCP attaches a dummy
22292 	 * ipsec_out and make sure that we don't apply global policy.
22293 	 */
22294 	if (ipha != NULL)
22295 		policy_present = ipss->ipsec_outbound_v4_policy_present;
22296 	else
22297 		policy_present = ipss->ipsec_outbound_v6_policy_present;
22298 	if (!policy_present)
22299 		return (mp);
22300 
22301 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
22302 	    zoneid));
22303 }
22304 
22305 ire_t *
22306 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
22307 {
22308 	ipaddr_t addr;
22309 	ire_t *save_ire;
22310 	irb_t *irb;
22311 	ill_group_t *illgrp;
22312 	int	err;
22313 
22314 	save_ire = ire;
22315 	addr = ire->ire_addr;
22316 
22317 	ASSERT(ire->ire_type == IRE_BROADCAST);
22318 
22319 	illgrp = connp->conn_outgoing_ill->ill_group;
22320 	if (illgrp == NULL) {
22321 		*conn_outgoing_ill = conn_get_held_ill(connp,
22322 		    &connp->conn_outgoing_ill, &err);
22323 		if (err == ILL_LOOKUP_FAILED) {
22324 			ire_refrele(save_ire);
22325 			return (NULL);
22326 		}
22327 		return (save_ire);
22328 	}
22329 	/*
22330 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
22331 	 * If it is part of the group, we need to send on the ire
22332 	 * that has been cleared of IRE_MARK_NORECV and that belongs
22333 	 * to this group. This is okay as IP_BOUND_IF really means
22334 	 * any ill in the group. We depend on the fact that the
22335 	 * first ire in the group is always cleared of IRE_MARK_NORECV
22336 	 * if such an ire exists. This is possible only if you have
22337 	 * at least one ill in the group that has not failed.
22338 	 *
22339 	 * First get to the ire that matches the address and group.
22340 	 *
22341 	 * We don't look for an ire with a matching zoneid because a given zone
22342 	 * won't always have broadcast ires on all ills in the group.
22343 	 */
22344 	irb = ire->ire_bucket;
22345 	rw_enter(&irb->irb_lock, RW_READER);
22346 	if (ire->ire_marks & IRE_MARK_NORECV) {
22347 		/*
22348 		 * If the current zone only has an ire broadcast for this
22349 		 * address marked NORECV, the ire we want is ahead in the
22350 		 * bucket, so we look it up deliberately ignoring the zoneid.
22351 		 */
22352 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
22353 			if (ire->ire_addr != addr)
22354 				continue;
22355 			/* skip over deleted ires */
22356 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
22357 				continue;
22358 		}
22359 	}
22360 	while (ire != NULL) {
22361 		/*
22362 		 * If a new interface is coming up, we could end up
22363 		 * seeing the loopback ire and the non-loopback ire
22364 		 * may not have been added yet. So check for ire_stq
22365 		 */
22366 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
22367 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
22368 			break;
22369 		}
22370 		ire = ire->ire_next;
22371 	}
22372 	if (ire != NULL && ire->ire_addr == addr &&
22373 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
22374 		IRE_REFHOLD(ire);
22375 		rw_exit(&irb->irb_lock);
22376 		ire_refrele(save_ire);
22377 		*conn_outgoing_ill = ire_to_ill(ire);
22378 		/*
22379 		 * Refhold the ill to make the conn_outgoing_ill
22380 		 * independent of the ire. ip_wput_ire goes in a loop
22381 		 * and may refrele the ire. Since we have an ire at this
22382 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
22383 		 */
22384 		ill_refhold(*conn_outgoing_ill);
22385 		return (ire);
22386 	}
22387 	rw_exit(&irb->irb_lock);
22388 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
22389 	/*
22390 	 * If we can't find a suitable ire, return the original ire.
22391 	 */
22392 	return (save_ire);
22393 }
22394 
22395 /*
22396  * This function does the ire_refrele of the ire passed in as the
22397  * argument. As this function looks up more ires i.e broadcast ires,
22398  * it needs to REFRELE them. Currently, for simplicity we don't
22399  * differentiate the one passed in and looked up here. We always
22400  * REFRELE.
22401  * IPQoS Notes:
22402  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22403  * IPsec packets are done in ipsec_out_process.
22404  *
22405  */
22406 void
22407 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22408     zoneid_t zoneid)
22409 {
22410 	ipha_t		*ipha;
22411 #define	rptr	((uchar_t *)ipha)
22412 	queue_t		*stq;
22413 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22414 	uint32_t	v_hlen_tos_len;
22415 	uint32_t	ttl_protocol;
22416 	ipaddr_t	src;
22417 	ipaddr_t	dst;
22418 	uint32_t	cksum;
22419 	ipaddr_t	orig_src;
22420 	ire_t		*ire1;
22421 	mblk_t		*next_mp;
22422 	uint_t		hlen;
22423 	uint16_t	*up;
22424 	uint32_t	max_frag = ire->ire_max_frag;
22425 	ill_t		*ill = ire_to_ill(ire);
22426 	int		clusterwide;
22427 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22428 	int		ipsec_len;
22429 	mblk_t		*first_mp;
22430 	ipsec_out_t	*io;
22431 	boolean_t	conn_dontroute;		/* conn value for multicast */
22432 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22433 	boolean_t	multicast_forward;	/* Should we forward ? */
22434 	boolean_t	unspec_src;
22435 	ill_t		*conn_outgoing_ill = NULL;
22436 	ill_t		*ire_ill;
22437 	ill_t		*ire1_ill;
22438 	ill_t		*out_ill;
22439 	uint32_t 	ill_index = 0;
22440 	boolean_t	multirt_send = B_FALSE;
22441 	int		err;
22442 	ipxmit_state_t	pktxmit_state;
22443 	ip_stack_t	*ipst = ire->ire_ipst;
22444 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22445 
22446 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22447 	    "ip_wput_ire_start: q %p", q);
22448 
22449 	multicast_forward = B_FALSE;
22450 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22451 
22452 	if (ire->ire_flags & RTF_MULTIRT) {
22453 		/*
22454 		 * Multirouting case. The bucket where ire is stored
22455 		 * probably holds other RTF_MULTIRT flagged ire
22456 		 * to the destination. In this call to ip_wput_ire,
22457 		 * we attempt to send the packet through all
22458 		 * those ires. Thus, we first ensure that ire is the
22459 		 * first RTF_MULTIRT ire in the bucket,
22460 		 * before walking the ire list.
22461 		 */
22462 		ire_t *first_ire;
22463 		irb_t *irb = ire->ire_bucket;
22464 		ASSERT(irb != NULL);
22465 
22466 		/* Make sure we do not omit any multiroute ire. */
22467 		IRB_REFHOLD(irb);
22468 		for (first_ire = irb->irb_ire;
22469 		    first_ire != NULL;
22470 		    first_ire = first_ire->ire_next) {
22471 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22472 			    (first_ire->ire_addr == ire->ire_addr) &&
22473 			    !(first_ire->ire_marks &
22474 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
22475 				break;
22476 			}
22477 		}
22478 
22479 		if ((first_ire != NULL) && (first_ire != ire)) {
22480 			IRE_REFHOLD(first_ire);
22481 			ire_refrele(ire);
22482 			ire = first_ire;
22483 			ill = ire_to_ill(ire);
22484 		}
22485 		IRB_REFRELE(irb);
22486 	}
22487 
22488 	/*
22489 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22490 	 * for performance we don't grab the mutexs in the fastpath
22491 	 */
22492 	if ((connp != NULL) &&
22493 	    (ire->ire_type == IRE_BROADCAST) &&
22494 	    ((connp->conn_nofailover_ill != NULL) ||
22495 	    (connp->conn_outgoing_ill != NULL))) {
22496 		/*
22497 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22498 		 * option. So, see if this endpoint is bound to a
22499 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22500 		 * that if the interface is failed, we will still send
22501 		 * the packet on the same ill which is what we want.
22502 		 */
22503 		conn_outgoing_ill = conn_get_held_ill(connp,
22504 		    &connp->conn_nofailover_ill, &err);
22505 		if (err == ILL_LOOKUP_FAILED) {
22506 			ire_refrele(ire);
22507 			freemsg(mp);
22508 			return;
22509 		}
22510 		if (conn_outgoing_ill == NULL) {
22511 			/*
22512 			 * Choose a good ill in the group to send the
22513 			 * packets on.
22514 			 */
22515 			ire = conn_set_outgoing_ill(connp, ire,
22516 			    &conn_outgoing_ill);
22517 			if (ire == NULL) {
22518 				freemsg(mp);
22519 				return;
22520 			}
22521 		}
22522 	}
22523 
22524 	if (mp->b_datap->db_type != M_CTL) {
22525 		ipha = (ipha_t *)mp->b_rptr;
22526 	} else {
22527 		io = (ipsec_out_t *)mp->b_rptr;
22528 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22529 		ASSERT(zoneid == io->ipsec_out_zoneid);
22530 		ASSERT(zoneid != ALL_ZONES);
22531 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22532 		dst = ipha->ipha_dst;
22533 		/*
22534 		 * For the multicast case, ipsec_out carries conn_dontroute and
22535 		 * conn_multicast_loop as conn may not be available here. We
22536 		 * need this for multicast loopback and forwarding which is done
22537 		 * later in the code.
22538 		 */
22539 		if (CLASSD(dst)) {
22540 			conn_dontroute = io->ipsec_out_dontroute;
22541 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22542 			/*
22543 			 * If conn_dontroute is not set or conn_multicast_loop
22544 			 * is set, we need to do forwarding/loopback. For
22545 			 * datagrams from ip_wput_multicast, conn_dontroute is
22546 			 * set to B_TRUE and conn_multicast_loop is set to
22547 			 * B_FALSE so that we neither do forwarding nor
22548 			 * loopback.
22549 			 */
22550 			if (!conn_dontroute || conn_multicast_loop)
22551 				multicast_forward = B_TRUE;
22552 		}
22553 	}
22554 
22555 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22556 	    ire->ire_zoneid != ALL_ZONES) {
22557 		/*
22558 		 * When a zone sends a packet to another zone, we try to deliver
22559 		 * the packet under the same conditions as if the destination
22560 		 * was a real node on the network. To do so, we look for a
22561 		 * matching route in the forwarding table.
22562 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22563 		 * ip_newroute() does.
22564 		 * Note that IRE_LOCAL are special, since they are used
22565 		 * when the zoneid doesn't match in some cases. This means that
22566 		 * we need to handle ipha_src differently since ire_src_addr
22567 		 * belongs to the receiving zone instead of the sending zone.
22568 		 * When ip_restrict_interzone_loopback is set, then
22569 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22570 		 * for loopback between zones when the logical "Ethernet" would
22571 		 * have looped them back.
22572 		 */
22573 		ire_t *src_ire;
22574 
22575 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22576 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22577 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22578 		if (src_ire != NULL &&
22579 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22580 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22581 		    ire_local_same_ill_group(ire, src_ire))) {
22582 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22583 				ipha->ipha_src = src_ire->ire_src_addr;
22584 			ire_refrele(src_ire);
22585 		} else {
22586 			ire_refrele(ire);
22587 			if (conn_outgoing_ill != NULL)
22588 				ill_refrele(conn_outgoing_ill);
22589 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22590 			if (src_ire != NULL) {
22591 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22592 					ire_refrele(src_ire);
22593 					freemsg(mp);
22594 					return;
22595 				}
22596 				ire_refrele(src_ire);
22597 			}
22598 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22599 				/* Failed */
22600 				freemsg(mp);
22601 				return;
22602 			}
22603 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22604 			    ipst);
22605 			return;
22606 		}
22607 	}
22608 
22609 	if (mp->b_datap->db_type == M_CTL ||
22610 	    ipss->ipsec_outbound_v4_policy_present) {
22611 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22612 		    unspec_src, zoneid);
22613 		if (mp == NULL) {
22614 			ire_refrele(ire);
22615 			if (conn_outgoing_ill != NULL)
22616 				ill_refrele(conn_outgoing_ill);
22617 			return;
22618 		}
22619 		/*
22620 		 * Trusted Extensions supports all-zones interfaces, so
22621 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22622 		 * the global zone.
22623 		 */
22624 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22625 			io = (ipsec_out_t *)mp->b_rptr;
22626 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22627 			zoneid = io->ipsec_out_zoneid;
22628 		}
22629 	}
22630 
22631 	first_mp = mp;
22632 	ipsec_len = 0;
22633 
22634 	if (first_mp->b_datap->db_type == M_CTL) {
22635 		io = (ipsec_out_t *)first_mp->b_rptr;
22636 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22637 		mp = first_mp->b_cont;
22638 		ipsec_len = ipsec_out_extra_length(first_mp);
22639 		ASSERT(ipsec_len >= 0);
22640 		/* We already picked up the zoneid from the M_CTL above */
22641 		ASSERT(zoneid == io->ipsec_out_zoneid);
22642 		ASSERT(zoneid != ALL_ZONES);
22643 
22644 		/*
22645 		 * Drop M_CTL here if IPsec processing is not needed.
22646 		 * (Non-IPsec use of M_CTL extracted any information it
22647 		 * needed above).
22648 		 */
22649 		if (ipsec_len == 0) {
22650 			freeb(first_mp);
22651 			first_mp = mp;
22652 		}
22653 	}
22654 
22655 	/*
22656 	 * Fast path for ip_wput_ire
22657 	 */
22658 
22659 	ipha = (ipha_t *)mp->b_rptr;
22660 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22661 	dst = ipha->ipha_dst;
22662 
22663 	/*
22664 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22665 	 * if the socket is a SOCK_RAW type. The transport checksum should
22666 	 * be provided in the pre-built packet, so we don't need to compute it.
22667 	 * Also, other application set flags, like DF, should not be altered.
22668 	 * Other transport MUST pass down zero.
22669 	 */
22670 	ip_hdr_included = ipha->ipha_ident;
22671 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22672 
22673 	if (CLASSD(dst)) {
22674 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22675 		    ntohl(dst),
22676 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22677 		    ntohl(ire->ire_addr)));
22678 	}
22679 
22680 /* Macros to extract header fields from data already in registers */
22681 #ifdef	_BIG_ENDIAN
22682 #define	V_HLEN	(v_hlen_tos_len >> 24)
22683 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22684 #define	PROTO	(ttl_protocol & 0xFF)
22685 #else
22686 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22687 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22688 #define	PROTO	(ttl_protocol >> 8)
22689 #endif
22690 
22691 
22692 	orig_src = src = ipha->ipha_src;
22693 	/* (The loop back to "another" is explained down below.) */
22694 another:;
22695 	/*
22696 	 * Assign an ident value for this packet.  We assign idents on
22697 	 * a per destination basis out of the IRE.  There could be
22698 	 * other threads targeting the same destination, so we have to
22699 	 * arrange for a atomic increment.  Note that we use a 32-bit
22700 	 * atomic add because it has better performance than its
22701 	 * 16-bit sibling.
22702 	 *
22703 	 * If running in cluster mode and if the source address
22704 	 * belongs to a replicated service then vector through
22705 	 * cl_inet_ipident vector to allocate ip identifier
22706 	 * NOTE: This is a contract private interface with the
22707 	 * clustering group.
22708 	 */
22709 	clusterwide = 0;
22710 	if (cl_inet_ipident) {
22711 		ASSERT(cl_inet_isclusterwide);
22712 		netstackid_t stack_id = ipst->ips_netstack->netstack_stackid;
22713 
22714 		if ((*cl_inet_isclusterwide)(stack_id, IPPROTO_IP,
22715 		    AF_INET, (uint8_t *)(uintptr_t)src, NULL)) {
22716 			ipha->ipha_ident = (*cl_inet_ipident)(stack_id,
22717 			    IPPROTO_IP, AF_INET, (uint8_t *)(uintptr_t)src,
22718 			    (uint8_t *)(uintptr_t)dst, NULL);
22719 			clusterwide = 1;
22720 		}
22721 	}
22722 	if (!clusterwide) {
22723 		ipha->ipha_ident =
22724 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22725 	}
22726 
22727 #ifndef _BIG_ENDIAN
22728 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22729 #endif
22730 
22731 	/*
22732 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22733 	 * This is needed to obey conn_unspec_src when packets go through
22734 	 * ip_newroute + arp.
22735 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22736 	 */
22737 	if (src == INADDR_ANY && !unspec_src) {
22738 		/*
22739 		 * Assign the appropriate source address from the IRE if none
22740 		 * was specified.
22741 		 */
22742 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22743 
22744 		/*
22745 		 * With IP multipathing, broadcast packets are sent on the ire
22746 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22747 		 * the group. However, this ire might not be in the same zone so
22748 		 * we can't always use its source address. We look for a
22749 		 * broadcast ire in the same group and in the right zone.
22750 		 */
22751 		if (ire->ire_type == IRE_BROADCAST &&
22752 		    ire->ire_zoneid != zoneid) {
22753 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22754 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22755 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22756 			if (src_ire != NULL) {
22757 				src = src_ire->ire_src_addr;
22758 				ire_refrele(src_ire);
22759 			} else {
22760 				ire_refrele(ire);
22761 				if (conn_outgoing_ill != NULL)
22762 					ill_refrele(conn_outgoing_ill);
22763 				freemsg(first_mp);
22764 				if (ill != NULL) {
22765 					BUMP_MIB(ill->ill_ip_mib,
22766 					    ipIfStatsOutDiscards);
22767 				} else {
22768 					BUMP_MIB(&ipst->ips_ip_mib,
22769 					    ipIfStatsOutDiscards);
22770 				}
22771 				return;
22772 			}
22773 		} else {
22774 			src = ire->ire_src_addr;
22775 		}
22776 
22777 		if (connp == NULL) {
22778 			ip1dbg(("ip_wput_ire: no connp and no src "
22779 			    "address for dst 0x%x, using src 0x%x\n",
22780 			    ntohl(dst),
22781 			    ntohl(src)));
22782 		}
22783 		ipha->ipha_src = src;
22784 	}
22785 	stq = ire->ire_stq;
22786 
22787 	/*
22788 	 * We only allow ire chains for broadcasts since there will
22789 	 * be multiple IRE_CACHE entries for the same multicast
22790 	 * address (one per ipif).
22791 	 */
22792 	next_mp = NULL;
22793 
22794 	/* broadcast packet */
22795 	if (ire->ire_type == IRE_BROADCAST)
22796 		goto broadcast;
22797 
22798 	/* loopback ? */
22799 	if (stq == NULL)
22800 		goto nullstq;
22801 
22802 	/* The ill_index for outbound ILL */
22803 	ill_index = Q_TO_INDEX(stq);
22804 
22805 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22806 	ttl_protocol = ((uint16_t *)ipha)[4];
22807 
22808 	/* pseudo checksum (do it in parts for IP header checksum) */
22809 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22810 
22811 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22812 		queue_t *dev_q = stq->q_next;
22813 
22814 		/* flow controlled */
22815 		if (DEV_Q_FLOW_BLOCKED(dev_q))
22816 			goto blocked;
22817 
22818 		if ((PROTO == IPPROTO_UDP) &&
22819 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22820 			hlen = (V_HLEN & 0xF) << 2;
22821 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22822 			if (*up != 0) {
22823 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22824 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22825 				/* Software checksum? */
22826 				if (DB_CKSUMFLAGS(mp) == 0) {
22827 					IP_STAT(ipst, ip_out_sw_cksum);
22828 					IP_STAT_UPDATE(ipst,
22829 					    ip_udp_out_sw_cksum_bytes,
22830 					    LENGTH - hlen);
22831 				}
22832 			}
22833 		}
22834 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22835 		hlen = (V_HLEN & 0xF) << 2;
22836 		if (PROTO == IPPROTO_TCP) {
22837 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22838 			/*
22839 			 * The packet header is processed once and for all, even
22840 			 * in the multirouting case. We disable hardware
22841 			 * checksum if the packet is multirouted, as it will be
22842 			 * replicated via several interfaces, and not all of
22843 			 * them may have this capability.
22844 			 */
22845 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22846 			    LENGTH, max_frag, ipsec_len, cksum);
22847 			/* Software checksum? */
22848 			if (DB_CKSUMFLAGS(mp) == 0) {
22849 				IP_STAT(ipst, ip_out_sw_cksum);
22850 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22851 				    LENGTH - hlen);
22852 			}
22853 		} else {
22854 			sctp_hdr_t	*sctph;
22855 
22856 			ASSERT(PROTO == IPPROTO_SCTP);
22857 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22858 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22859 			/*
22860 			 * Zero out the checksum field to ensure proper
22861 			 * checksum calculation.
22862 			 */
22863 			sctph->sh_chksum = 0;
22864 #ifdef	DEBUG
22865 			if (!skip_sctp_cksum)
22866 #endif
22867 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22868 		}
22869 	}
22870 
22871 	/*
22872 	 * If this is a multicast packet and originated from ip_wput
22873 	 * we need to do loopback and forwarding checks. If it comes
22874 	 * from ip_wput_multicast, we SHOULD not do this.
22875 	 */
22876 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22877 
22878 	/* checksum */
22879 	cksum += ttl_protocol;
22880 
22881 	/* fragment the packet */
22882 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22883 		goto fragmentit;
22884 	/*
22885 	 * Don't use frag_flag if packet is pre-built or source
22886 	 * routed or if multicast (since multicast packets do
22887 	 * not solicit ICMP "packet too big" messages).
22888 	 */
22889 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22890 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22891 	    !ip_source_route_included(ipha)) &&
22892 	    !CLASSD(ipha->ipha_dst))
22893 		ipha->ipha_fragment_offset_and_flags |=
22894 		    htons(ire->ire_frag_flag);
22895 
22896 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22897 		/* calculate IP header checksum */
22898 		cksum += ipha->ipha_ident;
22899 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22900 		cksum += ipha->ipha_fragment_offset_and_flags;
22901 
22902 		/* IP options present */
22903 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22904 		if (hlen)
22905 			goto checksumoptions;
22906 
22907 		/* calculate hdr checksum */
22908 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22909 		cksum = ~(cksum + (cksum >> 16));
22910 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22911 	}
22912 	if (ipsec_len != 0) {
22913 		/*
22914 		 * We will do the rest of the processing after
22915 		 * we come back from IPsec in ip_wput_ipsec_out().
22916 		 */
22917 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22918 
22919 		io = (ipsec_out_t *)first_mp->b_rptr;
22920 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22921 		    ill_phyint->phyint_ifindex;
22922 
22923 		ipsec_out_process(q, first_mp, ire, ill_index);
22924 		ire_refrele(ire);
22925 		if (conn_outgoing_ill != NULL)
22926 			ill_refrele(conn_outgoing_ill);
22927 		return;
22928 	}
22929 
22930 	/*
22931 	 * In most cases, the emission loop below is entered only
22932 	 * once. Only in the case where the ire holds the
22933 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22934 	 * flagged ires in the bucket, and send the packet
22935 	 * through all crossed RTF_MULTIRT routes.
22936 	 */
22937 	if (ire->ire_flags & RTF_MULTIRT) {
22938 		multirt_send = B_TRUE;
22939 	}
22940 	do {
22941 		if (multirt_send) {
22942 			irb_t *irb;
22943 			/*
22944 			 * We are in a multiple send case, need to get
22945 			 * the next ire and make a duplicate of the packet.
22946 			 * ire1 holds here the next ire to process in the
22947 			 * bucket. If multirouting is expected,
22948 			 * any non-RTF_MULTIRT ire that has the
22949 			 * right destination address is ignored.
22950 			 */
22951 			irb = ire->ire_bucket;
22952 			ASSERT(irb != NULL);
22953 
22954 			IRB_REFHOLD(irb);
22955 			for (ire1 = ire->ire_next;
22956 			    ire1 != NULL;
22957 			    ire1 = ire1->ire_next) {
22958 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22959 					continue;
22960 				if (ire1->ire_addr != ire->ire_addr)
22961 					continue;
22962 				if (ire1->ire_marks &
22963 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22964 					continue;
22965 
22966 				/* Got one */
22967 				IRE_REFHOLD(ire1);
22968 				break;
22969 			}
22970 			IRB_REFRELE(irb);
22971 
22972 			if (ire1 != NULL) {
22973 				next_mp = copyb(mp);
22974 				if ((next_mp == NULL) ||
22975 				    ((mp->b_cont != NULL) &&
22976 				    ((next_mp->b_cont =
22977 				    dupmsg(mp->b_cont)) == NULL))) {
22978 					freemsg(next_mp);
22979 					next_mp = NULL;
22980 					ire_refrele(ire1);
22981 					ire1 = NULL;
22982 				}
22983 			}
22984 
22985 			/* Last multiroute ire; don't loop anymore. */
22986 			if (ire1 == NULL) {
22987 				multirt_send = B_FALSE;
22988 			}
22989 		}
22990 
22991 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22992 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22993 		    mblk_t *, mp);
22994 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22995 		    ipst->ips_ipv4firewall_physical_out,
22996 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22997 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22998 
22999 		if (mp == NULL)
23000 			goto release_ire_and_ill;
23001 
23002 		if (ipst->ips_ipobs_enabled) {
23003 			zoneid_t szone;
23004 
23005 			/*
23006 			 * On the outbound path the destination zone will be
23007 			 * unknown as we're sending this packet out on the
23008 			 * wire.
23009 			 */
23010 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
23011 			    ALL_ZONES);
23012 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
23013 			    ire->ire_ipif->ipif_ill, IPV4_VERSION, 0, ipst);
23014 		}
23015 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
23016 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
23017 
23018 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE, connp);
23019 
23020 		if ((pktxmit_state == SEND_FAILED) ||
23021 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23022 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
23023 			    "- packet dropped\n"));
23024 release_ire_and_ill:
23025 			ire_refrele(ire);
23026 			if (next_mp != NULL) {
23027 				freemsg(next_mp);
23028 				ire_refrele(ire1);
23029 			}
23030 			if (conn_outgoing_ill != NULL)
23031 				ill_refrele(conn_outgoing_ill);
23032 			return;
23033 		}
23034 
23035 		if (CLASSD(dst)) {
23036 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
23037 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
23038 			    LENGTH);
23039 		}
23040 
23041 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23042 		    "ip_wput_ire_end: q %p (%S)",
23043 		    q, "last copy out");
23044 		IRE_REFRELE(ire);
23045 
23046 		if (multirt_send) {
23047 			ASSERT(ire1);
23048 			/*
23049 			 * Proceed with the next RTF_MULTIRT ire,
23050 			 * Also set up the send-to queue accordingly.
23051 			 */
23052 			ire = ire1;
23053 			ire1 = NULL;
23054 			stq = ire->ire_stq;
23055 			mp = next_mp;
23056 			next_mp = NULL;
23057 			ipha = (ipha_t *)mp->b_rptr;
23058 			ill_index = Q_TO_INDEX(stq);
23059 			ill = (ill_t *)stq->q_ptr;
23060 		}
23061 	} while (multirt_send);
23062 	if (conn_outgoing_ill != NULL)
23063 		ill_refrele(conn_outgoing_ill);
23064 	return;
23065 
23066 	/*
23067 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
23068 	 */
23069 broadcast:
23070 	{
23071 		/*
23072 		 * To avoid broadcast storms, we usually set the TTL to 1 for
23073 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
23074 		 * can be overridden stack-wide through the ip_broadcast_ttl
23075 		 * ndd tunable, or on a per-connection basis through the
23076 		 * IP_BROADCAST_TTL socket option.
23077 		 *
23078 		 * In the event that we are replying to incoming ICMP packets,
23079 		 * connp could be NULL.
23080 		 */
23081 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
23082 		if (connp != NULL) {
23083 			if (connp->conn_dontroute)
23084 				ipha->ipha_ttl = 1;
23085 			else if (connp->conn_broadcast_ttl != 0)
23086 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
23087 		}
23088 
23089 		/*
23090 		 * Note that we are not doing a IRB_REFHOLD here.
23091 		 * Actually we don't care if the list changes i.e
23092 		 * if somebody deletes an IRE from the list while
23093 		 * we drop the lock, the next time we come around
23094 		 * ire_next will be NULL and hence we won't send
23095 		 * out multiple copies which is fine.
23096 		 */
23097 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
23098 		ire1 = ire->ire_next;
23099 		if (conn_outgoing_ill != NULL) {
23100 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
23101 				ASSERT(ire1 == ire->ire_next);
23102 				if (ire1 != NULL && ire1->ire_addr == dst) {
23103 					ire_refrele(ire);
23104 					ire = ire1;
23105 					IRE_REFHOLD(ire);
23106 					ire1 = ire->ire_next;
23107 					continue;
23108 				}
23109 				rw_exit(&ire->ire_bucket->irb_lock);
23110 				/* Did not find a matching ill */
23111 				ip1dbg(("ip_wput_ire: broadcast with no "
23112 				    "matching IP_BOUND_IF ill %s dst %x\n",
23113 				    conn_outgoing_ill->ill_name, dst));
23114 				freemsg(first_mp);
23115 				if (ire != NULL)
23116 					ire_refrele(ire);
23117 				ill_refrele(conn_outgoing_ill);
23118 				return;
23119 			}
23120 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
23121 			/*
23122 			 * If the next IRE has the same address and is not one
23123 			 * of the two copies that we need to send, try to see
23124 			 * whether this copy should be sent at all. This
23125 			 * assumes that we insert loopbacks first and then
23126 			 * non-loopbacks. This is acheived by inserting the
23127 			 * loopback always before non-loopback.
23128 			 * This is used to send a single copy of a broadcast
23129 			 * packet out all physical interfaces that have an
23130 			 * matching IRE_BROADCAST while also looping
23131 			 * back one copy (to ip_wput_local) for each
23132 			 * matching physical interface. However, we avoid
23133 			 * sending packets out different logical that match by
23134 			 * having ipif_up/ipif_down supress duplicate
23135 			 * IRE_BROADCASTS.
23136 			 *
23137 			 * This feature is currently used to get broadcasts
23138 			 * sent to multiple interfaces, when the broadcast
23139 			 * address being used applies to multiple interfaces.
23140 			 * For example, a whole net broadcast will be
23141 			 * replicated on every connected subnet of
23142 			 * the target net.
23143 			 *
23144 			 * Each zone has its own set of IRE_BROADCASTs, so that
23145 			 * we're able to distribute inbound packets to multiple
23146 			 * zones who share a broadcast address. We avoid looping
23147 			 * back outbound packets in different zones but on the
23148 			 * same ill, as the application would see duplicates.
23149 			 *
23150 			 * If the interfaces are part of the same group,
23151 			 * we would want to send only one copy out for
23152 			 * whole group.
23153 			 *
23154 			 * This logic assumes that ire_add_v4() groups the
23155 			 * IRE_BROADCAST entries so that those with the same
23156 			 * ire_addr and ill_group are kept together.
23157 			 */
23158 			ire_ill = ire->ire_ipif->ipif_ill;
23159 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
23160 				if (ire_ill->ill_group != NULL &&
23161 				    (ire->ire_marks & IRE_MARK_NORECV)) {
23162 					/*
23163 					 * If the current zone only has an ire
23164 					 * broadcast for this address marked
23165 					 * NORECV, the ire we want is ahead in
23166 					 * the bucket, so we look it up
23167 					 * deliberately ignoring the zoneid.
23168 					 */
23169 					for (ire1 = ire->ire_bucket->irb_ire;
23170 					    ire1 != NULL;
23171 					    ire1 = ire1->ire_next) {
23172 						ire1_ill =
23173 						    ire1->ire_ipif->ipif_ill;
23174 						if (ire1->ire_addr != dst)
23175 							continue;
23176 						/* skip over the current ire */
23177 						if (ire1 == ire)
23178 							continue;
23179 						/* skip over deleted ires */
23180 						if (ire1->ire_marks &
23181 						    IRE_MARK_CONDEMNED)
23182 							continue;
23183 						/*
23184 						 * non-loopback ire in our
23185 						 * group: use it for the next
23186 						 * pass in the loop
23187 						 */
23188 						if (ire1->ire_stq != NULL &&
23189 						    ire1_ill->ill_group ==
23190 						    ire_ill->ill_group)
23191 							break;
23192 					}
23193 				}
23194 			} else {
23195 				while (ire1 != NULL && ire1->ire_addr == dst) {
23196 					ire1_ill = ire1->ire_ipif->ipif_ill;
23197 					/*
23198 					 * We can have two broadcast ires on the
23199 					 * same ill in different zones; here
23200 					 * we'll send a copy of the packet on
23201 					 * each ill and the fanout code will
23202 					 * call conn_wantpacket() to check that
23203 					 * the zone has the broadcast address
23204 					 * configured on the ill. If the two
23205 					 * ires are in the same group we only
23206 					 * send one copy up.
23207 					 */
23208 					if (ire1_ill != ire_ill &&
23209 					    (ire1_ill->ill_group == NULL ||
23210 					    ire_ill->ill_group == NULL ||
23211 					    ire1_ill->ill_group !=
23212 					    ire_ill->ill_group)) {
23213 						break;
23214 					}
23215 					ire1 = ire1->ire_next;
23216 				}
23217 			}
23218 		}
23219 		ASSERT(multirt_send == B_FALSE);
23220 		if (ire1 != NULL && ire1->ire_addr == dst) {
23221 			if ((ire->ire_flags & RTF_MULTIRT) &&
23222 			    (ire1->ire_flags & RTF_MULTIRT)) {
23223 				/*
23224 				 * We are in the multirouting case.
23225 				 * The message must be sent at least
23226 				 * on both ires. These ires have been
23227 				 * inserted AFTER the standard ones
23228 				 * in ip_rt_add(). There are thus no
23229 				 * other ire entries for the destination
23230 				 * address in the rest of the bucket
23231 				 * that do not have the RTF_MULTIRT
23232 				 * flag. We don't process a copy
23233 				 * of the message here. This will be
23234 				 * done in the final sending loop.
23235 				 */
23236 				multirt_send = B_TRUE;
23237 			} else {
23238 				next_mp = ip_copymsg(first_mp);
23239 				if (next_mp != NULL)
23240 					IRE_REFHOLD(ire1);
23241 			}
23242 		}
23243 		rw_exit(&ire->ire_bucket->irb_lock);
23244 	}
23245 
23246 	if (stq) {
23247 		/*
23248 		 * A non-NULL send-to queue means this packet is going
23249 		 * out of this machine.
23250 		 */
23251 		out_ill = (ill_t *)stq->q_ptr;
23252 
23253 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
23254 		ttl_protocol = ((uint16_t *)ipha)[4];
23255 		/*
23256 		 * We accumulate the pseudo header checksum in cksum.
23257 		 * This is pretty hairy code, so watch close.  One
23258 		 * thing to keep in mind is that UDP and TCP have
23259 		 * stored their respective datagram lengths in their
23260 		 * checksum fields.  This lines things up real nice.
23261 		 */
23262 		cksum = (dst >> 16) + (dst & 0xFFFF) +
23263 		    (src >> 16) + (src & 0xFFFF);
23264 		/*
23265 		 * We assume the udp checksum field contains the
23266 		 * length, so to compute the pseudo header checksum,
23267 		 * all we need is the protocol number and src/dst.
23268 		 */
23269 		/* Provide the checksums for UDP and TCP. */
23270 		if ((PROTO == IPPROTO_TCP) &&
23271 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
23272 			/* hlen gets the number of uchar_ts in the IP header */
23273 			hlen = (V_HLEN & 0xF) << 2;
23274 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
23275 			IP_STAT(ipst, ip_out_sw_cksum);
23276 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
23277 			    LENGTH - hlen);
23278 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
23279 		} else if (PROTO == IPPROTO_SCTP &&
23280 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
23281 			sctp_hdr_t	*sctph;
23282 
23283 			hlen = (V_HLEN & 0xF) << 2;
23284 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
23285 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
23286 			sctph->sh_chksum = 0;
23287 #ifdef	DEBUG
23288 			if (!skip_sctp_cksum)
23289 #endif
23290 				sctph->sh_chksum = sctp_cksum(mp, hlen);
23291 		} else {
23292 			queue_t	*dev_q = stq->q_next;
23293 
23294 			if (DEV_Q_FLOW_BLOCKED(dev_q)) {
23295 blocked:
23296 				ipha->ipha_ident = ip_hdr_included;
23297 				/*
23298 				 * If we don't have a conn to apply
23299 				 * backpressure, free the message.
23300 				 * In the ire_send path, we don't know
23301 				 * the position to requeue the packet. Rather
23302 				 * than reorder packets, we just drop this
23303 				 * packet.
23304 				 */
23305 				if (ipst->ips_ip_output_queue &&
23306 				    connp != NULL &&
23307 				    caller != IRE_SEND) {
23308 					if (caller == IP_WSRV) {
23309 						connp->conn_did_putbq = 1;
23310 						(void) putbq(connp->conn_wq,
23311 						    first_mp);
23312 						conn_drain_insert(connp);
23313 						/*
23314 						 * This is the service thread,
23315 						 * and the queue is already
23316 						 * noenabled. The check for
23317 						 * canput and the putbq is not
23318 						 * atomic. So we need to check
23319 						 * again.
23320 						 */
23321 						if (canput(stq->q_next))
23322 							connp->conn_did_putbq
23323 							    = 0;
23324 						IP_STAT(ipst, ip_conn_flputbq);
23325 					} else {
23326 						/*
23327 						 * We are not the service proc.
23328 						 * ip_wsrv will be scheduled or
23329 						 * is already running.
23330 						 */
23331 
23332 						(void) putq(connp->conn_wq,
23333 						    first_mp);
23334 					}
23335 				} else {
23336 					out_ill = (ill_t *)stq->q_ptr;
23337 					BUMP_MIB(out_ill->ill_ip_mib,
23338 					    ipIfStatsOutDiscards);
23339 					freemsg(first_mp);
23340 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23341 					    "ip_wput_ire_end: q %p (%S)",
23342 					    q, "discard");
23343 				}
23344 				ire_refrele(ire);
23345 				if (next_mp) {
23346 					ire_refrele(ire1);
23347 					freemsg(next_mp);
23348 				}
23349 				if (conn_outgoing_ill != NULL)
23350 					ill_refrele(conn_outgoing_ill);
23351 				return;
23352 			}
23353 			if ((PROTO == IPPROTO_UDP) &&
23354 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
23355 				/*
23356 				 * hlen gets the number of uchar_ts in the
23357 				 * IP header
23358 				 */
23359 				hlen = (V_HLEN & 0xF) << 2;
23360 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
23361 				max_frag = ire->ire_max_frag;
23362 				if (*up != 0) {
23363 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
23364 					    up, PROTO, hlen, LENGTH, max_frag,
23365 					    ipsec_len, cksum);
23366 					/* Software checksum? */
23367 					if (DB_CKSUMFLAGS(mp) == 0) {
23368 						IP_STAT(ipst, ip_out_sw_cksum);
23369 						IP_STAT_UPDATE(ipst,
23370 						    ip_udp_out_sw_cksum_bytes,
23371 						    LENGTH - hlen);
23372 					}
23373 				}
23374 			}
23375 		}
23376 		/*
23377 		 * Need to do this even when fragmenting. The local
23378 		 * loopback can be done without computing checksums
23379 		 * but forwarding out other interface must be done
23380 		 * after the IP checksum (and ULP checksums) have been
23381 		 * computed.
23382 		 *
23383 		 * NOTE : multicast_forward is set only if this packet
23384 		 * originated from ip_wput. For packets originating from
23385 		 * ip_wput_multicast, it is not set.
23386 		 */
23387 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23388 multi_loopback:
23389 			ip2dbg(("ip_wput: multicast, loop %d\n",
23390 			    conn_multicast_loop));
23391 
23392 			/*  Forget header checksum offload */
23393 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23394 
23395 			/*
23396 			 * Local loopback of multicasts?  Check the
23397 			 * ill.
23398 			 *
23399 			 * Note that the loopback function will not come
23400 			 * in through ip_rput - it will only do the
23401 			 * client fanout thus we need to do an mforward
23402 			 * as well.  The is different from the BSD
23403 			 * logic.
23404 			 */
23405 			if (ill != NULL) {
23406 				ilm_t	*ilm;
23407 
23408 				ILM_WALKER_HOLD(ill);
23409 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
23410 				    ALL_ZONES);
23411 				ILM_WALKER_RELE(ill);
23412 				if (ilm != NULL) {
23413 					/*
23414 					 * Pass along the virtual output q.
23415 					 * ip_wput_local() will distribute the
23416 					 * packet to all the matching zones,
23417 					 * except the sending zone when
23418 					 * IP_MULTICAST_LOOP is false.
23419 					 */
23420 					ip_multicast_loopback(q, ill, first_mp,
23421 					    conn_multicast_loop ? 0 :
23422 					    IP_FF_NO_MCAST_LOOP, zoneid);
23423 				}
23424 			}
23425 			if (ipha->ipha_ttl == 0) {
23426 				/*
23427 				 * 0 => only to this host i.e. we are
23428 				 * done. We are also done if this was the
23429 				 * loopback interface since it is sufficient
23430 				 * to loopback one copy of a multicast packet.
23431 				 */
23432 				freemsg(first_mp);
23433 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23434 				    "ip_wput_ire_end: q %p (%S)",
23435 				    q, "loopback");
23436 				ire_refrele(ire);
23437 				if (conn_outgoing_ill != NULL)
23438 					ill_refrele(conn_outgoing_ill);
23439 				return;
23440 			}
23441 			/*
23442 			 * ILLF_MULTICAST is checked in ip_newroute
23443 			 * i.e. we don't need to check it here since
23444 			 * all IRE_CACHEs come from ip_newroute.
23445 			 * For multicast traffic, SO_DONTROUTE is interpreted
23446 			 * to mean only send the packet out the interface
23447 			 * (optionally specified with IP_MULTICAST_IF)
23448 			 * and do not forward it out additional interfaces.
23449 			 * RSVP and the rsvp daemon is an example of a
23450 			 * protocol and user level process that
23451 			 * handles it's own routing. Hence, it uses the
23452 			 * SO_DONTROUTE option to accomplish this.
23453 			 */
23454 
23455 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23456 			    ill != NULL) {
23457 				/* Unconditionally redo the checksum */
23458 				ipha->ipha_hdr_checksum = 0;
23459 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23460 
23461 				/*
23462 				 * If this needs to go out secure, we need
23463 				 * to wait till we finish the IPsec
23464 				 * processing.
23465 				 */
23466 				if (ipsec_len == 0 &&
23467 				    ip_mforward(ill, ipha, mp)) {
23468 					freemsg(first_mp);
23469 					ip1dbg(("ip_wput: mforward failed\n"));
23470 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23471 					    "ip_wput_ire_end: q %p (%S)",
23472 					    q, "mforward failed");
23473 					ire_refrele(ire);
23474 					if (conn_outgoing_ill != NULL)
23475 						ill_refrele(conn_outgoing_ill);
23476 					return;
23477 				}
23478 			}
23479 		}
23480 		max_frag = ire->ire_max_frag;
23481 		cksum += ttl_protocol;
23482 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23483 			/* No fragmentation required for this one. */
23484 			/*
23485 			 * Don't use frag_flag if packet is pre-built or source
23486 			 * routed or if multicast (since multicast packets do
23487 			 * not solicit ICMP "packet too big" messages).
23488 			 */
23489 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23490 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23491 			    !ip_source_route_included(ipha)) &&
23492 			    !CLASSD(ipha->ipha_dst))
23493 				ipha->ipha_fragment_offset_and_flags |=
23494 				    htons(ire->ire_frag_flag);
23495 
23496 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23497 				/* Complete the IP header checksum. */
23498 				cksum += ipha->ipha_ident;
23499 				cksum += (v_hlen_tos_len >> 16)+
23500 				    (v_hlen_tos_len & 0xFFFF);
23501 				cksum += ipha->ipha_fragment_offset_and_flags;
23502 				hlen = (V_HLEN & 0xF) -
23503 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23504 				if (hlen) {
23505 checksumoptions:
23506 					/*
23507 					 * Account for the IP Options in the IP
23508 					 * header checksum.
23509 					 */
23510 					up = (uint16_t *)(rptr+
23511 					    IP_SIMPLE_HDR_LENGTH);
23512 					do {
23513 						cksum += up[0];
23514 						cksum += up[1];
23515 						up += 2;
23516 					} while (--hlen);
23517 				}
23518 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23519 				cksum = ~(cksum + (cksum >> 16));
23520 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23521 			}
23522 			if (ipsec_len != 0) {
23523 				ipsec_out_process(q, first_mp, ire, ill_index);
23524 				if (!next_mp) {
23525 					ire_refrele(ire);
23526 					if (conn_outgoing_ill != NULL)
23527 						ill_refrele(conn_outgoing_ill);
23528 					return;
23529 				}
23530 				goto next;
23531 			}
23532 
23533 			/*
23534 			 * multirt_send has already been handled
23535 			 * for broadcast, but not yet for multicast
23536 			 * or IP options.
23537 			 */
23538 			if (next_mp == NULL) {
23539 				if (ire->ire_flags & RTF_MULTIRT) {
23540 					multirt_send = B_TRUE;
23541 				}
23542 			}
23543 
23544 			/*
23545 			 * In most cases, the emission loop below is
23546 			 * entered only once. Only in the case where
23547 			 * the ire holds the RTF_MULTIRT flag, do we loop
23548 			 * to process all RTF_MULTIRT ires in the bucket,
23549 			 * and send the packet through all crossed
23550 			 * RTF_MULTIRT routes.
23551 			 */
23552 			do {
23553 				if (multirt_send) {
23554 					irb_t *irb;
23555 
23556 					irb = ire->ire_bucket;
23557 					ASSERT(irb != NULL);
23558 					/*
23559 					 * We are in a multiple send case,
23560 					 * need to get the next IRE and make
23561 					 * a duplicate of the packet.
23562 					 */
23563 					IRB_REFHOLD(irb);
23564 					for (ire1 = ire->ire_next;
23565 					    ire1 != NULL;
23566 					    ire1 = ire1->ire_next) {
23567 						if (!(ire1->ire_flags &
23568 						    RTF_MULTIRT)) {
23569 							continue;
23570 						}
23571 						if (ire1->ire_addr !=
23572 						    ire->ire_addr) {
23573 							continue;
23574 						}
23575 						if (ire1->ire_marks &
23576 						    (IRE_MARK_CONDEMNED|
23577 						    IRE_MARK_HIDDEN)) {
23578 							continue;
23579 						}
23580 
23581 						/* Got one */
23582 						IRE_REFHOLD(ire1);
23583 						break;
23584 					}
23585 					IRB_REFRELE(irb);
23586 
23587 					if (ire1 != NULL) {
23588 						next_mp = copyb(mp);
23589 						if ((next_mp == NULL) ||
23590 						    ((mp->b_cont != NULL) &&
23591 						    ((next_mp->b_cont =
23592 						    dupmsg(mp->b_cont))
23593 						    == NULL))) {
23594 							freemsg(next_mp);
23595 							next_mp = NULL;
23596 							ire_refrele(ire1);
23597 							ire1 = NULL;
23598 						}
23599 					}
23600 
23601 					/*
23602 					 * Last multiroute ire; don't loop
23603 					 * anymore. The emission is over
23604 					 * and next_mp is NULL.
23605 					 */
23606 					if (ire1 == NULL) {
23607 						multirt_send = B_FALSE;
23608 					}
23609 				}
23610 
23611 				out_ill = ire_to_ill(ire);
23612 				DTRACE_PROBE4(ip4__physical__out__start,
23613 				    ill_t *, NULL,
23614 				    ill_t *, out_ill,
23615 				    ipha_t *, ipha, mblk_t *, mp);
23616 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23617 				    ipst->ips_ipv4firewall_physical_out,
23618 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23619 				DTRACE_PROBE1(ip4__physical__out__end,
23620 				    mblk_t *, mp);
23621 				if (mp == NULL)
23622 					goto release_ire_and_ill_2;
23623 
23624 				ASSERT(ipsec_len == 0);
23625 				mp->b_prev =
23626 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23627 				DTRACE_PROBE2(ip__xmit__2,
23628 				    mblk_t *, mp, ire_t *, ire);
23629 				pktxmit_state = ip_xmit_v4(mp, ire,
23630 				    NULL, B_TRUE, connp);
23631 				if ((pktxmit_state == SEND_FAILED) ||
23632 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23633 release_ire_and_ill_2:
23634 					if (next_mp) {
23635 						freemsg(next_mp);
23636 						ire_refrele(ire1);
23637 					}
23638 					ire_refrele(ire);
23639 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23640 					    "ip_wput_ire_end: q %p (%S)",
23641 					    q, "discard MDATA");
23642 					if (conn_outgoing_ill != NULL)
23643 						ill_refrele(conn_outgoing_ill);
23644 					return;
23645 				}
23646 
23647 				if (CLASSD(dst)) {
23648 					BUMP_MIB(out_ill->ill_ip_mib,
23649 					    ipIfStatsHCOutMcastPkts);
23650 					UPDATE_MIB(out_ill->ill_ip_mib,
23651 					    ipIfStatsHCOutMcastOctets,
23652 					    LENGTH);
23653 				} else if (ire->ire_type == IRE_BROADCAST) {
23654 					BUMP_MIB(out_ill->ill_ip_mib,
23655 					    ipIfStatsHCOutBcastPkts);
23656 				}
23657 
23658 				if (multirt_send) {
23659 					/*
23660 					 * We are in a multiple send case,
23661 					 * need to re-enter the sending loop
23662 					 * using the next ire.
23663 					 */
23664 					ire_refrele(ire);
23665 					ire = ire1;
23666 					stq = ire->ire_stq;
23667 					mp = next_mp;
23668 					next_mp = NULL;
23669 					ipha = (ipha_t *)mp->b_rptr;
23670 					ill_index = Q_TO_INDEX(stq);
23671 				}
23672 			} while (multirt_send);
23673 
23674 			if (!next_mp) {
23675 				/*
23676 				 * Last copy going out (the ultra-common
23677 				 * case).  Note that we intentionally replicate
23678 				 * the putnext rather than calling it before
23679 				 * the next_mp check in hopes of a little
23680 				 * tail-call action out of the compiler.
23681 				 */
23682 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23683 				    "ip_wput_ire_end: q %p (%S)",
23684 				    q, "last copy out(1)");
23685 				ire_refrele(ire);
23686 				if (conn_outgoing_ill != NULL)
23687 					ill_refrele(conn_outgoing_ill);
23688 				return;
23689 			}
23690 			/* More copies going out below. */
23691 		} else {
23692 			int offset;
23693 fragmentit:
23694 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23695 			/*
23696 			 * If this would generate a icmp_frag_needed message,
23697 			 * we need to handle it before we do the IPsec
23698 			 * processing. Otherwise, we need to strip the IPsec
23699 			 * headers before we send up the message to the ULPs
23700 			 * which becomes messy and difficult.
23701 			 */
23702 			if (ipsec_len != 0) {
23703 				if ((max_frag < (unsigned int)(LENGTH +
23704 				    ipsec_len)) && (offset & IPH_DF)) {
23705 					out_ill = (ill_t *)stq->q_ptr;
23706 					BUMP_MIB(out_ill->ill_ip_mib,
23707 					    ipIfStatsOutFragFails);
23708 					BUMP_MIB(out_ill->ill_ip_mib,
23709 					    ipIfStatsOutFragReqds);
23710 					ipha->ipha_hdr_checksum = 0;
23711 					ipha->ipha_hdr_checksum =
23712 					    (uint16_t)ip_csum_hdr(ipha);
23713 					icmp_frag_needed(ire->ire_stq, first_mp,
23714 					    max_frag, zoneid, ipst);
23715 					if (!next_mp) {
23716 						ire_refrele(ire);
23717 						if (conn_outgoing_ill != NULL) {
23718 							ill_refrele(
23719 							    conn_outgoing_ill);
23720 						}
23721 						return;
23722 					}
23723 				} else {
23724 					/*
23725 					 * This won't cause a icmp_frag_needed
23726 					 * message. to be generated. Send it on
23727 					 * the wire. Note that this could still
23728 					 * cause fragmentation and all we
23729 					 * do is the generation of the message
23730 					 * to the ULP if needed before IPsec.
23731 					 */
23732 					if (!next_mp) {
23733 						ipsec_out_process(q, first_mp,
23734 						    ire, ill_index);
23735 						TRACE_2(TR_FAC_IP,
23736 						    TR_IP_WPUT_IRE_END,
23737 						    "ip_wput_ire_end: q %p "
23738 						    "(%S)", q,
23739 						    "last ipsec_out_process");
23740 						ire_refrele(ire);
23741 						if (conn_outgoing_ill != NULL) {
23742 							ill_refrele(
23743 							    conn_outgoing_ill);
23744 						}
23745 						return;
23746 					}
23747 					ipsec_out_process(q, first_mp,
23748 					    ire, ill_index);
23749 				}
23750 			} else {
23751 				/*
23752 				 * Initiate IPPF processing. For
23753 				 * fragmentable packets we finish
23754 				 * all QOS packet processing before
23755 				 * calling:
23756 				 * ip_wput_ire_fragmentit->ip_wput_frag
23757 				 */
23758 
23759 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23760 					ip_process(IPP_LOCAL_OUT, &mp,
23761 					    ill_index);
23762 					if (mp == NULL) {
23763 						out_ill = (ill_t *)stq->q_ptr;
23764 						BUMP_MIB(out_ill->ill_ip_mib,
23765 						    ipIfStatsOutDiscards);
23766 						if (next_mp != NULL) {
23767 							freemsg(next_mp);
23768 							ire_refrele(ire1);
23769 						}
23770 						ire_refrele(ire);
23771 						TRACE_2(TR_FAC_IP,
23772 						    TR_IP_WPUT_IRE_END,
23773 						    "ip_wput_ire: q %p (%S)",
23774 						    q, "discard MDATA");
23775 						if (conn_outgoing_ill != NULL) {
23776 							ill_refrele(
23777 							    conn_outgoing_ill);
23778 						}
23779 						return;
23780 					}
23781 				}
23782 				if (!next_mp) {
23783 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23784 					    "ip_wput_ire_end: q %p (%S)",
23785 					    q, "last fragmentation");
23786 					ip_wput_ire_fragmentit(mp, ire,
23787 					    zoneid, ipst, connp);
23788 					ire_refrele(ire);
23789 					if (conn_outgoing_ill != NULL)
23790 						ill_refrele(conn_outgoing_ill);
23791 					return;
23792 				}
23793 				ip_wput_ire_fragmentit(mp, ire,
23794 				    zoneid, ipst, connp);
23795 			}
23796 		}
23797 	} else {
23798 nullstq:
23799 		/* A NULL stq means the destination address is local. */
23800 		UPDATE_OB_PKT_COUNT(ire);
23801 		ire->ire_last_used_time = lbolt;
23802 		ASSERT(ire->ire_ipif != NULL);
23803 		if (!next_mp) {
23804 			/*
23805 			 * Is there an "in" and "out" for traffic local
23806 			 * to a host (loopback)?  The code in Solaris doesn't
23807 			 * explicitly draw a line in its code for in vs out,
23808 			 * so we've had to draw a line in the sand: ip_wput_ire
23809 			 * is considered to be the "output" side and
23810 			 * ip_wput_local to be the "input" side.
23811 			 */
23812 			out_ill = ire_to_ill(ire);
23813 
23814 			/*
23815 			 * DTrace this as ip:::send.  A blocked packet will
23816 			 * fire the send probe, but not the receive probe.
23817 			 */
23818 			DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23819 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23820 			    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23821 
23822 			DTRACE_PROBE4(ip4__loopback__out__start,
23823 			    ill_t *, NULL, ill_t *, out_ill,
23824 			    ipha_t *, ipha, mblk_t *, first_mp);
23825 
23826 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23827 			    ipst->ips_ipv4firewall_loopback_out,
23828 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23829 
23830 			DTRACE_PROBE1(ip4__loopback__out_end,
23831 			    mblk_t *, first_mp);
23832 
23833 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23834 			    "ip_wput_ire_end: q %p (%S)",
23835 			    q, "local address");
23836 
23837 			if (first_mp != NULL)
23838 				ip_wput_local(q, out_ill, ipha,
23839 				    first_mp, ire, 0, ire->ire_zoneid);
23840 			ire_refrele(ire);
23841 			if (conn_outgoing_ill != NULL)
23842 				ill_refrele(conn_outgoing_ill);
23843 			return;
23844 		}
23845 
23846 		out_ill = ire_to_ill(ire);
23847 
23848 		/*
23849 		 * DTrace this as ip:::send.  A blocked packet will fire the
23850 		 * send probe, but not the receive probe.
23851 		 */
23852 		DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23853 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23854 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23855 
23856 		DTRACE_PROBE4(ip4__loopback__out__start,
23857 		    ill_t *, NULL, ill_t *, out_ill,
23858 		    ipha_t *, ipha, mblk_t *, first_mp);
23859 
23860 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23861 		    ipst->ips_ipv4firewall_loopback_out,
23862 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23863 
23864 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23865 
23866 		if (first_mp != NULL)
23867 			ip_wput_local(q, out_ill, ipha,
23868 			    first_mp, ire, 0, ire->ire_zoneid);
23869 	}
23870 next:
23871 	/*
23872 	 * More copies going out to additional interfaces.
23873 	 * ire1 has already been held. We don't need the
23874 	 * "ire" anymore.
23875 	 */
23876 	ire_refrele(ire);
23877 	ire = ire1;
23878 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23879 	mp = next_mp;
23880 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23881 	ill = ire_to_ill(ire);
23882 	first_mp = mp;
23883 	if (ipsec_len != 0) {
23884 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23885 		mp = mp->b_cont;
23886 	}
23887 	dst = ire->ire_addr;
23888 	ipha = (ipha_t *)mp->b_rptr;
23889 	/*
23890 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23891 	 * Restore ipha_ident "no checksum" flag.
23892 	 */
23893 	src = orig_src;
23894 	ipha->ipha_ident = ip_hdr_included;
23895 	goto another;
23896 
23897 #undef	rptr
23898 #undef	Q_TO_INDEX
23899 }
23900 
23901 /*
23902  * Routine to allocate a message that is used to notify the ULP about MDT.
23903  * The caller may provide a pointer to the link-layer MDT capabilities,
23904  * or NULL if MDT is to be disabled on the stream.
23905  */
23906 mblk_t *
23907 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23908 {
23909 	mblk_t *mp;
23910 	ip_mdt_info_t *mdti;
23911 	ill_mdt_capab_t *idst;
23912 
23913 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23914 		DB_TYPE(mp) = M_CTL;
23915 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23916 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23917 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23918 		idst = &(mdti->mdt_capab);
23919 
23920 		/*
23921 		 * If the caller provides us with the capability, copy
23922 		 * it over into our notification message; otherwise
23923 		 * we zero out the capability portion.
23924 		 */
23925 		if (isrc != NULL)
23926 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23927 		else
23928 			bzero((caddr_t)idst, sizeof (*idst));
23929 	}
23930 	return (mp);
23931 }
23932 
23933 /*
23934  * Routine which determines whether MDT can be enabled on the destination
23935  * IRE and IPC combination, and if so, allocates and returns the MDT
23936  * notification mblk that may be used by ULP.  We also check if we need to
23937  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23938  * MDT usage in the past have been lifted.  This gets called during IP
23939  * and ULP binding.
23940  */
23941 mblk_t *
23942 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23943     ill_mdt_capab_t *mdt_cap)
23944 {
23945 	mblk_t *mp;
23946 	boolean_t rc = B_FALSE;
23947 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23948 
23949 	ASSERT(dst_ire != NULL);
23950 	ASSERT(connp != NULL);
23951 	ASSERT(mdt_cap != NULL);
23952 
23953 	/*
23954 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23955 	 * Multidata, which is handled in tcp_multisend().  This
23956 	 * is the reason why we do all these checks here, to ensure
23957 	 * that we don't enable Multidata for the cases which we
23958 	 * can't handle at the moment.
23959 	 */
23960 	do {
23961 		/* Only do TCP at the moment */
23962 		if (connp->conn_ulp != IPPROTO_TCP)
23963 			break;
23964 
23965 		/*
23966 		 * IPsec outbound policy present?  Note that we get here
23967 		 * after calling ipsec_conn_cache_policy() where the global
23968 		 * policy checking is performed.  conn_latch will be
23969 		 * non-NULL as long as there's a policy defined,
23970 		 * i.e. conn_out_enforce_policy may be NULL in such case
23971 		 * when the connection is non-secure, and hence we check
23972 		 * further if the latch refers to an outbound policy.
23973 		 */
23974 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23975 			break;
23976 
23977 		/* CGTP (multiroute) is enabled? */
23978 		if (dst_ire->ire_flags & RTF_MULTIRT)
23979 			break;
23980 
23981 		/* Outbound IPQoS enabled? */
23982 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23983 			/*
23984 			 * In this case, we disable MDT for this and all
23985 			 * future connections going over the interface.
23986 			 */
23987 			mdt_cap->ill_mdt_on = 0;
23988 			break;
23989 		}
23990 
23991 		/* socket option(s) present? */
23992 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23993 			break;
23994 
23995 		rc = B_TRUE;
23996 	/* CONSTCOND */
23997 	} while (0);
23998 
23999 	/* Remember the result */
24000 	connp->conn_mdt_ok = rc;
24001 
24002 	if (!rc)
24003 		return (NULL);
24004 	else if (!mdt_cap->ill_mdt_on) {
24005 		/*
24006 		 * If MDT has been previously turned off in the past, and we
24007 		 * currently can do MDT (due to IPQoS policy removal, etc.)
24008 		 * then enable it for this interface.
24009 		 */
24010 		mdt_cap->ill_mdt_on = 1;
24011 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
24012 		    "interface %s\n", ill_name));
24013 	}
24014 
24015 	/* Allocate the MDT info mblk */
24016 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
24017 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
24018 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
24019 		return (NULL);
24020 	}
24021 	return (mp);
24022 }
24023 
24024 /*
24025  * Routine to allocate a message that is used to notify the ULP about LSO.
24026  * The caller may provide a pointer to the link-layer LSO capabilities,
24027  * or NULL if LSO is to be disabled on the stream.
24028  */
24029 mblk_t *
24030 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
24031 {
24032 	mblk_t *mp;
24033 	ip_lso_info_t *lsoi;
24034 	ill_lso_capab_t *idst;
24035 
24036 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
24037 		DB_TYPE(mp) = M_CTL;
24038 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
24039 		lsoi = (ip_lso_info_t *)mp->b_rptr;
24040 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
24041 		idst = &(lsoi->lso_capab);
24042 
24043 		/*
24044 		 * If the caller provides us with the capability, copy
24045 		 * it over into our notification message; otherwise
24046 		 * we zero out the capability portion.
24047 		 */
24048 		if (isrc != NULL)
24049 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
24050 		else
24051 			bzero((caddr_t)idst, sizeof (*idst));
24052 	}
24053 	return (mp);
24054 }
24055 
24056 /*
24057  * Routine which determines whether LSO can be enabled on the destination
24058  * IRE and IPC combination, and if so, allocates and returns the LSO
24059  * notification mblk that may be used by ULP.  We also check if we need to
24060  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
24061  * LSO usage in the past have been lifted.  This gets called during IP
24062  * and ULP binding.
24063  */
24064 mblk_t *
24065 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
24066     ill_lso_capab_t *lso_cap)
24067 {
24068 	mblk_t *mp;
24069 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
24070 
24071 	ASSERT(dst_ire != NULL);
24072 	ASSERT(connp != NULL);
24073 	ASSERT(lso_cap != NULL);
24074 
24075 	connp->conn_lso_ok = B_TRUE;
24076 
24077 	if ((connp->conn_ulp != IPPROTO_TCP) ||
24078 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
24079 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
24080 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
24081 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
24082 		connp->conn_lso_ok = B_FALSE;
24083 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
24084 			/*
24085 			 * Disable LSO for this and all future connections going
24086 			 * over the interface.
24087 			 */
24088 			lso_cap->ill_lso_on = 0;
24089 		}
24090 	}
24091 
24092 	if (!connp->conn_lso_ok)
24093 		return (NULL);
24094 	else if (!lso_cap->ill_lso_on) {
24095 		/*
24096 		 * If LSO has been previously turned off in the past, and we
24097 		 * currently can do LSO (due to IPQoS policy removal, etc.)
24098 		 * then enable it for this interface.
24099 		 */
24100 		lso_cap->ill_lso_on = 1;
24101 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
24102 		    ill_name));
24103 	}
24104 
24105 	/* Allocate the LSO info mblk */
24106 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
24107 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
24108 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
24109 
24110 	return (mp);
24111 }
24112 
24113 /*
24114  * Create destination address attribute, and fill it with the physical
24115  * destination address and SAP taken from the template DL_UNITDATA_REQ
24116  * message block.
24117  */
24118 boolean_t
24119 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
24120 {
24121 	dl_unitdata_req_t *dlurp;
24122 	pattr_t *pa;
24123 	pattrinfo_t pa_info;
24124 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
24125 	uint_t das_len, das_off;
24126 
24127 	ASSERT(dlmp != NULL);
24128 
24129 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
24130 	das_len = dlurp->dl_dest_addr_length;
24131 	das_off = dlurp->dl_dest_addr_offset;
24132 
24133 	pa_info.type = PATTR_DSTADDRSAP;
24134 	pa_info.len = sizeof (**das) + das_len - 1;
24135 
24136 	/* create and associate the attribute */
24137 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
24138 	if (pa != NULL) {
24139 		ASSERT(*das != NULL);
24140 		(*das)->addr_is_group = 0;
24141 		(*das)->addr_len = (uint8_t)das_len;
24142 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
24143 	}
24144 
24145 	return (pa != NULL);
24146 }
24147 
24148 /*
24149  * Create hardware checksum attribute and fill it with the values passed.
24150  */
24151 boolean_t
24152 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
24153     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
24154 {
24155 	pattr_t *pa;
24156 	pattrinfo_t pa_info;
24157 
24158 	ASSERT(mmd != NULL);
24159 
24160 	pa_info.type = PATTR_HCKSUM;
24161 	pa_info.len = sizeof (pattr_hcksum_t);
24162 
24163 	/* create and associate the attribute */
24164 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
24165 	if (pa != NULL) {
24166 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
24167 
24168 		hck->hcksum_start_offset = start_offset;
24169 		hck->hcksum_stuff_offset = stuff_offset;
24170 		hck->hcksum_end_offset = end_offset;
24171 		hck->hcksum_flags = flags;
24172 	}
24173 	return (pa != NULL);
24174 }
24175 
24176 /*
24177  * Create zerocopy attribute and fill it with the specified flags
24178  */
24179 boolean_t
24180 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
24181 {
24182 	pattr_t *pa;
24183 	pattrinfo_t pa_info;
24184 
24185 	ASSERT(mmd != NULL);
24186 	pa_info.type = PATTR_ZCOPY;
24187 	pa_info.len = sizeof (pattr_zcopy_t);
24188 
24189 	/* create and associate the attribute */
24190 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
24191 	if (pa != NULL) {
24192 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
24193 
24194 		zcopy->zcopy_flags = flags;
24195 	}
24196 	return (pa != NULL);
24197 }
24198 
24199 /*
24200  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
24201  * block chain. We could rewrite to handle arbitrary message block chains but
24202  * that would make the code complicated and slow. Right now there three
24203  * restrictions:
24204  *
24205  *   1. The first message block must contain the complete IP header and
24206  *	at least 1 byte of payload data.
24207  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
24208  *	so that we can use a single Multidata message.
24209  *   3. No frag must be distributed over two or more message blocks so
24210  *	that we don't need more than two packet descriptors per frag.
24211  *
24212  * The above restrictions allow us to support userland applications (which
24213  * will send down a single message block) and NFS over UDP (which will
24214  * send down a chain of at most three message blocks).
24215  *
24216  * We also don't use MDT for payloads with less than or equal to
24217  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
24218  */
24219 boolean_t
24220 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
24221 {
24222 	int	blocks;
24223 	ssize_t	total, missing, size;
24224 
24225 	ASSERT(mp != NULL);
24226 	ASSERT(hdr_len > 0);
24227 
24228 	size = MBLKL(mp) - hdr_len;
24229 	if (size <= 0)
24230 		return (B_FALSE);
24231 
24232 	/* The first mblk contains the header and some payload. */
24233 	blocks = 1;
24234 	total = size;
24235 	size %= len;
24236 	missing = (size == 0) ? 0 : (len - size);
24237 	mp = mp->b_cont;
24238 
24239 	while (mp != NULL) {
24240 		/*
24241 		 * Give up if we encounter a zero length message block.
24242 		 * In practice, this should rarely happen and therefore
24243 		 * not worth the trouble of freeing and re-linking the
24244 		 * mblk from the chain to handle such case.
24245 		 */
24246 		if ((size = MBLKL(mp)) == 0)
24247 			return (B_FALSE);
24248 
24249 		/* Too many payload buffers for a single Multidata message? */
24250 		if (++blocks > MULTIDATA_MAX_PBUFS)
24251 			return (B_FALSE);
24252 
24253 		total += size;
24254 		/* Is a frag distributed over two or more message blocks? */
24255 		if (missing > size)
24256 			return (B_FALSE);
24257 		size -= missing;
24258 
24259 		size %= len;
24260 		missing = (size == 0) ? 0 : (len - size);
24261 
24262 		mp = mp->b_cont;
24263 	}
24264 
24265 	return (total > ip_wput_frag_mdt_min);
24266 }
24267 
24268 /*
24269  * Outbound IPv4 fragmentation routine using MDT.
24270  */
24271 static void
24272 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
24273     uint32_t frag_flag, int offset)
24274 {
24275 	ipha_t		*ipha_orig;
24276 	int		i1, ip_data_end;
24277 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
24278 	mblk_t		*hdr_mp, *md_mp = NULL;
24279 	unsigned char	*hdr_ptr, *pld_ptr;
24280 	multidata_t	*mmd;
24281 	ip_pdescinfo_t	pdi;
24282 	ill_t		*ill;
24283 	ip_stack_t	*ipst = ire->ire_ipst;
24284 
24285 	ASSERT(DB_TYPE(mp) == M_DATA);
24286 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
24287 
24288 	ill = ire_to_ill(ire);
24289 	ASSERT(ill != NULL);
24290 
24291 	ipha_orig = (ipha_t *)mp->b_rptr;
24292 	mp->b_rptr += sizeof (ipha_t);
24293 
24294 	/* Calculate how many packets we will send out */
24295 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
24296 	pkts = (i1 + len - 1) / len;
24297 	ASSERT(pkts > 1);
24298 
24299 	/* Allocate a message block which will hold all the IP Headers. */
24300 	wroff = ipst->ips_ip_wroff_extra;
24301 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
24302 
24303 	i1 = pkts * hdr_chunk_len;
24304 	/*
24305 	 * Create the header buffer, Multidata and destination address
24306 	 * and SAP attribute that should be associated with it.
24307 	 */
24308 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
24309 	    ((hdr_mp->b_wptr += i1),
24310 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
24311 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
24312 		freemsg(mp);
24313 		if (md_mp == NULL) {
24314 			freemsg(hdr_mp);
24315 		} else {
24316 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
24317 			freemsg(md_mp);
24318 		}
24319 		IP_STAT(ipst, ip_frag_mdt_allocfail);
24320 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
24321 		return;
24322 	}
24323 	IP_STAT(ipst, ip_frag_mdt_allocd);
24324 
24325 	/*
24326 	 * Add a payload buffer to the Multidata; this operation must not
24327 	 * fail, or otherwise our logic in this routine is broken.  There
24328 	 * is no memory allocation done by the routine, so any returned
24329 	 * failure simply tells us that we've done something wrong.
24330 	 *
24331 	 * A failure tells us that either we're adding the same payload
24332 	 * buffer more than once, or we're trying to add more buffers than
24333 	 * allowed.  None of the above cases should happen, and we panic
24334 	 * because either there's horrible heap corruption, and/or
24335 	 * programming mistake.
24336 	 */
24337 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24338 		goto pbuf_panic;
24339 
24340 	hdr_ptr = hdr_mp->b_rptr;
24341 	pld_ptr = mp->b_rptr;
24342 
24343 	/* Establish the ending byte offset, based on the starting offset. */
24344 	offset <<= 3;
24345 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
24346 	    IP_SIMPLE_HDR_LENGTH;
24347 
24348 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
24349 
24350 	while (pld_ptr < mp->b_wptr) {
24351 		ipha_t		*ipha;
24352 		uint16_t	offset_and_flags;
24353 		uint16_t	ip_len;
24354 		int		error;
24355 
24356 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
24357 		ipha = (ipha_t *)(hdr_ptr + wroff);
24358 		ASSERT(OK_32PTR(ipha));
24359 		*ipha = *ipha_orig;
24360 
24361 		if (ip_data_end - offset > len) {
24362 			offset_and_flags = IPH_MF;
24363 		} else {
24364 			/*
24365 			 * Last frag. Set len to the length of this last piece.
24366 			 */
24367 			len = ip_data_end - offset;
24368 			/* A frag of a frag might have IPH_MF non-zero */
24369 			offset_and_flags =
24370 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24371 			    IPH_MF;
24372 		}
24373 		offset_and_flags |= (uint16_t)(offset >> 3);
24374 		offset_and_flags |= (uint16_t)frag_flag;
24375 		/* Store the offset and flags in the IP header. */
24376 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24377 
24378 		/* Store the length in the IP header. */
24379 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
24380 		ipha->ipha_length = htons(ip_len);
24381 
24382 		/*
24383 		 * Set the IP header checksum.  Note that mp is just
24384 		 * the header, so this is easy to pass to ip_csum.
24385 		 */
24386 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24387 
24388 		DTRACE_IP7(send, mblk_t *, md_mp, conn_t *, NULL, void_ip_t *,
24389 		    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *,
24390 		    NULL, int, 0);
24391 
24392 		/*
24393 		 * Record offset and size of header and data of the next packet
24394 		 * in the multidata message.
24395 		 */
24396 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
24397 		PDESC_PLD_INIT(&pdi);
24398 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24399 		ASSERT(i1 > 0);
24400 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24401 		if (i1 == len) {
24402 			pld_ptr += len;
24403 		} else {
24404 			i1 = len - i1;
24405 			mp = mp->b_cont;
24406 			ASSERT(mp != NULL);
24407 			ASSERT(MBLKL(mp) >= i1);
24408 			/*
24409 			 * Attach the next payload message block to the
24410 			 * multidata message.
24411 			 */
24412 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24413 				goto pbuf_panic;
24414 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24415 			pld_ptr = mp->b_rptr + i1;
24416 		}
24417 
24418 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24419 		    KM_NOSLEEP)) == NULL) {
24420 			/*
24421 			 * Any failure other than ENOMEM indicates that we
24422 			 * have passed in invalid pdesc info or parameters
24423 			 * to mmd_addpdesc, which must not happen.
24424 			 *
24425 			 * EINVAL is a result of failure on boundary checks
24426 			 * against the pdesc info contents.  It should not
24427 			 * happen, and we panic because either there's
24428 			 * horrible heap corruption, and/or programming
24429 			 * mistake.
24430 			 */
24431 			if (error != ENOMEM) {
24432 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24433 				    "pdesc logic error detected for "
24434 				    "mmd %p pinfo %p (%d)\n",
24435 				    (void *)mmd, (void *)&pdi, error);
24436 				/* NOTREACHED */
24437 			}
24438 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24439 			/* Free unattached payload message blocks as well */
24440 			md_mp->b_cont = mp->b_cont;
24441 			goto free_mmd;
24442 		}
24443 
24444 		/* Advance fragment offset. */
24445 		offset += len;
24446 
24447 		/* Advance to location for next header in the buffer. */
24448 		hdr_ptr += hdr_chunk_len;
24449 
24450 		/* Did we reach the next payload message block? */
24451 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24452 			mp = mp->b_cont;
24453 			/*
24454 			 * Attach the next message block with payload
24455 			 * data to the multidata message.
24456 			 */
24457 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24458 				goto pbuf_panic;
24459 			pld_ptr = mp->b_rptr;
24460 		}
24461 	}
24462 
24463 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24464 	ASSERT(mp->b_wptr == pld_ptr);
24465 
24466 	/* Update IP statistics */
24467 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24468 
24469 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24470 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24471 
24472 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24473 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24474 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24475 
24476 	if (pkt_type == OB_PKT) {
24477 		ire->ire_ob_pkt_count += pkts;
24478 		if (ire->ire_ipif != NULL)
24479 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24480 	} else {
24481 		/* The type is IB_PKT in the forwarding path. */
24482 		ire->ire_ib_pkt_count += pkts;
24483 		ASSERT(!IRE_IS_LOCAL(ire));
24484 		if (ire->ire_type & IRE_BROADCAST) {
24485 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24486 		} else {
24487 			UPDATE_MIB(ill->ill_ip_mib,
24488 			    ipIfStatsHCOutForwDatagrams, pkts);
24489 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24490 		}
24491 	}
24492 	ire->ire_last_used_time = lbolt;
24493 	/* Send it down */
24494 	putnext(ire->ire_stq, md_mp);
24495 	return;
24496 
24497 pbuf_panic:
24498 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24499 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24500 	    pbuf_idx);
24501 	/* NOTREACHED */
24502 }
24503 
24504 /*
24505  * Outbound IP fragmentation routine.
24506  *
24507  * NOTE : This routine does not ire_refrele the ire that is passed in
24508  * as the argument.
24509  */
24510 static void
24511 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24512     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst, conn_t *connp)
24513 {
24514 	int		i1;
24515 	mblk_t		*ll_hdr_mp;
24516 	int 		ll_hdr_len;
24517 	int		hdr_len;
24518 	mblk_t		*hdr_mp;
24519 	ipha_t		*ipha;
24520 	int		ip_data_end;
24521 	int		len;
24522 	mblk_t		*mp = mp_orig, *mp1;
24523 	int		offset;
24524 	queue_t		*q;
24525 	uint32_t	v_hlen_tos_len;
24526 	mblk_t		*first_mp;
24527 	boolean_t	mctl_present;
24528 	ill_t		*ill;
24529 	ill_t		*out_ill;
24530 	mblk_t		*xmit_mp;
24531 	mblk_t		*carve_mp;
24532 	ire_t		*ire1 = NULL;
24533 	ire_t		*save_ire = NULL;
24534 	mblk_t  	*next_mp = NULL;
24535 	boolean_t	last_frag = B_FALSE;
24536 	boolean_t	multirt_send = B_FALSE;
24537 	ire_t		*first_ire = NULL;
24538 	irb_t		*irb = NULL;
24539 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24540 
24541 	ill = ire_to_ill(ire);
24542 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24543 
24544 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24545 
24546 	if (max_frag == 0) {
24547 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24548 		    " -  dropping packet\n"));
24549 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24550 		freemsg(mp);
24551 		return;
24552 	}
24553 
24554 	/*
24555 	 * IPsec does not allow hw accelerated packets to be fragmented
24556 	 * This check is made in ip_wput_ipsec_out prior to coming here
24557 	 * via ip_wput_ire_fragmentit.
24558 	 *
24559 	 * If at this point we have an ire whose ARP request has not
24560 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24561 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24562 	 * This packet and all fragmentable packets for this ire will
24563 	 * continue to get dropped while ire_nce->nce_state remains in
24564 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24565 	 * ND_REACHABLE, all subsquent large packets for this ire will
24566 	 * get fragemented and sent out by this function.
24567 	 */
24568 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24569 		/* If nce_state is ND_INITIAL, trigger ARP query */
24570 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
24571 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24572 		    " -  dropping packet\n"));
24573 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24574 		freemsg(mp);
24575 		return;
24576 	}
24577 
24578 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24579 	    "ip_wput_frag_start:");
24580 
24581 	if (mp->b_datap->db_type == M_CTL) {
24582 		first_mp = mp;
24583 		mp_orig = mp = mp->b_cont;
24584 		mctl_present = B_TRUE;
24585 	} else {
24586 		first_mp = mp;
24587 		mctl_present = B_FALSE;
24588 	}
24589 
24590 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24591 	ipha = (ipha_t *)mp->b_rptr;
24592 
24593 	/*
24594 	 * If the Don't Fragment flag is on, generate an ICMP destination
24595 	 * unreachable, fragmentation needed.
24596 	 */
24597 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24598 	if (offset & IPH_DF) {
24599 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24600 		if (is_system_labeled()) {
24601 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24602 			    ire->ire_max_frag - max_frag, AF_INET);
24603 		}
24604 		/*
24605 		 * Need to compute hdr checksum if called from ip_wput_ire.
24606 		 * Note that ip_rput_forward verifies the checksum before
24607 		 * calling this routine so in that case this is a noop.
24608 		 */
24609 		ipha->ipha_hdr_checksum = 0;
24610 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24611 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24612 		    ipst);
24613 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24614 		    "ip_wput_frag_end:(%S)",
24615 		    "don't fragment");
24616 		return;
24617 	}
24618 	/*
24619 	 * Labeled systems adjust max_frag if they add a label
24620 	 * to send the correct path mtu.  We need the real mtu since we
24621 	 * are fragmenting the packet after label adjustment.
24622 	 */
24623 	if (is_system_labeled())
24624 		max_frag = ire->ire_max_frag;
24625 	if (mctl_present)
24626 		freeb(first_mp);
24627 	/*
24628 	 * Establish the starting offset.  May not be zero if we are fragging
24629 	 * a fragment that is being forwarded.
24630 	 */
24631 	offset = offset & IPH_OFFSET;
24632 
24633 	/* TODO why is this test needed? */
24634 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24635 	if (((max_frag - LENGTH) & ~7) < 8) {
24636 		/* TODO: notify ulp somehow */
24637 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24638 		freemsg(mp);
24639 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24640 		    "ip_wput_frag_end:(%S)",
24641 		    "len < 8");
24642 		return;
24643 	}
24644 
24645 	hdr_len = (V_HLEN & 0xF) << 2;
24646 
24647 	ipha->ipha_hdr_checksum = 0;
24648 
24649 	/*
24650 	 * Establish the number of bytes maximum per frag, after putting
24651 	 * in the header.
24652 	 */
24653 	len = (max_frag - hdr_len) & ~7;
24654 
24655 	/* Check if we can use MDT to send out the frags. */
24656 	ASSERT(!IRE_IS_LOCAL(ire));
24657 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24658 	    ipst->ips_ip_multidata_outbound &&
24659 	    !(ire->ire_flags & RTF_MULTIRT) &&
24660 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24661 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24662 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24663 		ASSERT(ill->ill_mdt_capab != NULL);
24664 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24665 			/*
24666 			 * If MDT has been previously turned off in the past,
24667 			 * and we currently can do MDT (due to IPQoS policy
24668 			 * removal, etc.) then enable it for this interface.
24669 			 */
24670 			ill->ill_mdt_capab->ill_mdt_on = 1;
24671 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24672 			    ill->ill_name));
24673 		}
24674 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24675 		    offset);
24676 		return;
24677 	}
24678 
24679 	/* Get a copy of the header for the trailing frags */
24680 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24681 	if (!hdr_mp) {
24682 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24683 		freemsg(mp);
24684 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24685 		    "ip_wput_frag_end:(%S)",
24686 		    "couldn't copy hdr");
24687 		return;
24688 	}
24689 	if (DB_CRED(mp) != NULL)
24690 		mblk_setcred(hdr_mp, DB_CRED(mp));
24691 
24692 	/* Store the starting offset, with the MoreFrags flag. */
24693 	i1 = offset | IPH_MF | frag_flag;
24694 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24695 
24696 	/* Establish the ending byte offset, based on the starting offset. */
24697 	offset <<= 3;
24698 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24699 
24700 	/* Store the length of the first fragment in the IP header. */
24701 	i1 = len + hdr_len;
24702 	ASSERT(i1 <= IP_MAXPACKET);
24703 	ipha->ipha_length = htons((uint16_t)i1);
24704 
24705 	/*
24706 	 * Compute the IP header checksum for the first frag.  We have to
24707 	 * watch out that we stop at the end of the header.
24708 	 */
24709 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24710 
24711 	/*
24712 	 * Now carve off the first frag.  Note that this will include the
24713 	 * original IP header.
24714 	 */
24715 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24716 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24717 		freeb(hdr_mp);
24718 		freemsg(mp_orig);
24719 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24720 		    "ip_wput_frag_end:(%S)",
24721 		    "couldn't carve first");
24722 		return;
24723 	}
24724 
24725 	/*
24726 	 * Multirouting case. Each fragment is replicated
24727 	 * via all non-condemned RTF_MULTIRT routes
24728 	 * currently resolved.
24729 	 * We ensure that first_ire is the first RTF_MULTIRT
24730 	 * ire in the bucket.
24731 	 */
24732 	if (ire->ire_flags & RTF_MULTIRT) {
24733 		irb = ire->ire_bucket;
24734 		ASSERT(irb != NULL);
24735 
24736 		multirt_send = B_TRUE;
24737 
24738 		/* Make sure we do not omit any multiroute ire. */
24739 		IRB_REFHOLD(irb);
24740 		for (first_ire = irb->irb_ire;
24741 		    first_ire != NULL;
24742 		    first_ire = first_ire->ire_next) {
24743 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24744 			    (first_ire->ire_addr == ire->ire_addr) &&
24745 			    !(first_ire->ire_marks &
24746 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24747 				break;
24748 			}
24749 		}
24750 
24751 		if (first_ire != NULL) {
24752 			if (first_ire != ire) {
24753 				IRE_REFHOLD(first_ire);
24754 				/*
24755 				 * Do not release the ire passed in
24756 				 * as the argument.
24757 				 */
24758 				ire = first_ire;
24759 			} else {
24760 				first_ire = NULL;
24761 			}
24762 		}
24763 		IRB_REFRELE(irb);
24764 
24765 		/*
24766 		 * Save the first ire; we will need to restore it
24767 		 * for the trailing frags.
24768 		 * We REFHOLD save_ire, as each iterated ire will be
24769 		 * REFRELEd.
24770 		 */
24771 		save_ire = ire;
24772 		IRE_REFHOLD(save_ire);
24773 	}
24774 
24775 	/*
24776 	 * First fragment emission loop.
24777 	 * In most cases, the emission loop below is entered only
24778 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24779 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24780 	 * bucket, and send the fragment through all crossed
24781 	 * RTF_MULTIRT routes.
24782 	 */
24783 	do {
24784 		if (ire->ire_flags & RTF_MULTIRT) {
24785 			/*
24786 			 * We are in a multiple send case, need to get
24787 			 * the next ire and make a copy of the packet.
24788 			 * ire1 holds here the next ire to process in the
24789 			 * bucket. If multirouting is expected,
24790 			 * any non-RTF_MULTIRT ire that has the
24791 			 * right destination address is ignored.
24792 			 *
24793 			 * We have to take into account the MTU of
24794 			 * each walked ire. max_frag is set by the
24795 			 * the caller and generally refers to
24796 			 * the primary ire entry. Here we ensure that
24797 			 * no route with a lower MTU will be used, as
24798 			 * fragments are carved once for all ires,
24799 			 * then replicated.
24800 			 */
24801 			ASSERT(irb != NULL);
24802 			IRB_REFHOLD(irb);
24803 			for (ire1 = ire->ire_next;
24804 			    ire1 != NULL;
24805 			    ire1 = ire1->ire_next) {
24806 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24807 					continue;
24808 				if (ire1->ire_addr != ire->ire_addr)
24809 					continue;
24810 				if (ire1->ire_marks &
24811 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24812 					continue;
24813 				/*
24814 				 * Ensure we do not exceed the MTU
24815 				 * of the next route.
24816 				 */
24817 				if (ire1->ire_max_frag < max_frag) {
24818 					ip_multirt_bad_mtu(ire1, max_frag);
24819 					continue;
24820 				}
24821 
24822 				/* Got one. */
24823 				IRE_REFHOLD(ire1);
24824 				break;
24825 			}
24826 			IRB_REFRELE(irb);
24827 
24828 			if (ire1 != NULL) {
24829 				next_mp = copyb(mp);
24830 				if ((next_mp == NULL) ||
24831 				    ((mp->b_cont != NULL) &&
24832 				    ((next_mp->b_cont =
24833 				    dupmsg(mp->b_cont)) == NULL))) {
24834 					freemsg(next_mp);
24835 					next_mp = NULL;
24836 					ire_refrele(ire1);
24837 					ire1 = NULL;
24838 				}
24839 			}
24840 
24841 			/* Last multiroute ire; don't loop anymore. */
24842 			if (ire1 == NULL) {
24843 				multirt_send = B_FALSE;
24844 			}
24845 		}
24846 
24847 		ll_hdr_len = 0;
24848 		LOCK_IRE_FP_MP(ire);
24849 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24850 		if (ll_hdr_mp != NULL) {
24851 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24852 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24853 		} else {
24854 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24855 		}
24856 
24857 		/* If there is a transmit header, get a copy for this frag. */
24858 		/*
24859 		 * TODO: should check db_ref before calling ip_carve_mp since
24860 		 * it might give us a dup.
24861 		 */
24862 		if (!ll_hdr_mp) {
24863 			/* No xmit header. */
24864 			xmit_mp = mp;
24865 
24866 		/* We have a link-layer header that can fit in our mblk. */
24867 		} else if (mp->b_datap->db_ref == 1 &&
24868 		    ll_hdr_len != 0 &&
24869 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24870 			/* M_DATA fastpath */
24871 			mp->b_rptr -= ll_hdr_len;
24872 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24873 			xmit_mp = mp;
24874 
24875 		/* Corner case if copyb has failed */
24876 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24877 			UNLOCK_IRE_FP_MP(ire);
24878 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24879 			freeb(hdr_mp);
24880 			freemsg(mp);
24881 			freemsg(mp_orig);
24882 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24883 			    "ip_wput_frag_end:(%S)",
24884 			    "discard");
24885 
24886 			if (multirt_send) {
24887 				ASSERT(ire1);
24888 				ASSERT(next_mp);
24889 
24890 				freemsg(next_mp);
24891 				ire_refrele(ire1);
24892 			}
24893 			if (save_ire != NULL)
24894 				IRE_REFRELE(save_ire);
24895 
24896 			if (first_ire != NULL)
24897 				ire_refrele(first_ire);
24898 			return;
24899 
24900 		/*
24901 		 * Case of res_mp OR the fastpath mp can't fit
24902 		 * in the mblk
24903 		 */
24904 		} else {
24905 			xmit_mp->b_cont = mp;
24906 			if (DB_CRED(mp) != NULL)
24907 				mblk_setcred(xmit_mp, DB_CRED(mp));
24908 			/*
24909 			 * Get priority marking, if any.
24910 			 * We propagate the CoS marking from the
24911 			 * original packet that went to QoS processing
24912 			 * in ip_wput_ire to the newly carved mp.
24913 			 */
24914 			if (DB_TYPE(xmit_mp) == M_DATA)
24915 				xmit_mp->b_band = mp->b_band;
24916 		}
24917 		UNLOCK_IRE_FP_MP(ire);
24918 
24919 		q = ire->ire_stq;
24920 		out_ill = (ill_t *)q->q_ptr;
24921 
24922 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24923 
24924 		DTRACE_PROBE4(ip4__physical__out__start,
24925 		    ill_t *, NULL, ill_t *, out_ill,
24926 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24927 
24928 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24929 		    ipst->ips_ipv4firewall_physical_out,
24930 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24931 
24932 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24933 
24934 		if (xmit_mp != NULL) {
24935 			DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *, NULL,
24936 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
24937 			    ipha_t *, ipha, ip6_t *, NULL, int, 0);
24938 
24939 			ILL_SEND_TX(out_ill, ire, connp, xmit_mp, 0);
24940 
24941 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24942 			UPDATE_MIB(out_ill->ill_ip_mib,
24943 			    ipIfStatsHCOutOctets, i1);
24944 
24945 			if (pkt_type != OB_PKT) {
24946 				/*
24947 				 * Update the packet count and MIB stats
24948 				 * of trailing RTF_MULTIRT ires.
24949 				 */
24950 				UPDATE_OB_PKT_COUNT(ire);
24951 				BUMP_MIB(out_ill->ill_ip_mib,
24952 				    ipIfStatsOutFragReqds);
24953 			}
24954 		}
24955 
24956 		if (multirt_send) {
24957 			/*
24958 			 * We are in a multiple send case; look for
24959 			 * the next ire and re-enter the loop.
24960 			 */
24961 			ASSERT(ire1);
24962 			ASSERT(next_mp);
24963 			/* REFRELE the current ire before looping */
24964 			ire_refrele(ire);
24965 			ire = ire1;
24966 			ire1 = NULL;
24967 			mp = next_mp;
24968 			next_mp = NULL;
24969 		}
24970 	} while (multirt_send);
24971 
24972 	ASSERT(ire1 == NULL);
24973 
24974 	/* Restore the original ire; we need it for the trailing frags */
24975 	if (save_ire != NULL) {
24976 		/* REFRELE the last iterated ire */
24977 		ire_refrele(ire);
24978 		/* save_ire has been REFHOLDed */
24979 		ire = save_ire;
24980 		save_ire = NULL;
24981 		q = ire->ire_stq;
24982 	}
24983 
24984 	if (pkt_type == OB_PKT) {
24985 		UPDATE_OB_PKT_COUNT(ire);
24986 	} else {
24987 		out_ill = (ill_t *)q->q_ptr;
24988 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24989 		UPDATE_IB_PKT_COUNT(ire);
24990 	}
24991 
24992 	/* Advance the offset to the second frag starting point. */
24993 	offset += len;
24994 	/*
24995 	 * Update hdr_len from the copied header - there might be less options
24996 	 * in the later fragments.
24997 	 */
24998 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24999 	/* Loop until done. */
25000 	for (;;) {
25001 		uint16_t	offset_and_flags;
25002 		uint16_t	ip_len;
25003 
25004 		if (ip_data_end - offset > len) {
25005 			/*
25006 			 * Carve off the appropriate amount from the original
25007 			 * datagram.
25008 			 */
25009 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
25010 				mp = NULL;
25011 				break;
25012 			}
25013 			/*
25014 			 * More frags after this one.  Get another copy
25015 			 * of the header.
25016 			 */
25017 			if (carve_mp->b_datap->db_ref == 1 &&
25018 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
25019 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
25020 				/* Inline IP header */
25021 				carve_mp->b_rptr -= hdr_mp->b_wptr -
25022 				    hdr_mp->b_rptr;
25023 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
25024 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
25025 				mp = carve_mp;
25026 			} else {
25027 				if (!(mp = copyb(hdr_mp))) {
25028 					freemsg(carve_mp);
25029 					break;
25030 				}
25031 				/* Get priority marking, if any. */
25032 				mp->b_band = carve_mp->b_band;
25033 				mp->b_cont = carve_mp;
25034 			}
25035 			ipha = (ipha_t *)mp->b_rptr;
25036 			offset_and_flags = IPH_MF;
25037 		} else {
25038 			/*
25039 			 * Last frag.  Consume the header. Set len to
25040 			 * the length of this last piece.
25041 			 */
25042 			len = ip_data_end - offset;
25043 
25044 			/*
25045 			 * Carve off the appropriate amount from the original
25046 			 * datagram.
25047 			 */
25048 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
25049 				mp = NULL;
25050 				break;
25051 			}
25052 			if (carve_mp->b_datap->db_ref == 1 &&
25053 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
25054 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
25055 				/* Inline IP header */
25056 				carve_mp->b_rptr -= hdr_mp->b_wptr -
25057 				    hdr_mp->b_rptr;
25058 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
25059 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
25060 				mp = carve_mp;
25061 				freeb(hdr_mp);
25062 				hdr_mp = mp;
25063 			} else {
25064 				mp = hdr_mp;
25065 				/* Get priority marking, if any. */
25066 				mp->b_band = carve_mp->b_band;
25067 				mp->b_cont = carve_mp;
25068 			}
25069 			ipha = (ipha_t *)mp->b_rptr;
25070 			/* A frag of a frag might have IPH_MF non-zero */
25071 			offset_and_flags =
25072 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
25073 			    IPH_MF;
25074 		}
25075 		offset_and_flags |= (uint16_t)(offset >> 3);
25076 		offset_and_flags |= (uint16_t)frag_flag;
25077 		/* Store the offset and flags in the IP header. */
25078 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
25079 
25080 		/* Store the length in the IP header. */
25081 		ip_len = (uint16_t)(len + hdr_len);
25082 		ipha->ipha_length = htons(ip_len);
25083 
25084 		/*
25085 		 * Set the IP header checksum.	Note that mp is just
25086 		 * the header, so this is easy to pass to ip_csum.
25087 		 */
25088 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
25089 
25090 		/* Attach a transmit header, if any, and ship it. */
25091 		if (pkt_type == OB_PKT) {
25092 			UPDATE_OB_PKT_COUNT(ire);
25093 		} else {
25094 			out_ill = (ill_t *)q->q_ptr;
25095 			BUMP_MIB(out_ill->ill_ip_mib,
25096 			    ipIfStatsHCOutForwDatagrams);
25097 			UPDATE_IB_PKT_COUNT(ire);
25098 		}
25099 
25100 		if (ire->ire_flags & RTF_MULTIRT) {
25101 			irb = ire->ire_bucket;
25102 			ASSERT(irb != NULL);
25103 
25104 			multirt_send = B_TRUE;
25105 
25106 			/*
25107 			 * Save the original ire; we will need to restore it
25108 			 * for the tailing frags.
25109 			 */
25110 			save_ire = ire;
25111 			IRE_REFHOLD(save_ire);
25112 		}
25113 		/*
25114 		 * Emission loop for this fragment, similar
25115 		 * to what is done for the first fragment.
25116 		 */
25117 		do {
25118 			if (multirt_send) {
25119 				/*
25120 				 * We are in a multiple send case, need to get
25121 				 * the next ire and make a copy of the packet.
25122 				 */
25123 				ASSERT(irb != NULL);
25124 				IRB_REFHOLD(irb);
25125 				for (ire1 = ire->ire_next;
25126 				    ire1 != NULL;
25127 				    ire1 = ire1->ire_next) {
25128 					if (!(ire1->ire_flags & RTF_MULTIRT))
25129 						continue;
25130 					if (ire1->ire_addr != ire->ire_addr)
25131 						continue;
25132 					if (ire1->ire_marks &
25133 					    (IRE_MARK_CONDEMNED|
25134 					    IRE_MARK_HIDDEN)) {
25135 						continue;
25136 					}
25137 					/*
25138 					 * Ensure we do not exceed the MTU
25139 					 * of the next route.
25140 					 */
25141 					if (ire1->ire_max_frag < max_frag) {
25142 						ip_multirt_bad_mtu(ire1,
25143 						    max_frag);
25144 						continue;
25145 					}
25146 
25147 					/* Got one. */
25148 					IRE_REFHOLD(ire1);
25149 					break;
25150 				}
25151 				IRB_REFRELE(irb);
25152 
25153 				if (ire1 != NULL) {
25154 					next_mp = copyb(mp);
25155 					if ((next_mp == NULL) ||
25156 					    ((mp->b_cont != NULL) &&
25157 					    ((next_mp->b_cont =
25158 					    dupmsg(mp->b_cont)) == NULL))) {
25159 						freemsg(next_mp);
25160 						next_mp = NULL;
25161 						ire_refrele(ire1);
25162 						ire1 = NULL;
25163 					}
25164 				}
25165 
25166 				/* Last multiroute ire; don't loop anymore. */
25167 				if (ire1 == NULL) {
25168 					multirt_send = B_FALSE;
25169 				}
25170 			}
25171 
25172 			/* Update transmit header */
25173 			ll_hdr_len = 0;
25174 			LOCK_IRE_FP_MP(ire);
25175 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
25176 			if (ll_hdr_mp != NULL) {
25177 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
25178 				ll_hdr_len = MBLKL(ll_hdr_mp);
25179 			} else {
25180 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
25181 			}
25182 
25183 			if (!ll_hdr_mp) {
25184 				xmit_mp = mp;
25185 
25186 			/*
25187 			 * We have link-layer header that can fit in
25188 			 * our mblk.
25189 			 */
25190 			} else if (mp->b_datap->db_ref == 1 &&
25191 			    ll_hdr_len != 0 &&
25192 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
25193 				/* M_DATA fastpath */
25194 				mp->b_rptr -= ll_hdr_len;
25195 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
25196 				    ll_hdr_len);
25197 				xmit_mp = mp;
25198 
25199 			/*
25200 			 * Case of res_mp OR the fastpath mp can't fit
25201 			 * in the mblk
25202 			 */
25203 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
25204 				xmit_mp->b_cont = mp;
25205 				if (DB_CRED(mp) != NULL)
25206 					mblk_setcred(xmit_mp, DB_CRED(mp));
25207 				/* Get priority marking, if any. */
25208 				if (DB_TYPE(xmit_mp) == M_DATA)
25209 					xmit_mp->b_band = mp->b_band;
25210 
25211 			/* Corner case if copyb failed */
25212 			} else {
25213 				/*
25214 				 * Exit both the replication and
25215 				 * fragmentation loops.
25216 				 */
25217 				UNLOCK_IRE_FP_MP(ire);
25218 				goto drop_pkt;
25219 			}
25220 			UNLOCK_IRE_FP_MP(ire);
25221 
25222 			mp1 = mp;
25223 			out_ill = (ill_t *)q->q_ptr;
25224 
25225 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
25226 
25227 			DTRACE_PROBE4(ip4__physical__out__start,
25228 			    ill_t *, NULL, ill_t *, out_ill,
25229 			    ipha_t *, ipha, mblk_t *, xmit_mp);
25230 
25231 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
25232 			    ipst->ips_ipv4firewall_physical_out,
25233 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
25234 
25235 			DTRACE_PROBE1(ip4__physical__out__end,
25236 			    mblk_t *, xmit_mp);
25237 
25238 			if (mp != mp1 && hdr_mp == mp1)
25239 				hdr_mp = mp;
25240 			if (mp != mp1 && mp_orig == mp1)
25241 				mp_orig = mp;
25242 
25243 			if (xmit_mp != NULL) {
25244 				DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *,
25245 				    NULL, void_ip_t *, ipha,
25246 				    __dtrace_ipsr_ill_t *, out_ill, ipha_t *,
25247 				    ipha, ip6_t *, NULL, int, 0);
25248 
25249 				ILL_SEND_TX(out_ill, ire, connp, xmit_mp, 0);
25250 
25251 				BUMP_MIB(out_ill->ill_ip_mib,
25252 				    ipIfStatsHCOutTransmits);
25253 				UPDATE_MIB(out_ill->ill_ip_mib,
25254 				    ipIfStatsHCOutOctets, ip_len);
25255 
25256 				if (pkt_type != OB_PKT) {
25257 					/*
25258 					 * Update the packet count of trailing
25259 					 * RTF_MULTIRT ires.
25260 					 */
25261 					UPDATE_OB_PKT_COUNT(ire);
25262 				}
25263 			}
25264 
25265 			/* All done if we just consumed the hdr_mp. */
25266 			if (mp == hdr_mp) {
25267 				last_frag = B_TRUE;
25268 				BUMP_MIB(out_ill->ill_ip_mib,
25269 				    ipIfStatsOutFragOKs);
25270 			}
25271 
25272 			if (multirt_send) {
25273 				/*
25274 				 * We are in a multiple send case; look for
25275 				 * the next ire and re-enter the loop.
25276 				 */
25277 				ASSERT(ire1);
25278 				ASSERT(next_mp);
25279 				/* REFRELE the current ire before looping */
25280 				ire_refrele(ire);
25281 				ire = ire1;
25282 				ire1 = NULL;
25283 				q = ire->ire_stq;
25284 				mp = next_mp;
25285 				next_mp = NULL;
25286 			}
25287 		} while (multirt_send);
25288 		/*
25289 		 * Restore the original ire; we need it for the
25290 		 * trailing frags
25291 		 */
25292 		if (save_ire != NULL) {
25293 			ASSERT(ire1 == NULL);
25294 			/* REFRELE the last iterated ire */
25295 			ire_refrele(ire);
25296 			/* save_ire has been REFHOLDed */
25297 			ire = save_ire;
25298 			q = ire->ire_stq;
25299 			save_ire = NULL;
25300 		}
25301 
25302 		if (last_frag) {
25303 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25304 			    "ip_wput_frag_end:(%S)",
25305 			    "consumed hdr_mp");
25306 
25307 			if (first_ire != NULL)
25308 				ire_refrele(first_ire);
25309 			return;
25310 		}
25311 		/* Otherwise, advance and loop. */
25312 		offset += len;
25313 	}
25314 
25315 drop_pkt:
25316 	/* Clean up following allocation failure. */
25317 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
25318 	freemsg(mp);
25319 	if (mp != hdr_mp)
25320 		freeb(hdr_mp);
25321 	if (mp != mp_orig)
25322 		freemsg(mp_orig);
25323 
25324 	if (save_ire != NULL)
25325 		IRE_REFRELE(save_ire);
25326 	if (first_ire != NULL)
25327 		ire_refrele(first_ire);
25328 
25329 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25330 	    "ip_wput_frag_end:(%S)",
25331 	    "end--alloc failure");
25332 }
25333 
25334 /*
25335  * Copy the header plus those options which have the copy bit set
25336  */
25337 static mblk_t *
25338 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
25339 {
25340 	mblk_t	*mp;
25341 	uchar_t	*up;
25342 
25343 	/*
25344 	 * Quick check if we need to look for options without the copy bit
25345 	 * set
25346 	 */
25347 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
25348 	if (!mp)
25349 		return (mp);
25350 	mp->b_rptr += ipst->ips_ip_wroff_extra;
25351 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
25352 		bcopy(rptr, mp->b_rptr, hdr_len);
25353 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
25354 		return (mp);
25355 	}
25356 	up  = mp->b_rptr;
25357 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
25358 	up += IP_SIMPLE_HDR_LENGTH;
25359 	rptr += IP_SIMPLE_HDR_LENGTH;
25360 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
25361 	while (hdr_len > 0) {
25362 		uint32_t optval;
25363 		uint32_t optlen;
25364 
25365 		optval = *rptr;
25366 		if (optval == IPOPT_EOL)
25367 			break;
25368 		if (optval == IPOPT_NOP)
25369 			optlen = 1;
25370 		else
25371 			optlen = rptr[1];
25372 		if (optval & IPOPT_COPY) {
25373 			bcopy(rptr, up, optlen);
25374 			up += optlen;
25375 		}
25376 		rptr += optlen;
25377 		hdr_len -= optlen;
25378 	}
25379 	/*
25380 	 * Make sure that we drop an even number of words by filling
25381 	 * with EOL to the next word boundary.
25382 	 */
25383 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
25384 	    hdr_len & 0x3; hdr_len++)
25385 		*up++ = IPOPT_EOL;
25386 	mp->b_wptr = up;
25387 	/* Update header length */
25388 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
25389 	return (mp);
25390 }
25391 
25392 /*
25393  * Delivery to local recipients including fanout to multiple recipients.
25394  * Does not do checksumming of UDP/TCP.
25395  * Note: q should be the read side queue for either the ill or conn.
25396  * Note: rq should be the read side q for the lower (ill) stream.
25397  * We don't send packets to IPPF processing, thus the last argument
25398  * to all the fanout calls are B_FALSE.
25399  */
25400 void
25401 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25402     int fanout_flags, zoneid_t zoneid)
25403 {
25404 	uint32_t	protocol;
25405 	mblk_t		*first_mp;
25406 	boolean_t	mctl_present;
25407 	int		ire_type;
25408 #define	rptr	((uchar_t *)ipha)
25409 	ip_stack_t	*ipst = ill->ill_ipst;
25410 
25411 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25412 	    "ip_wput_local_start: q %p", q);
25413 
25414 	if (ire != NULL) {
25415 		ire_type = ire->ire_type;
25416 	} else {
25417 		/*
25418 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25419 		 * packet is not multicast, we can't tell the ire type.
25420 		 */
25421 		ASSERT(CLASSD(ipha->ipha_dst));
25422 		ire_type = IRE_BROADCAST;
25423 	}
25424 
25425 	first_mp = mp;
25426 	if (first_mp->b_datap->db_type == M_CTL) {
25427 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25428 		if (!io->ipsec_out_secure) {
25429 			/*
25430 			 * This ipsec_out_t was allocated in ip_wput
25431 			 * for multicast packets to store the ill_index.
25432 			 * As this is being delivered locally, we don't
25433 			 * need this anymore.
25434 			 */
25435 			mp = first_mp->b_cont;
25436 			freeb(first_mp);
25437 			first_mp = mp;
25438 			mctl_present = B_FALSE;
25439 		} else {
25440 			/*
25441 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25442 			 * security properties for the looped-back packet.
25443 			 */
25444 			mctl_present = B_TRUE;
25445 			mp = first_mp->b_cont;
25446 			ASSERT(mp != NULL);
25447 			ipsec_out_to_in(first_mp);
25448 		}
25449 	} else {
25450 		mctl_present = B_FALSE;
25451 	}
25452 
25453 	DTRACE_PROBE4(ip4__loopback__in__start,
25454 	    ill_t *, ill, ill_t *, NULL,
25455 	    ipha_t *, ipha, mblk_t *, first_mp);
25456 
25457 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25458 	    ipst->ips_ipv4firewall_loopback_in,
25459 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
25460 
25461 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25462 
25463 	if (first_mp == NULL)
25464 		return;
25465 
25466 	if (ipst->ips_ipobs_enabled) {
25467 		zoneid_t szone, dzone, lookup_zoneid = ALL_ZONES;
25468 		zoneid_t stackzoneid = netstackid_to_zoneid(
25469 		    ipst->ips_netstack->netstack_stackid);
25470 
25471 		dzone = (stackzoneid == GLOBAL_ZONEID) ? zoneid : stackzoneid;
25472 		/*
25473 		 * 127.0.0.1 is special, as we cannot lookup its zoneid by
25474 		 * address.  Restrict the lookup below to the destination zone.
25475 		 */
25476 		if (ipha->ipha_src == ntohl(INADDR_LOOPBACK))
25477 			lookup_zoneid = zoneid;
25478 		szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
25479 		    lookup_zoneid);
25480 		ipobs_hook(mp, IPOBS_HOOK_LOCAL, szone, dzone, ill,
25481 		    IPV4_VERSION, 0, ipst);
25482 	}
25483 
25484 	DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL, void_ip_t *,
25485 	    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *, NULL,
25486 	    int, 1);
25487 
25488 	ipst->ips_loopback_packets++;
25489 
25490 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25491 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25492 	if (!IS_SIMPLE_IPH(ipha)) {
25493 		ip_wput_local_options(ipha, ipst);
25494 	}
25495 
25496 	protocol = ipha->ipha_protocol;
25497 	switch (protocol) {
25498 	case IPPROTO_ICMP: {
25499 		ire_t		*ire_zone;
25500 		ilm_t		*ilm;
25501 		mblk_t		*mp1;
25502 		zoneid_t	last_zoneid;
25503 
25504 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25505 			ASSERT(ire_type == IRE_BROADCAST);
25506 			/*
25507 			 * In the multicast case, applications may have joined
25508 			 * the group from different zones, so we need to deliver
25509 			 * the packet to each of them. Loop through the
25510 			 * multicast memberships structures (ilm) on the receive
25511 			 * ill and send a copy of the packet up each matching
25512 			 * one. However, we don't do this for multicasts sent on
25513 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25514 			 * they must stay in the sender's zone.
25515 			 *
25516 			 * ilm_add_v6() ensures that ilms in the same zone are
25517 			 * contiguous in the ill_ilm list. We use this property
25518 			 * to avoid sending duplicates needed when two
25519 			 * applications in the same zone join the same group on
25520 			 * different logical interfaces: we ignore the ilm if
25521 			 * it's zoneid is the same as the last matching one.
25522 			 * In addition, the sending of the packet for
25523 			 * ire_zoneid is delayed until all of the other ilms
25524 			 * have been exhausted.
25525 			 */
25526 			last_zoneid = -1;
25527 			ILM_WALKER_HOLD(ill);
25528 			for (ilm = ill->ill_ilm; ilm != NULL;
25529 			    ilm = ilm->ilm_next) {
25530 				if ((ilm->ilm_flags & ILM_DELETED) ||
25531 				    ipha->ipha_dst != ilm->ilm_addr ||
25532 				    ilm->ilm_zoneid == last_zoneid ||
25533 				    ilm->ilm_zoneid == zoneid ||
25534 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25535 					continue;
25536 				mp1 = ip_copymsg(first_mp);
25537 				if (mp1 == NULL)
25538 					continue;
25539 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25540 				    mctl_present, B_FALSE, ill,
25541 				    ilm->ilm_zoneid);
25542 				last_zoneid = ilm->ilm_zoneid;
25543 			}
25544 			ILM_WALKER_RELE(ill);
25545 			/*
25546 			 * Loopback case: the sending endpoint has
25547 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25548 			 * dispatch the multicast packet to the sending zone.
25549 			 */
25550 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25551 				freemsg(first_mp);
25552 				return;
25553 			}
25554 		} else if (ire_type == IRE_BROADCAST) {
25555 			/*
25556 			 * In the broadcast case, there may be many zones
25557 			 * which need a copy of the packet delivered to them.
25558 			 * There is one IRE_BROADCAST per broadcast address
25559 			 * and per zone; we walk those using a helper function.
25560 			 * In addition, the sending of the packet for zoneid is
25561 			 * delayed until all of the other ires have been
25562 			 * processed.
25563 			 */
25564 			IRB_REFHOLD(ire->ire_bucket);
25565 			ire_zone = NULL;
25566 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25567 			    ire)) != NULL) {
25568 				mp1 = ip_copymsg(first_mp);
25569 				if (mp1 == NULL)
25570 					continue;
25571 
25572 				UPDATE_IB_PKT_COUNT(ire_zone);
25573 				ire_zone->ire_last_used_time = lbolt;
25574 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25575 				    mctl_present, B_FALSE, ill,
25576 				    ire_zone->ire_zoneid);
25577 			}
25578 			IRB_REFRELE(ire->ire_bucket);
25579 		}
25580 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25581 		    0, mctl_present, B_FALSE, ill, zoneid);
25582 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25583 		    "ip_wput_local_end: q %p (%S)",
25584 		    q, "icmp");
25585 		return;
25586 	}
25587 	case IPPROTO_IGMP:
25588 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25589 			/* Bad packet - discarded by igmp_input */
25590 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25591 			    "ip_wput_local_end: q %p (%S)",
25592 			    q, "igmp_input--bad packet");
25593 			if (mctl_present)
25594 				freeb(first_mp);
25595 			return;
25596 		}
25597 		/*
25598 		 * igmp_input() may have returned the pulled up message.
25599 		 * So first_mp and ipha need to be reinitialized.
25600 		 */
25601 		ipha = (ipha_t *)mp->b_rptr;
25602 		if (mctl_present)
25603 			first_mp->b_cont = mp;
25604 		else
25605 			first_mp = mp;
25606 		/* deliver to local raw users */
25607 		break;
25608 	case IPPROTO_ENCAP:
25609 		/*
25610 		 * This case is covered by either ip_fanout_proto, or by
25611 		 * the above security processing for self-tunneled packets.
25612 		 */
25613 		break;
25614 	case IPPROTO_UDP: {
25615 		uint16_t	*up;
25616 		uint32_t	ports;
25617 
25618 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25619 		    UDP_PORTS_OFFSET);
25620 		/* Force a 'valid' checksum. */
25621 		up[3] = 0;
25622 
25623 		ports = *(uint32_t *)up;
25624 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25625 		    (ire_type == IRE_BROADCAST),
25626 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25627 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25628 		    ill, zoneid);
25629 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25630 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25631 		return;
25632 	}
25633 	case IPPROTO_TCP: {
25634 
25635 		/*
25636 		 * For TCP, discard broadcast packets.
25637 		 */
25638 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25639 			freemsg(first_mp);
25640 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25641 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25642 			return;
25643 		}
25644 
25645 		if (mp->b_datap->db_type == M_DATA) {
25646 			/*
25647 			 * M_DATA mblk, so init mblk (chain) for no struio().
25648 			 */
25649 			mblk_t	*mp1 = mp;
25650 
25651 			do {
25652 				mp1->b_datap->db_struioflag = 0;
25653 			} while ((mp1 = mp1->b_cont) != NULL);
25654 		}
25655 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25656 		    <= mp->b_wptr);
25657 		ip_fanout_tcp(q, first_mp, ill, ipha,
25658 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25659 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25660 		    mctl_present, B_FALSE, zoneid);
25661 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25662 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25663 		return;
25664 	}
25665 	case IPPROTO_SCTP:
25666 	{
25667 		uint32_t	ports;
25668 
25669 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25670 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25671 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25672 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25673 		return;
25674 	}
25675 
25676 	default:
25677 		break;
25678 	}
25679 	/*
25680 	 * Find a client for some other protocol.  We give
25681 	 * copies to multiple clients, if more than one is
25682 	 * bound.
25683 	 */
25684 	ip_fanout_proto(q, first_mp, ill, ipha,
25685 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25686 	    mctl_present, B_FALSE, ill, zoneid);
25687 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25688 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25689 #undef	rptr
25690 }
25691 
25692 /*
25693  * Update any source route, record route, or timestamp options.
25694  * Check that we are at end of strict source route.
25695  * The options have been sanity checked by ip_wput_options().
25696  */
25697 static void
25698 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25699 {
25700 	ipoptp_t	opts;
25701 	uchar_t		*opt;
25702 	uint8_t		optval;
25703 	uint8_t		optlen;
25704 	ipaddr_t	dst;
25705 	uint32_t	ts;
25706 	ire_t		*ire;
25707 	timestruc_t	now;
25708 
25709 	ip2dbg(("ip_wput_local_options\n"));
25710 	for (optval = ipoptp_first(&opts, ipha);
25711 	    optval != IPOPT_EOL;
25712 	    optval = ipoptp_next(&opts)) {
25713 		opt = opts.ipoptp_cur;
25714 		optlen = opts.ipoptp_len;
25715 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25716 		switch (optval) {
25717 			uint32_t off;
25718 		case IPOPT_SSRR:
25719 		case IPOPT_LSRR:
25720 			off = opt[IPOPT_OFFSET];
25721 			off--;
25722 			if (optlen < IP_ADDR_LEN ||
25723 			    off > optlen - IP_ADDR_LEN) {
25724 				/* End of source route */
25725 				break;
25726 			}
25727 			/*
25728 			 * This will only happen if two consecutive entries
25729 			 * in the source route contains our address or if
25730 			 * it is a packet with a loose source route which
25731 			 * reaches us before consuming the whole source route
25732 			 */
25733 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25734 			if (optval == IPOPT_SSRR) {
25735 				return;
25736 			}
25737 			/*
25738 			 * Hack: instead of dropping the packet truncate the
25739 			 * source route to what has been used by filling the
25740 			 * rest with IPOPT_NOP.
25741 			 */
25742 			opt[IPOPT_OLEN] = (uint8_t)off;
25743 			while (off < optlen) {
25744 				opt[off++] = IPOPT_NOP;
25745 			}
25746 			break;
25747 		case IPOPT_RR:
25748 			off = opt[IPOPT_OFFSET];
25749 			off--;
25750 			if (optlen < IP_ADDR_LEN ||
25751 			    off > optlen - IP_ADDR_LEN) {
25752 				/* No more room - ignore */
25753 				ip1dbg((
25754 				    "ip_wput_forward_options: end of RR\n"));
25755 				break;
25756 			}
25757 			dst = htonl(INADDR_LOOPBACK);
25758 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25759 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25760 			break;
25761 		case IPOPT_TS:
25762 			/* Insert timestamp if there is romm */
25763 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25764 			case IPOPT_TS_TSONLY:
25765 				off = IPOPT_TS_TIMELEN;
25766 				break;
25767 			case IPOPT_TS_PRESPEC:
25768 			case IPOPT_TS_PRESPEC_RFC791:
25769 				/* Verify that the address matched */
25770 				off = opt[IPOPT_OFFSET] - 1;
25771 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25772 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25773 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25774 				    ipst);
25775 				if (ire == NULL) {
25776 					/* Not for us */
25777 					break;
25778 				}
25779 				ire_refrele(ire);
25780 				/* FALLTHRU */
25781 			case IPOPT_TS_TSANDADDR:
25782 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25783 				break;
25784 			default:
25785 				/*
25786 				 * ip_*put_options should have already
25787 				 * dropped this packet.
25788 				 */
25789 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25790 				    "unknown IT - bug in ip_wput_options?\n");
25791 				return;	/* Keep "lint" happy */
25792 			}
25793 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25794 				/* Increase overflow counter */
25795 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25796 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25797 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25798 				    (off << 4);
25799 				break;
25800 			}
25801 			off = opt[IPOPT_OFFSET] - 1;
25802 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25803 			case IPOPT_TS_PRESPEC:
25804 			case IPOPT_TS_PRESPEC_RFC791:
25805 			case IPOPT_TS_TSANDADDR:
25806 				dst = htonl(INADDR_LOOPBACK);
25807 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25808 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25809 				/* FALLTHRU */
25810 			case IPOPT_TS_TSONLY:
25811 				off = opt[IPOPT_OFFSET] - 1;
25812 				/* Compute # of milliseconds since midnight */
25813 				gethrestime(&now);
25814 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25815 				    now.tv_nsec / (NANOSEC / MILLISEC);
25816 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25817 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25818 				break;
25819 			}
25820 			break;
25821 		}
25822 	}
25823 }
25824 
25825 /*
25826  * Send out a multicast packet on interface ipif.
25827  * The sender does not have an conn.
25828  * Caller verifies that this isn't a PHYI_LOOPBACK.
25829  */
25830 void
25831 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25832 {
25833 	ipha_t	*ipha;
25834 	ire_t	*ire;
25835 	ipaddr_t	dst;
25836 	mblk_t		*first_mp;
25837 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25838 
25839 	/* igmp_sendpkt always allocates a ipsec_out_t */
25840 	ASSERT(mp->b_datap->db_type == M_CTL);
25841 	ASSERT(!ipif->ipif_isv6);
25842 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25843 
25844 	first_mp = mp;
25845 	mp = first_mp->b_cont;
25846 	ASSERT(mp->b_datap->db_type == M_DATA);
25847 	ipha = (ipha_t *)mp->b_rptr;
25848 
25849 	/*
25850 	 * Find an IRE which matches the destination and the outgoing
25851 	 * queue (i.e. the outgoing interface.)
25852 	 */
25853 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25854 		dst = ipif->ipif_pp_dst_addr;
25855 	else
25856 		dst = ipha->ipha_dst;
25857 	/*
25858 	 * The source address has already been initialized by the
25859 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25860 	 * be sufficient rather than MATCH_IRE_IPIF.
25861 	 *
25862 	 * This function is used for sending IGMP packets. We need
25863 	 * to make sure that we send the packet out of the interface
25864 	 * (ipif->ipif_ill) where we joined the group. This is to
25865 	 * prevent from switches doing IGMP snooping to send us multicast
25866 	 * packets for a given group on the interface we have joined.
25867 	 * If we can't find an ire, igmp_sendpkt has already initialized
25868 	 * ipsec_out_attach_if so that this will not be load spread in
25869 	 * ip_newroute_ipif.
25870 	 */
25871 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25872 	    MATCH_IRE_ILL, ipst);
25873 	if (!ire) {
25874 		/*
25875 		 * Mark this packet to make it be delivered to
25876 		 * ip_wput_ire after the new ire has been
25877 		 * created.
25878 		 */
25879 		mp->b_prev = NULL;
25880 		mp->b_next = NULL;
25881 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25882 		    zoneid, &zero_info);
25883 		return;
25884 	}
25885 
25886 	/*
25887 	 * Honor the RTF_SETSRC flag; this is the only case
25888 	 * where we force this addr whatever the current src addr is,
25889 	 * because this address is set by igmp_sendpkt(), and
25890 	 * cannot be specified by any user.
25891 	 */
25892 	if (ire->ire_flags & RTF_SETSRC) {
25893 		ipha->ipha_src = ire->ire_src_addr;
25894 	}
25895 
25896 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25897 }
25898 
25899 /*
25900  * NOTE : This function does not ire_refrele the ire argument passed in.
25901  *
25902  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25903  * failure. The nce_fp_mp can vanish any time in the case of
25904  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25905  * the ire_lock to access the nce_fp_mp in this case.
25906  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25907  * prepending a fastpath message IPQoS processing must precede it, we also set
25908  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25909  * (IPQoS might have set the b_band for CoS marking).
25910  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25911  * must follow it so that IPQoS can mark the dl_priority field for CoS
25912  * marking, if needed.
25913  */
25914 static mblk_t *
25915 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc,
25916     uint32_t ill_index, ipha_t **iphap)
25917 {
25918 	uint_t	hlen;
25919 	ipha_t *ipha;
25920 	mblk_t *mp1;
25921 	boolean_t qos_done = B_FALSE;
25922 	uchar_t	*ll_hdr;
25923 	ip_stack_t	*ipst = ire->ire_ipst;
25924 
25925 #define	rptr	((uchar_t *)ipha)
25926 
25927 	ipha = (ipha_t *)mp->b_rptr;
25928 	hlen = 0;
25929 	LOCK_IRE_FP_MP(ire);
25930 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25931 		ASSERT(DB_TYPE(mp1) == M_DATA);
25932 		/* Initiate IPPF processing */
25933 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25934 			UNLOCK_IRE_FP_MP(ire);
25935 			ip_process(proc, &mp, ill_index);
25936 			if (mp == NULL)
25937 				return (NULL);
25938 
25939 			ipha = (ipha_t *)mp->b_rptr;
25940 			LOCK_IRE_FP_MP(ire);
25941 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25942 				qos_done = B_TRUE;
25943 				goto no_fp_mp;
25944 			}
25945 			ASSERT(DB_TYPE(mp1) == M_DATA);
25946 		}
25947 		hlen = MBLKL(mp1);
25948 		/*
25949 		 * Check if we have enough room to prepend fastpath
25950 		 * header
25951 		 */
25952 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25953 			ll_hdr = rptr - hlen;
25954 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25955 			/*
25956 			 * Set the b_rptr to the start of the link layer
25957 			 * header
25958 			 */
25959 			mp->b_rptr = ll_hdr;
25960 			mp1 = mp;
25961 		} else {
25962 			mp1 = copyb(mp1);
25963 			if (mp1 == NULL)
25964 				goto unlock_err;
25965 			mp1->b_band = mp->b_band;
25966 			mp1->b_cont = mp;
25967 			/*
25968 			 * certain system generated traffic may not
25969 			 * have cred/label in ip header block. This
25970 			 * is true even for a labeled system. But for
25971 			 * labeled traffic, inherit the label in the
25972 			 * new header.
25973 			 */
25974 			if (DB_CRED(mp) != NULL)
25975 				mblk_setcred(mp1, DB_CRED(mp));
25976 			/*
25977 			 * XXX disable ICK_VALID and compute checksum
25978 			 * here; can happen if nce_fp_mp changes and
25979 			 * it can't be copied now due to insufficient
25980 			 * space. (unlikely, fp mp can change, but it
25981 			 * does not increase in length)
25982 			 */
25983 		}
25984 		UNLOCK_IRE_FP_MP(ire);
25985 	} else {
25986 no_fp_mp:
25987 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25988 		if (mp1 == NULL) {
25989 unlock_err:
25990 			UNLOCK_IRE_FP_MP(ire);
25991 			freemsg(mp);
25992 			return (NULL);
25993 		}
25994 		UNLOCK_IRE_FP_MP(ire);
25995 		mp1->b_cont = mp;
25996 		/*
25997 		 * certain system generated traffic may not
25998 		 * have cred/label in ip header block. This
25999 		 * is true even for a labeled system. But for
26000 		 * labeled traffic, inherit the label in the
26001 		 * new header.
26002 		 */
26003 		if (DB_CRED(mp) != NULL)
26004 			mblk_setcred(mp1, DB_CRED(mp));
26005 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
26006 			ip_process(proc, &mp1, ill_index);
26007 			if (mp1 == NULL)
26008 				return (NULL);
26009 
26010 			if (mp1->b_cont == NULL)
26011 				ipha = NULL;
26012 			else
26013 				ipha = (ipha_t *)mp1->b_cont->b_rptr;
26014 		}
26015 	}
26016 
26017 	*iphap = ipha;
26018 	return (mp1);
26019 #undef rptr
26020 }
26021 
26022 /*
26023  * Finish the outbound IPsec processing for an IPv6 packet. This function
26024  * is called from ipsec_out_process() if the IPsec packet was processed
26025  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
26026  * asynchronously.
26027  */
26028 void
26029 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
26030     ire_t *ire_arg)
26031 {
26032 	in6_addr_t *v6dstp;
26033 	ire_t *ire;
26034 	mblk_t *mp;
26035 	ip6_t *ip6h1;
26036 	uint_t	ill_index;
26037 	ipsec_out_t *io;
26038 	boolean_t attach_if, hwaccel;
26039 	uint32_t flags = IP6_NO_IPPOLICY;
26040 	int match_flags;
26041 	zoneid_t zoneid;
26042 	boolean_t ill_need_rele = B_FALSE;
26043 	boolean_t ire_need_rele = B_FALSE;
26044 	ip_stack_t	*ipst;
26045 
26046 	mp = ipsec_mp->b_cont;
26047 	ip6h1 = (ip6_t *)mp->b_rptr;
26048 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26049 	ASSERT(io->ipsec_out_ns != NULL);
26050 	ipst = io->ipsec_out_ns->netstack_ip;
26051 	ill_index = io->ipsec_out_ill_index;
26052 	if (io->ipsec_out_reachable) {
26053 		flags |= IPV6_REACHABILITY_CONFIRMATION;
26054 	}
26055 	attach_if = io->ipsec_out_attach_if;
26056 	hwaccel = io->ipsec_out_accelerated;
26057 	zoneid = io->ipsec_out_zoneid;
26058 	ASSERT(zoneid != ALL_ZONES);
26059 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
26060 	/* Multicast addresses should have non-zero ill_index. */
26061 	v6dstp = &ip6h->ip6_dst;
26062 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
26063 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
26064 	ASSERT(!attach_if || ill_index != 0);
26065 	if (ill_index != 0) {
26066 		if (ill == NULL) {
26067 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
26068 			    B_TRUE, ipst);
26069 
26070 			/* Failure case frees things for us. */
26071 			if (ill == NULL)
26072 				return;
26073 
26074 			ill_need_rele = B_TRUE;
26075 		}
26076 		/*
26077 		 * If this packet needs to go out on a particular interface
26078 		 * honor it.
26079 		 */
26080 		if (attach_if) {
26081 			match_flags = MATCH_IRE_ILL;
26082 
26083 			/*
26084 			 * Check if we need an ire that will not be
26085 			 * looked up by anybody else i.e. HIDDEN.
26086 			 */
26087 			if (ill_is_probeonly(ill)) {
26088 				match_flags |= MATCH_IRE_MARK_HIDDEN;
26089 			}
26090 		}
26091 	}
26092 	ASSERT(mp != NULL);
26093 
26094 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
26095 		boolean_t unspec_src;
26096 		ipif_t	*ipif;
26097 
26098 		/*
26099 		 * Use the ill_index to get the right ill.
26100 		 */
26101 		unspec_src = io->ipsec_out_unspec_src;
26102 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
26103 		if (ipif == NULL) {
26104 			if (ill_need_rele)
26105 				ill_refrele(ill);
26106 			freemsg(ipsec_mp);
26107 			return;
26108 		}
26109 
26110 		if (ire_arg != NULL) {
26111 			ire = ire_arg;
26112 		} else {
26113 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
26114 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
26115 			ire_need_rele = B_TRUE;
26116 		}
26117 		if (ire != NULL) {
26118 			ipif_refrele(ipif);
26119 			/*
26120 			 * XXX Do the multicast forwarding now, as the IPsec
26121 			 * processing has been done.
26122 			 */
26123 			goto send;
26124 		}
26125 
26126 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
26127 		mp->b_prev = NULL;
26128 		mp->b_next = NULL;
26129 
26130 		/*
26131 		 * If the IPsec packet was processed asynchronously,
26132 		 * drop it now.
26133 		 */
26134 		if (q == NULL) {
26135 			if (ill_need_rele)
26136 				ill_refrele(ill);
26137 			freemsg(ipsec_mp);
26138 			return;
26139 		}
26140 
26141 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
26142 		    unspec_src, zoneid);
26143 		ipif_refrele(ipif);
26144 	} else {
26145 		if (attach_if) {
26146 			ipif_t	*ipif;
26147 
26148 			ipif = ipif_get_next_ipif(NULL, ill);
26149 			if (ipif == NULL) {
26150 				if (ill_need_rele)
26151 					ill_refrele(ill);
26152 				freemsg(ipsec_mp);
26153 				return;
26154 			}
26155 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
26156 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
26157 			ire_need_rele = B_TRUE;
26158 			ipif_refrele(ipif);
26159 		} else {
26160 			if (ire_arg != NULL) {
26161 				ire = ire_arg;
26162 			} else {
26163 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
26164 				    ipst);
26165 				ire_need_rele = B_TRUE;
26166 			}
26167 		}
26168 		if (ire != NULL)
26169 			goto send;
26170 		/*
26171 		 * ire disappeared underneath.
26172 		 *
26173 		 * What we need to do here is the ip_newroute
26174 		 * logic to get the ire without doing the IPsec
26175 		 * processing. Follow the same old path. But this
26176 		 * time, ip_wput or ire_add_then_send will call us
26177 		 * directly as all the IPsec operations are done.
26178 		 */
26179 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
26180 		mp->b_prev = NULL;
26181 		mp->b_next = NULL;
26182 
26183 		/*
26184 		 * If the IPsec packet was processed asynchronously,
26185 		 * drop it now.
26186 		 */
26187 		if (q == NULL) {
26188 			if (ill_need_rele)
26189 				ill_refrele(ill);
26190 			freemsg(ipsec_mp);
26191 			return;
26192 		}
26193 
26194 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
26195 		    zoneid, ipst);
26196 	}
26197 	if (ill != NULL && ill_need_rele)
26198 		ill_refrele(ill);
26199 	return;
26200 send:
26201 	if (ill != NULL && ill_need_rele)
26202 		ill_refrele(ill);
26203 
26204 	/* Local delivery */
26205 	if (ire->ire_stq == NULL) {
26206 		ill_t	*out_ill;
26207 		ASSERT(q != NULL);
26208 
26209 		/* PFHooks: LOOPBACK_OUT */
26210 		out_ill = ire_to_ill(ire);
26211 
26212 		/*
26213 		 * DTrace this as ip:::send.  A blocked packet will fire the
26214 		 * send probe, but not the receive probe.
26215 		 */
26216 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
26217 		    void_ip_t *, ip6h, __dtrace_ipsr_ill_t *, out_ill,
26218 		    ipha_t *, NULL, ip6_t *, ip6h, int, 1);
26219 
26220 		DTRACE_PROBE4(ip6__loopback__out__start,
26221 		    ill_t *, NULL, ill_t *, out_ill,
26222 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
26223 
26224 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
26225 		    ipst->ips_ipv6firewall_loopback_out,
26226 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
26227 
26228 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
26229 
26230 		if (ipsec_mp != NULL) {
26231 			ip_wput_local_v6(RD(q), out_ill,
26232 			    ip6h, ipsec_mp, ire, 0, zoneid);
26233 		}
26234 		if (ire_need_rele)
26235 			ire_refrele(ire);
26236 		return;
26237 	}
26238 	/*
26239 	 * Everything is done. Send it out on the wire.
26240 	 * We force the insertion of a fragment header using the
26241 	 * IPH_FRAG_HDR flag in two cases:
26242 	 * - after reception of an ICMPv6 "packet too big" message
26243 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
26244 	 * - for multirouted IPv6 packets, so that the receiver can
26245 	 *   discard duplicates according to their fragment identifier
26246 	 */
26247 	/* XXX fix flow control problems. */
26248 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
26249 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
26250 		if (hwaccel) {
26251 			/*
26252 			 * hardware acceleration does not handle these
26253 			 * "slow path" cases.
26254 			 */
26255 			/* IPsec KSTATS: should bump bean counter here. */
26256 			if (ire_need_rele)
26257 				ire_refrele(ire);
26258 			freemsg(ipsec_mp);
26259 			return;
26260 		}
26261 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
26262 		    (mp->b_cont ? msgdsize(mp) :
26263 		    mp->b_wptr - (uchar_t *)ip6h)) {
26264 			/* IPsec KSTATS: should bump bean counter here. */
26265 			ip0dbg(("Packet length mismatch: %d, %ld\n",
26266 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
26267 			    msgdsize(mp)));
26268 			if (ire_need_rele)
26269 				ire_refrele(ire);
26270 			freemsg(ipsec_mp);
26271 			return;
26272 		}
26273 		ASSERT(mp->b_prev == NULL);
26274 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
26275 		    ntohs(ip6h->ip6_plen) +
26276 		    IPV6_HDR_LEN, ire->ire_max_frag));
26277 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
26278 		    ire->ire_max_frag);
26279 	} else {
26280 		UPDATE_OB_PKT_COUNT(ire);
26281 		ire->ire_last_used_time = lbolt;
26282 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
26283 	}
26284 	if (ire_need_rele)
26285 		ire_refrele(ire);
26286 	freeb(ipsec_mp);
26287 }
26288 
26289 void
26290 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
26291 {
26292 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
26293 	da_ipsec_t *hada;	/* data attributes */
26294 	ill_t *ill = (ill_t *)q->q_ptr;
26295 
26296 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
26297 
26298 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
26299 		/* IPsec KSTATS: Bump lose counter here! */
26300 		freemsg(mp);
26301 		return;
26302 	}
26303 
26304 	/*
26305 	 * It's an IPsec packet that must be
26306 	 * accelerated by the Provider, and the
26307 	 * outbound ill is IPsec acceleration capable.
26308 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
26309 	 * to the ill.
26310 	 * IPsec KSTATS: should bump packet counter here.
26311 	 */
26312 
26313 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
26314 	if (hada_mp == NULL) {
26315 		/* IPsec KSTATS: should bump packet counter here. */
26316 		freemsg(mp);
26317 		return;
26318 	}
26319 
26320 	hada_mp->b_datap->db_type = M_CTL;
26321 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
26322 	hada_mp->b_cont = mp;
26323 
26324 	hada = (da_ipsec_t *)hada_mp->b_rptr;
26325 	bzero(hada, sizeof (da_ipsec_t));
26326 	hada->da_type = IPHADA_M_CTL;
26327 
26328 	putnext(q, hada_mp);
26329 }
26330 
26331 /*
26332  * Finish the outbound IPsec processing. This function is called from
26333  * ipsec_out_process() if the IPsec packet was processed
26334  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
26335  * asynchronously.
26336  */
26337 void
26338 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
26339     ire_t *ire_arg)
26340 {
26341 	uint32_t v_hlen_tos_len;
26342 	ipaddr_t	dst;
26343 	ipif_t	*ipif = NULL;
26344 	ire_t *ire;
26345 	ire_t *ire1 = NULL;
26346 	mblk_t *next_mp = NULL;
26347 	uint32_t max_frag;
26348 	boolean_t multirt_send = B_FALSE;
26349 	mblk_t *mp;
26350 	ipha_t *ipha1;
26351 	uint_t	ill_index;
26352 	ipsec_out_t *io;
26353 	boolean_t attach_if;
26354 	int match_flags;
26355 	irb_t *irb = NULL;
26356 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
26357 	zoneid_t zoneid;
26358 	ipxmit_state_t	pktxmit_state;
26359 	ip_stack_t	*ipst;
26360 
26361 #ifdef	_BIG_ENDIAN
26362 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
26363 #else
26364 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
26365 #endif
26366 
26367 	mp = ipsec_mp->b_cont;
26368 	ipha1 = (ipha_t *)mp->b_rptr;
26369 	ASSERT(mp != NULL);
26370 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
26371 	dst = ipha->ipha_dst;
26372 
26373 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26374 	ill_index = io->ipsec_out_ill_index;
26375 	attach_if = io->ipsec_out_attach_if;
26376 	zoneid = io->ipsec_out_zoneid;
26377 	ASSERT(zoneid != ALL_ZONES);
26378 	ipst = io->ipsec_out_ns->netstack_ip;
26379 	ASSERT(io->ipsec_out_ns != NULL);
26380 
26381 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
26382 	if (ill_index != 0) {
26383 		if (ill == NULL) {
26384 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
26385 			    ill_index, B_FALSE, ipst);
26386 
26387 			/* Failure case frees things for us. */
26388 			if (ill == NULL)
26389 				return;
26390 
26391 			ill_need_rele = B_TRUE;
26392 		}
26393 		/*
26394 		 * If this packet needs to go out on a particular interface
26395 		 * honor it.
26396 		 */
26397 		if (attach_if) {
26398 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
26399 
26400 			/*
26401 			 * Check if we need an ire that will not be
26402 			 * looked up by anybody else i.e. HIDDEN.
26403 			 */
26404 			if (ill_is_probeonly(ill)) {
26405 				match_flags |= MATCH_IRE_MARK_HIDDEN;
26406 			}
26407 		}
26408 	}
26409 
26410 	if (CLASSD(dst)) {
26411 		boolean_t conn_dontroute;
26412 		/*
26413 		 * Use the ill_index to get the right ipif.
26414 		 */
26415 		conn_dontroute = io->ipsec_out_dontroute;
26416 		if (ill_index == 0)
26417 			ipif = ipif_lookup_group(dst, zoneid, ipst);
26418 		else
26419 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
26420 		if (ipif == NULL) {
26421 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
26422 			    " multicast\n"));
26423 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
26424 			freemsg(ipsec_mp);
26425 			goto done;
26426 		}
26427 		/*
26428 		 * ipha_src has already been intialized with the
26429 		 * value of the ipif in ip_wput. All we need now is
26430 		 * an ire to send this downstream.
26431 		 */
26432 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
26433 		    MBLK_GETLABEL(mp), match_flags, ipst);
26434 		if (ire != NULL) {
26435 			ill_t *ill1;
26436 			/*
26437 			 * Do the multicast forwarding now, as the IPsec
26438 			 * processing has been done.
26439 			 */
26440 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
26441 			    (ill1 = ire_to_ill(ire))) {
26442 				if (ip_mforward(ill1, ipha, mp)) {
26443 					freemsg(ipsec_mp);
26444 					ip1dbg(("ip_wput_ipsec_out: mforward "
26445 					    "failed\n"));
26446 					ire_refrele(ire);
26447 					goto done;
26448 				}
26449 			}
26450 			goto send;
26451 		}
26452 
26453 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
26454 		mp->b_prev = NULL;
26455 		mp->b_next = NULL;
26456 
26457 		/*
26458 		 * If the IPsec packet was processed asynchronously,
26459 		 * drop it now.
26460 		 */
26461 		if (q == NULL) {
26462 			freemsg(ipsec_mp);
26463 			goto done;
26464 		}
26465 
26466 		/*
26467 		 * We may be using a wrong ipif to create the ire.
26468 		 * But it is okay as the source address is assigned
26469 		 * for the packet already. Next outbound packet would
26470 		 * create the IRE with the right IPIF in ip_wput.
26471 		 *
26472 		 * Also handle RTF_MULTIRT routes.
26473 		 */
26474 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26475 		    zoneid, &zero_info);
26476 	} else {
26477 		if (attach_if) {
26478 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
26479 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
26480 		} else {
26481 			if (ire_arg != NULL) {
26482 				ire = ire_arg;
26483 				ire_need_rele = B_FALSE;
26484 			} else {
26485 				ire = ire_cache_lookup(dst, zoneid,
26486 				    MBLK_GETLABEL(mp), ipst);
26487 			}
26488 		}
26489 		if (ire != NULL) {
26490 			goto send;
26491 		}
26492 
26493 		/*
26494 		 * ire disappeared underneath.
26495 		 *
26496 		 * What we need to do here is the ip_newroute
26497 		 * logic to get the ire without doing the IPsec
26498 		 * processing. Follow the same old path. But this
26499 		 * time, ip_wput or ire_add_then_put will call us
26500 		 * directly as all the IPsec operations are done.
26501 		 */
26502 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26503 		mp->b_prev = NULL;
26504 		mp->b_next = NULL;
26505 
26506 		/*
26507 		 * If the IPsec packet was processed asynchronously,
26508 		 * drop it now.
26509 		 */
26510 		if (q == NULL) {
26511 			freemsg(ipsec_mp);
26512 			goto done;
26513 		}
26514 
26515 		/*
26516 		 * Since we're going through ip_newroute() again, we
26517 		 * need to make sure we don't:
26518 		 *
26519 		 *	1.) Trigger the ASSERT() with the ipha_ident
26520 		 *	    overloading.
26521 		 *	2.) Redo transport-layer checksumming, since we've
26522 		 *	    already done all that to get this far.
26523 		 *
26524 		 * The easiest way not do either of the above is to set
26525 		 * the ipha_ident field to IP_HDR_INCLUDED.
26526 		 */
26527 		ipha->ipha_ident = IP_HDR_INCLUDED;
26528 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
26529 		    zoneid, ipst);
26530 	}
26531 	goto done;
26532 send:
26533 	if (ire->ire_stq == NULL) {
26534 		ill_t	*out_ill;
26535 		/*
26536 		 * Loopbacks go through ip_wput_local except for one case.
26537 		 * We come here if we generate a icmp_frag_needed message
26538 		 * after IPsec processing is over. When this function calls
26539 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26540 		 * icmp_frag_needed. The message generated comes back here
26541 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26542 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26543 		 * source address as it is usually set in ip_wput_ire. As
26544 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26545 		 * and we end up here. We can't enter ip_wput_ire once the
26546 		 * IPsec processing is over and hence we need to do it here.
26547 		 */
26548 		ASSERT(q != NULL);
26549 		UPDATE_OB_PKT_COUNT(ire);
26550 		ire->ire_last_used_time = lbolt;
26551 		if (ipha->ipha_src == 0)
26552 			ipha->ipha_src = ire->ire_src_addr;
26553 
26554 		/* PFHooks: LOOPBACK_OUT */
26555 		out_ill = ire_to_ill(ire);
26556 
26557 		/*
26558 		 * DTrace this as ip:::send.  A blocked packet will fire the
26559 		 * send probe, but not the receive probe.
26560 		 */
26561 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
26562 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
26563 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
26564 
26565 		DTRACE_PROBE4(ip4__loopback__out__start,
26566 		    ill_t *, NULL, ill_t *, out_ill,
26567 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26568 
26569 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26570 		    ipst->ips_ipv4firewall_loopback_out,
26571 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
26572 
26573 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26574 
26575 		if (ipsec_mp != NULL)
26576 			ip_wput_local(RD(q), out_ill,
26577 			    ipha, ipsec_mp, ire, 0, zoneid);
26578 		if (ire_need_rele)
26579 			ire_refrele(ire);
26580 		goto done;
26581 	}
26582 
26583 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26584 		/*
26585 		 * We are through with IPsec processing.
26586 		 * Fragment this and send it on the wire.
26587 		 */
26588 		if (io->ipsec_out_accelerated) {
26589 			/*
26590 			 * The packet has been accelerated but must
26591 			 * be fragmented. This should not happen
26592 			 * since AH and ESP must not accelerate
26593 			 * packets that need fragmentation, however
26594 			 * the configuration could have changed
26595 			 * since the AH or ESP processing.
26596 			 * Drop packet.
26597 			 * IPsec KSTATS: bump bean counter here.
26598 			 */
26599 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26600 			    "fragmented accelerated packet!\n"));
26601 			freemsg(ipsec_mp);
26602 		} else {
26603 			ip_wput_ire_fragmentit(ipsec_mp, ire,
26604 			    zoneid, ipst, NULL);
26605 		}
26606 		if (ire_need_rele)
26607 			ire_refrele(ire);
26608 		goto done;
26609 	}
26610 
26611 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26612 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26613 	    (void *)ire->ire_ipif, (void *)ipif));
26614 
26615 	/*
26616 	 * Multiroute the secured packet, unless IPsec really
26617 	 * requires the packet to go out only through a particular
26618 	 * interface.
26619 	 */
26620 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26621 		ire_t *first_ire;
26622 		irb = ire->ire_bucket;
26623 		ASSERT(irb != NULL);
26624 		/*
26625 		 * This ire has been looked up as the one that
26626 		 * goes through the given ipif;
26627 		 * make sure we do not omit any other multiroute ire
26628 		 * that may be present in the bucket before this one.
26629 		 */
26630 		IRB_REFHOLD(irb);
26631 		for (first_ire = irb->irb_ire;
26632 		    first_ire != NULL;
26633 		    first_ire = first_ire->ire_next) {
26634 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26635 			    (first_ire->ire_addr == ire->ire_addr) &&
26636 			    !(first_ire->ire_marks &
26637 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26638 				break;
26639 			}
26640 		}
26641 
26642 		if ((first_ire != NULL) && (first_ire != ire)) {
26643 			/*
26644 			 * Don't change the ire if the packet must
26645 			 * be fragmented if sent via this new one.
26646 			 */
26647 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26648 				IRE_REFHOLD(first_ire);
26649 				if (ire_need_rele)
26650 					ire_refrele(ire);
26651 				else
26652 					ire_need_rele = B_TRUE;
26653 				ire = first_ire;
26654 			}
26655 		}
26656 		IRB_REFRELE(irb);
26657 
26658 		multirt_send = B_TRUE;
26659 		max_frag = ire->ire_max_frag;
26660 	} else {
26661 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26662 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26663 			    "flag, attach_if %d\n", attach_if));
26664 		}
26665 	}
26666 
26667 	/*
26668 	 * In most cases, the emission loop below is entered only once.
26669 	 * Only in the case where the ire holds the RTF_MULTIRT
26670 	 * flag, we loop to process all RTF_MULTIRT ires in the
26671 	 * bucket, and send the packet through all crossed
26672 	 * RTF_MULTIRT routes.
26673 	 */
26674 	do {
26675 		if (multirt_send) {
26676 			/*
26677 			 * ire1 holds here the next ire to process in the
26678 			 * bucket. If multirouting is expected,
26679 			 * any non-RTF_MULTIRT ire that has the
26680 			 * right destination address is ignored.
26681 			 */
26682 			ASSERT(irb != NULL);
26683 			IRB_REFHOLD(irb);
26684 			for (ire1 = ire->ire_next;
26685 			    ire1 != NULL;
26686 			    ire1 = ire1->ire_next) {
26687 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26688 					continue;
26689 				if (ire1->ire_addr != ire->ire_addr)
26690 					continue;
26691 				if (ire1->ire_marks &
26692 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26693 					continue;
26694 				/* No loopback here */
26695 				if (ire1->ire_stq == NULL)
26696 					continue;
26697 				/*
26698 				 * Ensure we do not exceed the MTU
26699 				 * of the next route.
26700 				 */
26701 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26702 					ip_multirt_bad_mtu(ire1, max_frag);
26703 					continue;
26704 				}
26705 
26706 				IRE_REFHOLD(ire1);
26707 				break;
26708 			}
26709 			IRB_REFRELE(irb);
26710 			if (ire1 != NULL) {
26711 				/*
26712 				 * We are in a multiple send case, need to
26713 				 * make a copy of the packet.
26714 				 */
26715 				next_mp = copymsg(ipsec_mp);
26716 				if (next_mp == NULL) {
26717 					ire_refrele(ire1);
26718 					ire1 = NULL;
26719 				}
26720 			}
26721 		}
26722 		/*
26723 		 * Everything is done. Send it out on the wire
26724 		 *
26725 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26726 		 * either send it on the wire or, in the case of
26727 		 * HW acceleration, call ipsec_hw_putnext.
26728 		 */
26729 		if (ire->ire_nce &&
26730 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26731 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26732 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26733 			/*
26734 			 * If ire's link-layer is unresolved (this
26735 			 * would only happen if the incomplete ire
26736 			 * was added to cachetable via forwarding path)
26737 			 * don't bother going to ip_xmit_v4. Just drop the
26738 			 * packet.
26739 			 * There is a slight risk here, in that, if we
26740 			 * have the forwarding path create an incomplete
26741 			 * IRE, then until the IRE is completed, any
26742 			 * transmitted IPsec packets will be dropped
26743 			 * instead of being queued waiting for resolution.
26744 			 *
26745 			 * But the likelihood of a forwarding packet and a wput
26746 			 * packet sending to the same dst at the same time
26747 			 * and there not yet be an ARP entry for it is small.
26748 			 * Furthermore, if this actually happens, it might
26749 			 * be likely that wput would generate multiple
26750 			 * packets (and forwarding would also have a train
26751 			 * of packets) for that destination. If this is
26752 			 * the case, some of them would have been dropped
26753 			 * anyway, since ARP only queues a few packets while
26754 			 * waiting for resolution
26755 			 *
26756 			 * NOTE: We should really call ip_xmit_v4,
26757 			 * and let it queue the packet and send the
26758 			 * ARP query and have ARP come back thus:
26759 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26760 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26761 			 * hw accel work. But it's too complex to get
26762 			 * the IPsec hw  acceleration approach to fit
26763 			 * well with ip_xmit_v4 doing ARP without
26764 			 * doing IPsec simplification. For now, we just
26765 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26766 			 * that we can continue with the send on the next
26767 			 * attempt.
26768 			 *
26769 			 * XXX THis should be revisited, when
26770 			 * the IPsec/IP interaction is cleaned up
26771 			 */
26772 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26773 			    " - dropping packet\n"));
26774 			freemsg(ipsec_mp);
26775 			/*
26776 			 * Call ip_xmit_v4() to trigger ARP query
26777 			 * in case the nce_state is ND_INITIAL
26778 			 */
26779 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
26780 			goto drop_pkt;
26781 		}
26782 
26783 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26784 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26785 		    mblk_t *, ipsec_mp);
26786 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26787 		    ipst->ips_ipv4firewall_physical_out, NULL,
26788 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26789 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26790 		if (ipsec_mp == NULL)
26791 			goto drop_pkt;
26792 
26793 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26794 		pktxmit_state = ip_xmit_v4(mp, ire,
26795 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE, NULL);
26796 
26797 		if ((pktxmit_state ==  SEND_FAILED) ||
26798 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26799 
26800 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26801 drop_pkt:
26802 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26803 			    ipIfStatsOutDiscards);
26804 			if (ire_need_rele)
26805 				ire_refrele(ire);
26806 			if (ire1 != NULL) {
26807 				ire_refrele(ire1);
26808 				freemsg(next_mp);
26809 			}
26810 			goto done;
26811 		}
26812 
26813 		freeb(ipsec_mp);
26814 		if (ire_need_rele)
26815 			ire_refrele(ire);
26816 
26817 		if (ire1 != NULL) {
26818 			ire = ire1;
26819 			ire_need_rele = B_TRUE;
26820 			ASSERT(next_mp);
26821 			ipsec_mp = next_mp;
26822 			mp = ipsec_mp->b_cont;
26823 			ire1 = NULL;
26824 			next_mp = NULL;
26825 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26826 		} else {
26827 			multirt_send = B_FALSE;
26828 		}
26829 	} while (multirt_send);
26830 done:
26831 	if (ill != NULL && ill_need_rele)
26832 		ill_refrele(ill);
26833 	if (ipif != NULL)
26834 		ipif_refrele(ipif);
26835 }
26836 
26837 /*
26838  * Get the ill corresponding to the specified ire, and compare its
26839  * capabilities with the protocol and algorithms specified by the
26840  * the SA obtained from ipsec_out. If they match, annotate the
26841  * ipsec_out structure to indicate that the packet needs acceleration.
26842  *
26843  *
26844  * A packet is eligible for outbound hardware acceleration if the
26845  * following conditions are satisfied:
26846  *
26847  * 1. the packet will not be fragmented
26848  * 2. the provider supports the algorithm
26849  * 3. there is no pending control message being exchanged
26850  * 4. snoop is not attached
26851  * 5. the destination address is not a broadcast or multicast address.
26852  *
26853  * Rationale:
26854  *	- Hardware drivers do not support fragmentation with
26855  *	  the current interface.
26856  *	- snoop, multicast, and broadcast may result in exposure of
26857  *	  a cleartext datagram.
26858  * We check all five of these conditions here.
26859  *
26860  * XXX would like to nuke "ire_t *" parameter here; problem is that
26861  * IRE is only way to figure out if a v4 address is a broadcast and
26862  * thus ineligible for acceleration...
26863  */
26864 static void
26865 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26866 {
26867 	ipsec_out_t *io;
26868 	mblk_t *data_mp;
26869 	uint_t plen, overhead;
26870 	ip_stack_t	*ipst;
26871 
26872 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26873 		return;
26874 
26875 	if (ill == NULL)
26876 		return;
26877 	ipst = ill->ill_ipst;
26878 	/*
26879 	 * Destination address is a broadcast or multicast.  Punt.
26880 	 */
26881 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26882 	    IRE_LOCAL)))
26883 		return;
26884 
26885 	data_mp = ipsec_mp->b_cont;
26886 
26887 	if (ill->ill_isv6) {
26888 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26889 
26890 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26891 			return;
26892 
26893 		plen = ip6h->ip6_plen;
26894 	} else {
26895 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26896 
26897 		if (CLASSD(ipha->ipha_dst))
26898 			return;
26899 
26900 		plen = ipha->ipha_length;
26901 	}
26902 	/*
26903 	 * Is there a pending DLPI control message being exchanged
26904 	 * between IP/IPsec and the DLS Provider? If there is, it
26905 	 * could be a SADB update, and the state of the DLS Provider
26906 	 * SADB might not be in sync with the SADB maintained by
26907 	 * IPsec. To avoid dropping packets or using the wrong keying
26908 	 * material, we do not accelerate this packet.
26909 	 */
26910 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26911 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26912 		    "ill_dlpi_pending! don't accelerate packet\n"));
26913 		return;
26914 	}
26915 
26916 	/*
26917 	 * Is the Provider in promiscous mode? If it does, we don't
26918 	 * accelerate the packet since it will bounce back up to the
26919 	 * listeners in the clear.
26920 	 */
26921 	if (ill->ill_promisc_on_phys) {
26922 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26923 		    "ill in promiscous mode, don't accelerate packet\n"));
26924 		return;
26925 	}
26926 
26927 	/*
26928 	 * Will the packet require fragmentation?
26929 	 */
26930 
26931 	/*
26932 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26933 	 * as is used elsewhere.
26934 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26935 	 *	+ 2-byte trailer
26936 	 */
26937 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26938 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26939 
26940 	if ((plen + overhead) > ill->ill_max_mtu)
26941 		return;
26942 
26943 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26944 
26945 	/*
26946 	 * Can the ill accelerate this IPsec protocol and algorithm
26947 	 * specified by the SA?
26948 	 */
26949 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26950 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26951 		return;
26952 	}
26953 
26954 	/*
26955 	 * Tell AH or ESP that the outbound ill is capable of
26956 	 * accelerating this packet.
26957 	 */
26958 	io->ipsec_out_is_capab_ill = B_TRUE;
26959 }
26960 
26961 /*
26962  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26963  *
26964  * If this function returns B_TRUE, the requested SA's have been filled
26965  * into the ipsec_out_*_sa pointers.
26966  *
26967  * If the function returns B_FALSE, the packet has been "consumed", most
26968  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26969  *
26970  * The SA references created by the protocol-specific "select"
26971  * function will be released when the ipsec_mp is freed, thanks to the
26972  * ipsec_out_free destructor -- see spd.c.
26973  */
26974 static boolean_t
26975 ipsec_out_select_sa(mblk_t *ipsec_mp)
26976 {
26977 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26978 	ipsec_out_t *io;
26979 	ipsec_policy_t *pp;
26980 	ipsec_action_t *ap;
26981 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26982 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26983 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26984 
26985 	if (!io->ipsec_out_secure) {
26986 		/*
26987 		 * We came here by mistake.
26988 		 * Don't bother with ipsec processing
26989 		 * We should "discourage" this path in the future.
26990 		 */
26991 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26992 		return (B_FALSE);
26993 	}
26994 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26995 	ASSERT((io->ipsec_out_policy != NULL) ||
26996 	    (io->ipsec_out_act != NULL));
26997 
26998 	ASSERT(io->ipsec_out_failed == B_FALSE);
26999 
27000 	/*
27001 	 * IPsec processing has started.
27002 	 */
27003 	io->ipsec_out_proc_begin = B_TRUE;
27004 	ap = io->ipsec_out_act;
27005 	if (ap == NULL) {
27006 		pp = io->ipsec_out_policy;
27007 		ASSERT(pp != NULL);
27008 		ap = pp->ipsp_act;
27009 		ASSERT(ap != NULL);
27010 	}
27011 
27012 	/*
27013 	 * We have an action.  now, let's select SA's.
27014 	 * (In the future, we can cache this in the conn_t..)
27015 	 */
27016 	if (ap->ipa_want_esp) {
27017 		if (io->ipsec_out_esp_sa == NULL) {
27018 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
27019 			    IPPROTO_ESP);
27020 		}
27021 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
27022 	}
27023 
27024 	if (ap->ipa_want_ah) {
27025 		if (io->ipsec_out_ah_sa == NULL) {
27026 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
27027 			    IPPROTO_AH);
27028 		}
27029 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
27030 		/*
27031 		 * The ESP and AH processing order needs to be preserved
27032 		 * when both protocols are required (ESP should be applied
27033 		 * before AH for an outbound packet). Force an ESP ACQUIRE
27034 		 * when both ESP and AH are required, and an AH ACQUIRE
27035 		 * is needed.
27036 		 */
27037 		if (ap->ipa_want_esp && need_ah_acquire)
27038 			need_esp_acquire = B_TRUE;
27039 	}
27040 
27041 	/*
27042 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
27043 	 * Release SAs that got referenced, but will not be used until we
27044 	 * acquire _all_ of the SAs we need.
27045 	 */
27046 	if (need_ah_acquire || need_esp_acquire) {
27047 		if (io->ipsec_out_ah_sa != NULL) {
27048 			IPSA_REFRELE(io->ipsec_out_ah_sa);
27049 			io->ipsec_out_ah_sa = NULL;
27050 		}
27051 		if (io->ipsec_out_esp_sa != NULL) {
27052 			IPSA_REFRELE(io->ipsec_out_esp_sa);
27053 			io->ipsec_out_esp_sa = NULL;
27054 		}
27055 
27056 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
27057 		return (B_FALSE);
27058 	}
27059 
27060 	return (B_TRUE);
27061 }
27062 
27063 /*
27064  * Process an IPSEC_OUT message and see what you can
27065  * do with it.
27066  * IPQoS Notes:
27067  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
27068  * IPsec.
27069  * XXX would like to nuke ire_t.
27070  * XXX ill_index better be "real"
27071  */
27072 void
27073 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
27074 {
27075 	ipsec_out_t *io;
27076 	ipsec_policy_t *pp;
27077 	ipsec_action_t *ap;
27078 	ipha_t *ipha;
27079 	ip6_t *ip6h;
27080 	mblk_t *mp;
27081 	ill_t *ill;
27082 	zoneid_t zoneid;
27083 	ipsec_status_t ipsec_rc;
27084 	boolean_t ill_need_rele = B_FALSE;
27085 	ip_stack_t	*ipst;
27086 	ipsec_stack_t	*ipss;
27087 
27088 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
27089 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
27090 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
27091 	ipst = io->ipsec_out_ns->netstack_ip;
27092 	mp = ipsec_mp->b_cont;
27093 
27094 	/*
27095 	 * Initiate IPPF processing. We do it here to account for packets
27096 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
27097 	 * We can check for ipsec_out_proc_begin even for such packets, as
27098 	 * they will always be false (asserted below).
27099 	 */
27100 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
27101 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
27102 		    io->ipsec_out_ill_index : ill_index);
27103 		if (mp == NULL) {
27104 			ip2dbg(("ipsec_out_process: packet dropped "\
27105 			    "during IPPF processing\n"));
27106 			freeb(ipsec_mp);
27107 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
27108 			return;
27109 		}
27110 	}
27111 
27112 	if (!io->ipsec_out_secure) {
27113 		/*
27114 		 * We came here by mistake.
27115 		 * Don't bother with ipsec processing
27116 		 * Should "discourage" this path in the future.
27117 		 */
27118 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
27119 		goto done;
27120 	}
27121 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
27122 	ASSERT((io->ipsec_out_policy != NULL) ||
27123 	    (io->ipsec_out_act != NULL));
27124 	ASSERT(io->ipsec_out_failed == B_FALSE);
27125 
27126 	ipss = ipst->ips_netstack->netstack_ipsec;
27127 	if (!ipsec_loaded(ipss)) {
27128 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
27129 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
27130 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
27131 		} else {
27132 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
27133 		}
27134 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
27135 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
27136 		    &ipss->ipsec_dropper);
27137 		return;
27138 	}
27139 
27140 	/*
27141 	 * IPsec processing has started.
27142 	 */
27143 	io->ipsec_out_proc_begin = B_TRUE;
27144 	ap = io->ipsec_out_act;
27145 	if (ap == NULL) {
27146 		pp = io->ipsec_out_policy;
27147 		ASSERT(pp != NULL);
27148 		ap = pp->ipsp_act;
27149 		ASSERT(ap != NULL);
27150 	}
27151 
27152 	/*
27153 	 * Save the outbound ill index. When the packet comes back
27154 	 * from IPsec, we make sure the ill hasn't changed or disappeared
27155 	 * before sending it the accelerated packet.
27156 	 */
27157 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
27158 		int ifindex;
27159 		ill = ire_to_ill(ire);
27160 		ifindex = ill->ill_phyint->phyint_ifindex;
27161 		io->ipsec_out_capab_ill_index = ifindex;
27162 	}
27163 
27164 	/*
27165 	 * The order of processing is first insert a IP header if needed.
27166 	 * Then insert the ESP header and then the AH header.
27167 	 */
27168 	if ((io->ipsec_out_se_done == B_FALSE) &&
27169 	    (ap->ipa_want_se)) {
27170 		/*
27171 		 * First get the outer IP header before sending
27172 		 * it to ESP.
27173 		 */
27174 		ipha_t *oipha, *iipha;
27175 		mblk_t *outer_mp, *inner_mp;
27176 
27177 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
27178 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
27179 			    "ipsec_out_process: "
27180 			    "Self-Encapsulation failed: Out of memory\n");
27181 			freemsg(ipsec_mp);
27182 			if (ill != NULL) {
27183 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
27184 			} else {
27185 				BUMP_MIB(&ipst->ips_ip_mib,
27186 				    ipIfStatsOutDiscards);
27187 			}
27188 			return;
27189 		}
27190 		inner_mp = ipsec_mp->b_cont;
27191 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
27192 		oipha = (ipha_t *)outer_mp->b_rptr;
27193 		iipha = (ipha_t *)inner_mp->b_rptr;
27194 		*oipha = *iipha;
27195 		outer_mp->b_wptr += sizeof (ipha_t);
27196 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
27197 		    sizeof (ipha_t));
27198 		oipha->ipha_protocol = IPPROTO_ENCAP;
27199 		oipha->ipha_version_and_hdr_length =
27200 		    IP_SIMPLE_HDR_VERSION;
27201 		oipha->ipha_hdr_checksum = 0;
27202 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
27203 		outer_mp->b_cont = inner_mp;
27204 		ipsec_mp->b_cont = outer_mp;
27205 
27206 		io->ipsec_out_se_done = B_TRUE;
27207 		io->ipsec_out_tunnel = B_TRUE;
27208 	}
27209 
27210 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
27211 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
27212 	    !ipsec_out_select_sa(ipsec_mp))
27213 		return;
27214 
27215 	/*
27216 	 * By now, we know what SA's to use.  Toss over to ESP & AH
27217 	 * to do the heavy lifting.
27218 	 */
27219 	zoneid = io->ipsec_out_zoneid;
27220 	ASSERT(zoneid != ALL_ZONES);
27221 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
27222 		ASSERT(io->ipsec_out_esp_sa != NULL);
27223 		io->ipsec_out_esp_done = B_TRUE;
27224 		/*
27225 		 * Note that since hw accel can only apply one transform,
27226 		 * not two, we skip hw accel for ESP if we also have AH
27227 		 * This is an design limitation of the interface
27228 		 * which should be revisited.
27229 		 */
27230 		ASSERT(ire != NULL);
27231 		if (io->ipsec_out_ah_sa == NULL) {
27232 			ill = (ill_t *)ire->ire_stq->q_ptr;
27233 			ipsec_out_is_accelerated(ipsec_mp,
27234 			    io->ipsec_out_esp_sa, ill, ire);
27235 		}
27236 
27237 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
27238 		switch (ipsec_rc) {
27239 		case IPSEC_STATUS_SUCCESS:
27240 			break;
27241 		case IPSEC_STATUS_FAILED:
27242 			if (ill != NULL) {
27243 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
27244 			} else {
27245 				BUMP_MIB(&ipst->ips_ip_mib,
27246 				    ipIfStatsOutDiscards);
27247 			}
27248 			/* FALLTHRU */
27249 		case IPSEC_STATUS_PENDING:
27250 			return;
27251 		}
27252 	}
27253 
27254 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
27255 		ASSERT(io->ipsec_out_ah_sa != NULL);
27256 		io->ipsec_out_ah_done = B_TRUE;
27257 		if (ire == NULL) {
27258 			int idx = io->ipsec_out_capab_ill_index;
27259 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
27260 			    NULL, NULL, NULL, NULL, ipst);
27261 			ill_need_rele = B_TRUE;
27262 		} else {
27263 			ill = (ill_t *)ire->ire_stq->q_ptr;
27264 		}
27265 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
27266 		    ire);
27267 
27268 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
27269 		switch (ipsec_rc) {
27270 		case IPSEC_STATUS_SUCCESS:
27271 			break;
27272 		case IPSEC_STATUS_FAILED:
27273 			if (ill != NULL) {
27274 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
27275 			} else {
27276 				BUMP_MIB(&ipst->ips_ip_mib,
27277 				    ipIfStatsOutDiscards);
27278 			}
27279 			/* FALLTHRU */
27280 		case IPSEC_STATUS_PENDING:
27281 			if (ill != NULL && ill_need_rele)
27282 				ill_refrele(ill);
27283 			return;
27284 		}
27285 	}
27286 	/*
27287 	 * We are done with IPsec processing. Send it over
27288 	 * the wire.
27289 	 */
27290 done:
27291 	mp = ipsec_mp->b_cont;
27292 	ipha = (ipha_t *)mp->b_rptr;
27293 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
27294 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
27295 	} else {
27296 		ip6h = (ip6_t *)ipha;
27297 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
27298 	}
27299 	if (ill != NULL && ill_need_rele)
27300 		ill_refrele(ill);
27301 }
27302 
27303 /* ARGSUSED */
27304 void
27305 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
27306 {
27307 	opt_restart_t	*or;
27308 	int	err;
27309 	conn_t	*connp;
27310 
27311 	ASSERT(CONN_Q(q));
27312 	connp = Q_TO_CONN(q);
27313 
27314 	ASSERT(first_mp->b_datap->db_type == M_CTL);
27315 	or = (opt_restart_t *)first_mp->b_rptr;
27316 	/*
27317 	 * We don't need to pass any credentials here since this is just
27318 	 * a restart. The credentials are passed in when svr4_optcom_req
27319 	 * is called the first time (from ip_wput_nondata).
27320 	 */
27321 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
27322 		err = svr4_optcom_req(q, first_mp, NULL,
27323 		    &ip_opt_obj, B_FALSE);
27324 	} else {
27325 		ASSERT(or->or_type == T_OPTMGMT_REQ);
27326 		err = tpi_optcom_req(q, first_mp, NULL,
27327 		    &ip_opt_obj, B_FALSE);
27328 	}
27329 	if (err != EINPROGRESS) {
27330 		/* operation is done */
27331 		CONN_OPER_PENDING_DONE(connp);
27332 	}
27333 }
27334 
27335 /*
27336  * ioctls that go through a down/up sequence may need to wait for the down
27337  * to complete. This involves waiting for the ire and ipif refcnts to go down
27338  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
27339  */
27340 /* ARGSUSED */
27341 void
27342 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27343 {
27344 	struct iocblk *iocp;
27345 	mblk_t *mp1;
27346 	ip_ioctl_cmd_t *ipip;
27347 	int err;
27348 	sin_t	*sin;
27349 	struct lifreq *lifr;
27350 	struct ifreq *ifr;
27351 
27352 	iocp = (struct iocblk *)mp->b_rptr;
27353 	ASSERT(ipsq != NULL);
27354 	/* Existence of mp1 verified in ip_wput_nondata */
27355 	mp1 = mp->b_cont->b_cont;
27356 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27357 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
27358 		/*
27359 		 * Special case where ipsq_current_ipif is not set:
27360 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
27361 		 * ill could also have become part of a ipmp group in the
27362 		 * process, we are here as were not able to complete the
27363 		 * operation in ipif_set_values because we could not become
27364 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
27365 		 * will not be set so we need to set it.
27366 		 */
27367 		ill_t *ill = q->q_ptr;
27368 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
27369 	}
27370 	ASSERT(ipsq->ipsq_current_ipif != NULL);
27371 
27372 	if (ipip->ipi_cmd_type == IF_CMD) {
27373 		/* This a old style SIOC[GS]IF* command */
27374 		ifr = (struct ifreq *)mp1->b_rptr;
27375 		sin = (sin_t *)&ifr->ifr_addr;
27376 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
27377 		/* This a new style SIOC[GS]LIF* command */
27378 		lifr = (struct lifreq *)mp1->b_rptr;
27379 		sin = (sin_t *)&lifr->lifr_addr;
27380 	} else {
27381 		sin = NULL;
27382 	}
27383 
27384 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
27385 	    ipip, mp1->b_rptr);
27386 
27387 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27388 }
27389 
27390 /*
27391  * ioctl processing
27392  *
27393  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
27394  * the ioctl command in the ioctl tables, determines the copyin data size
27395  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
27396  *
27397  * ioctl processing then continues when the M_IOCDATA makes its way down to
27398  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
27399  * associated 'conn' is refheld till the end of the ioctl and the general
27400  * ioctl processing function ip_process_ioctl() is called to extract the
27401  * arguments and process the ioctl.  To simplify extraction, ioctl commands
27402  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
27403  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
27404  * is used to extract the ioctl's arguments.
27405  *
27406  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
27407  * so goes thru the serialization primitive ipsq_try_enter. Then the
27408  * appropriate function to handle the ioctl is called based on the entry in
27409  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
27410  * which also refreleases the 'conn' that was refheld at the start of the
27411  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
27412  *
27413  * Many exclusive ioctls go thru an internal down up sequence as part of
27414  * the operation. For example an attempt to change the IP address of an
27415  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
27416  * does all the cleanup such as deleting all ires that use this address.
27417  * Then we need to wait till all references to the interface go away.
27418  */
27419 void
27420 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
27421 {
27422 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
27423 	ip_ioctl_cmd_t *ipip = arg;
27424 	ip_extract_func_t *extract_funcp;
27425 	cmd_info_t ci;
27426 	int err;
27427 
27428 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
27429 
27430 	if (ipip == NULL)
27431 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27432 
27433 	/*
27434 	 * SIOCLIFADDIF needs to go thru a special path since the
27435 	 * ill may not exist yet. This happens in the case of lo0
27436 	 * which is created using this ioctl.
27437 	 */
27438 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
27439 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
27440 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27441 		return;
27442 	}
27443 
27444 	ci.ci_ipif = NULL;
27445 	if (ipip->ipi_cmd_type == MISC_CMD) {
27446 		/*
27447 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
27448 		 */
27449 		if (ipip->ipi_cmd == IF_UNITSEL) {
27450 			/* ioctl comes down the ill */
27451 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
27452 			ipif_refhold(ci.ci_ipif);
27453 		}
27454 		err = 0;
27455 		ci.ci_sin = NULL;
27456 		ci.ci_sin6 = NULL;
27457 		ci.ci_lifr = NULL;
27458 	} else {
27459 		switch (ipip->ipi_cmd_type) {
27460 		case IF_CMD:
27461 		case LIF_CMD:
27462 			extract_funcp = ip_extract_lifreq;
27463 			break;
27464 
27465 		case ARP_CMD:
27466 		case XARP_CMD:
27467 			extract_funcp = ip_extract_arpreq;
27468 			break;
27469 
27470 		case TUN_CMD:
27471 			extract_funcp = ip_extract_tunreq;
27472 			break;
27473 
27474 		case MSFILT_CMD:
27475 			extract_funcp = ip_extract_msfilter;
27476 			break;
27477 
27478 		default:
27479 			ASSERT(0);
27480 		}
27481 
27482 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
27483 		if (err != 0) {
27484 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27485 			return;
27486 		}
27487 
27488 		/*
27489 		 * All of the extraction functions return a refheld ipif.
27490 		 */
27491 		ASSERT(ci.ci_ipif != NULL);
27492 	}
27493 
27494 	if (!(ipip->ipi_flags & IPI_WR)) {
27495 		/*
27496 		 * A return value of EINPROGRESS means the ioctl is
27497 		 * either queued and waiting for some reason or has
27498 		 * already completed.
27499 		 */
27500 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27501 		    ci.ci_lifr);
27502 		if (ci.ci_ipif != NULL)
27503 			ipif_refrele(ci.ci_ipif);
27504 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27505 		return;
27506 	}
27507 
27508 	/*
27509 	 * If ipsq is non-null, we are already being called exclusively on an
27510 	 * ill but in the case of a failover in progress it is the "from" ill,
27511 	 *  rather than the "to" ill (which is the ill ptr passed in).
27512 	 * In order to ensure we are exclusive on both ILLs we rerun
27513 	 * ipsq_try_enter() here, ipsq's support recursive entry.
27514 	 */
27515 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27516 	ASSERT(ci.ci_ipif != NULL);
27517 
27518 	ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
27519 	    NEW_OP, B_TRUE);
27520 
27521 	/*
27522 	 * Release the ipif so that ipif_down and friends that wait for
27523 	 * references to go away are not misled about the current ipif_refcnt
27524 	 * values. We are writer so we can access the ipif even after releasing
27525 	 * the ipif.
27526 	 */
27527 	ipif_refrele(ci.ci_ipif);
27528 	if (ipsq == NULL)
27529 		return;
27530 
27531 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27532 
27533 	/*
27534 	 * For most set ioctls that come here, this serves as a single point
27535 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27536 	 * be any new references to the ipif. This helps functions that go
27537 	 * through this path and end up trying to wait for the refcnts
27538 	 * associated with the ipif to go down to zero. Some exceptions are
27539 	 * Failover, Failback, and Groupname commands that operate on more than
27540 	 * just the ci.ci_ipif. These commands internally determine the
27541 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
27542 	 * flags on that set. Another exception is the Removeif command that
27543 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
27544 	 * ipif to operate on.
27545 	 */
27546 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27547 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27548 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27549 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27550 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27551 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27552 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27553 
27554 	/*
27555 	 * A return value of EINPROGRESS means the ioctl is
27556 	 * either queued and waiting for some reason or has
27557 	 * already completed.
27558 	 */
27559 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27560 
27561 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27562 
27563 	ipsq_exit(ipsq);
27564 }
27565 
27566 /*
27567  * Complete the ioctl. Typically ioctls use the mi package and need to
27568  * do mi_copyout/mi_copy_done.
27569  */
27570 void
27571 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27572 {
27573 	conn_t	*connp = NULL;
27574 
27575 	if (err == EINPROGRESS)
27576 		return;
27577 
27578 	if (CONN_Q(q)) {
27579 		connp = Q_TO_CONN(q);
27580 		ASSERT(connp->conn_ref >= 2);
27581 	}
27582 
27583 	switch (mode) {
27584 	case COPYOUT:
27585 		if (err == 0)
27586 			mi_copyout(q, mp);
27587 		else
27588 			mi_copy_done(q, mp, err);
27589 		break;
27590 
27591 	case NO_COPYOUT:
27592 		mi_copy_done(q, mp, err);
27593 		break;
27594 
27595 	default:
27596 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27597 		break;
27598 	}
27599 
27600 	/*
27601 	 * The refhold placed at the start of the ioctl is released here.
27602 	 */
27603 	if (connp != NULL)
27604 		CONN_OPER_PENDING_DONE(connp);
27605 
27606 	if (ipsq != NULL)
27607 		ipsq_current_finish(ipsq);
27608 }
27609 
27610 /* Called from ip_wput for all non data messages */
27611 /* ARGSUSED */
27612 void
27613 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27614 {
27615 	mblk_t		*mp1;
27616 	ire_t		*ire, *fake_ire;
27617 	ill_t		*ill;
27618 	struct iocblk	*iocp;
27619 	ip_ioctl_cmd_t	*ipip;
27620 	cred_t		*cr;
27621 	conn_t		*connp;
27622 	int		err;
27623 	nce_t		*nce;
27624 	ipif_t		*ipif;
27625 	ip_stack_t	*ipst;
27626 	char		*proto_str;
27627 
27628 	if (CONN_Q(q)) {
27629 		connp = Q_TO_CONN(q);
27630 		ipst = connp->conn_netstack->netstack_ip;
27631 	} else {
27632 		connp = NULL;
27633 		ipst = ILLQ_TO_IPST(q);
27634 	}
27635 
27636 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27637 
27638 	switch (DB_TYPE(mp)) {
27639 	case M_IOCTL:
27640 		/*
27641 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27642 		 * will arrange to copy in associated control structures.
27643 		 */
27644 		ip_sioctl_copyin_setup(q, mp);
27645 		return;
27646 	case M_IOCDATA:
27647 		/*
27648 		 * Ensure that this is associated with one of our trans-
27649 		 * parent ioctls.  If it's not ours, discard it if we're
27650 		 * running as a driver, or pass it on if we're a module.
27651 		 */
27652 		iocp = (struct iocblk *)mp->b_rptr;
27653 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27654 		if (ipip == NULL) {
27655 			if (q->q_next == NULL) {
27656 				goto nak;
27657 			} else {
27658 				putnext(q, mp);
27659 			}
27660 			return;
27661 		}
27662 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27663 			/*
27664 			 * the ioctl is one we recognise, but is not
27665 			 * consumed by IP as a module, pass M_IOCDATA
27666 			 * for processing downstream, but only for
27667 			 * common Streams ioctls.
27668 			 */
27669 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27670 				putnext(q, mp);
27671 				return;
27672 			} else {
27673 				goto nak;
27674 			}
27675 		}
27676 
27677 		/* IOCTL continuation following copyin or copyout. */
27678 		if (mi_copy_state(q, mp, NULL) == -1) {
27679 			/*
27680 			 * The copy operation failed.  mi_copy_state already
27681 			 * cleaned up, so we're out of here.
27682 			 */
27683 			return;
27684 		}
27685 		/*
27686 		 * If we just completed a copy in, we become writer and
27687 		 * continue processing in ip_sioctl_copyin_done.  If it
27688 		 * was a copy out, we call mi_copyout again.  If there is
27689 		 * nothing more to copy out, it will complete the IOCTL.
27690 		 */
27691 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27692 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27693 				mi_copy_done(q, mp, EPROTO);
27694 				return;
27695 			}
27696 			/*
27697 			 * Check for cases that need more copying.  A return
27698 			 * value of 0 means a second copyin has been started,
27699 			 * so we return; a return value of 1 means no more
27700 			 * copying is needed, so we continue.
27701 			 */
27702 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27703 			    MI_COPY_COUNT(mp) == 1) {
27704 				if (ip_copyin_msfilter(q, mp) == 0)
27705 					return;
27706 			}
27707 			/*
27708 			 * Refhold the conn, till the ioctl completes. This is
27709 			 * needed in case the ioctl ends up in the pending mp
27710 			 * list. Every mp in the ill_pending_mp list and
27711 			 * the ipsq_pending_mp must have a refhold on the conn
27712 			 * to resume processing. The refhold is released when
27713 			 * the ioctl completes. (normally or abnormally)
27714 			 * In all cases ip_ioctl_finish is called to finish
27715 			 * the ioctl.
27716 			 */
27717 			if (connp != NULL) {
27718 				/* This is not a reentry */
27719 				ASSERT(ipsq == NULL);
27720 				CONN_INC_REF(connp);
27721 			} else {
27722 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27723 					mi_copy_done(q, mp, EINVAL);
27724 					return;
27725 				}
27726 			}
27727 
27728 			ip_process_ioctl(ipsq, q, mp, ipip);
27729 
27730 		} else {
27731 			mi_copyout(q, mp);
27732 		}
27733 		return;
27734 nak:
27735 		iocp->ioc_error = EINVAL;
27736 		mp->b_datap->db_type = M_IOCNAK;
27737 		iocp->ioc_count = 0;
27738 		qreply(q, mp);
27739 		return;
27740 
27741 	case M_IOCNAK:
27742 		/*
27743 		 * The only way we could get here is if a resolver didn't like
27744 		 * an IOCTL we sent it.	 This shouldn't happen.
27745 		 */
27746 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27747 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27748 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27749 		freemsg(mp);
27750 		return;
27751 	case M_IOCACK:
27752 		/* /dev/ip shouldn't see this */
27753 		if (CONN_Q(q))
27754 			goto nak;
27755 
27756 		/* Finish socket ioctls passed through to ARP. */
27757 		ip_sioctl_iocack(q, mp);
27758 		return;
27759 	case M_FLUSH:
27760 		if (*mp->b_rptr & FLUSHW)
27761 			flushq(q, FLUSHALL);
27762 		if (q->q_next) {
27763 			putnext(q, mp);
27764 			return;
27765 		}
27766 		if (*mp->b_rptr & FLUSHR) {
27767 			*mp->b_rptr &= ~FLUSHW;
27768 			qreply(q, mp);
27769 			return;
27770 		}
27771 		freemsg(mp);
27772 		return;
27773 	case IRE_DB_REQ_TYPE:
27774 		if (connp == NULL) {
27775 			proto_str = "IRE_DB_REQ_TYPE";
27776 			goto protonak;
27777 		}
27778 		/* An Upper Level Protocol wants a copy of an IRE. */
27779 		ip_ire_req(q, mp);
27780 		return;
27781 	case M_CTL:
27782 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27783 			break;
27784 
27785 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27786 		    TUN_HELLO) {
27787 			ASSERT(connp != NULL);
27788 			connp->conn_flags |= IPCL_IPTUN;
27789 			freeb(mp);
27790 			return;
27791 		}
27792 
27793 		/* M_CTL messages are used by ARP to tell us things. */
27794 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27795 			break;
27796 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27797 		case AR_ENTRY_SQUERY:
27798 			ip_wput_ctl(q, mp);
27799 			return;
27800 		case AR_CLIENT_NOTIFY:
27801 			ip_arp_news(q, mp);
27802 			return;
27803 		case AR_DLPIOP_DONE:
27804 			ASSERT(q->q_next != NULL);
27805 			ill = (ill_t *)q->q_ptr;
27806 			/* qwriter_ip releases the refhold */
27807 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27808 			ill_refhold(ill);
27809 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27810 			return;
27811 		case AR_ARP_CLOSING:
27812 			/*
27813 			 * ARP (above us) is closing. If no ARP bringup is
27814 			 * currently pending, ack the message so that ARP
27815 			 * can complete its close. Also mark ill_arp_closing
27816 			 * so that new ARP bringups will fail. If any
27817 			 * ARP bringup is currently in progress, we will
27818 			 * ack this when the current ARP bringup completes.
27819 			 */
27820 			ASSERT(q->q_next != NULL);
27821 			ill = (ill_t *)q->q_ptr;
27822 			mutex_enter(&ill->ill_lock);
27823 			ill->ill_arp_closing = 1;
27824 			if (!ill->ill_arp_bringup_pending) {
27825 				mutex_exit(&ill->ill_lock);
27826 				qreply(q, mp);
27827 			} else {
27828 				mutex_exit(&ill->ill_lock);
27829 				freemsg(mp);
27830 			}
27831 			return;
27832 		case AR_ARP_EXTEND:
27833 			/*
27834 			 * The ARP module above us is capable of duplicate
27835 			 * address detection.  Old ATM drivers will not send
27836 			 * this message.
27837 			 */
27838 			ASSERT(q->q_next != NULL);
27839 			ill = (ill_t *)q->q_ptr;
27840 			ill->ill_arp_extend = B_TRUE;
27841 			freemsg(mp);
27842 			return;
27843 		default:
27844 			break;
27845 		}
27846 		break;
27847 	case M_PROTO:
27848 	case M_PCPROTO:
27849 		/*
27850 		 * The only PROTO messages we expect are copies of option
27851 		 * negotiation acknowledgements, AH and ESP bind requests
27852 		 * are also expected.
27853 		 */
27854 		switch (((union T_primitives *)mp->b_rptr)->type) {
27855 		case O_T_BIND_REQ:
27856 		case T_BIND_REQ: {
27857 			/* Request can get queued in bind */
27858 			if (connp == NULL) {
27859 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27860 				goto protonak;
27861 			}
27862 			/*
27863 			 * The transports except SCTP call ip_bind_{v4,v6}()
27864 			 * directly instead of a a putnext. SCTP doesn't
27865 			 * generate any T_BIND_REQ since it has its own
27866 			 * fanout data structures. However, ESP and AH
27867 			 * come in for regular binds; all other cases are
27868 			 * bind retries.
27869 			 */
27870 			ASSERT(!IPCL_IS_SCTP(connp));
27871 
27872 			/* Don't increment refcnt if this is a re-entry */
27873 			if (ipsq == NULL)
27874 				CONN_INC_REF(connp);
27875 
27876 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27877 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27878 			ASSERT(mp != NULL);
27879 
27880 			ASSERT(!IPCL_IS_TCP(connp));
27881 			ASSERT(!IPCL_IS_UDP(connp));
27882 			ASSERT(!IPCL_IS_RAWIP(connp));
27883 
27884 			/* The case of AH and ESP */
27885 			qreply(q, mp);
27886 			CONN_OPER_PENDING_DONE(connp);
27887 			return;
27888 		}
27889 		case T_SVR4_OPTMGMT_REQ:
27890 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27891 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27892 
27893 			if (connp == NULL) {
27894 				proto_str = "T_SVR4_OPTMGMT_REQ";
27895 				goto protonak;
27896 			}
27897 
27898 			if (!snmpcom_req(q, mp, ip_snmp_set,
27899 			    ip_snmp_get, cr)) {
27900 				/*
27901 				 * Call svr4_optcom_req so that it can
27902 				 * generate the ack. We don't come here
27903 				 * if this operation is being restarted.
27904 				 * ip_restart_optmgmt will drop the conn ref.
27905 				 * In the case of ipsec option after the ipsec
27906 				 * load is complete conn_restart_ipsec_waiter
27907 				 * drops the conn ref.
27908 				 */
27909 				ASSERT(ipsq == NULL);
27910 				CONN_INC_REF(connp);
27911 				if (ip_check_for_ipsec_opt(q, mp))
27912 					return;
27913 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27914 				    B_FALSE);
27915 				if (err != EINPROGRESS) {
27916 					/* Operation is done */
27917 					CONN_OPER_PENDING_DONE(connp);
27918 				}
27919 			}
27920 			return;
27921 		case T_OPTMGMT_REQ:
27922 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27923 			/*
27924 			 * Note: No snmpcom_req support through new
27925 			 * T_OPTMGMT_REQ.
27926 			 * Call tpi_optcom_req so that it can
27927 			 * generate the ack.
27928 			 */
27929 			if (connp == NULL) {
27930 				proto_str = "T_OPTMGMT_REQ";
27931 				goto protonak;
27932 			}
27933 
27934 			ASSERT(ipsq == NULL);
27935 			/*
27936 			 * We don't come here for restart. ip_restart_optmgmt
27937 			 * will drop the conn ref. In the case of ipsec option
27938 			 * after the ipsec load is complete
27939 			 * conn_restart_ipsec_waiter drops the conn ref.
27940 			 */
27941 			CONN_INC_REF(connp);
27942 			if (ip_check_for_ipsec_opt(q, mp))
27943 				return;
27944 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27945 			if (err != EINPROGRESS) {
27946 				/* Operation is done */
27947 				CONN_OPER_PENDING_DONE(connp);
27948 			}
27949 			return;
27950 		case T_UNBIND_REQ:
27951 			if (connp == NULL) {
27952 				proto_str = "T_UNBIND_REQ";
27953 				goto protonak;
27954 			}
27955 			ip_unbind(Q_TO_CONN(q));
27956 			mp = mi_tpi_ok_ack_alloc(mp);
27957 			qreply(q, mp);
27958 			return;
27959 		default:
27960 			/*
27961 			 * Have to drop any DLPI messages coming down from
27962 			 * arp (such as an info_req which would cause ip
27963 			 * to receive an extra info_ack if it was passed
27964 			 * through.
27965 			 */
27966 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27967 			    (int)*(uint_t *)mp->b_rptr));
27968 			freemsg(mp);
27969 			return;
27970 		}
27971 		/* NOTREACHED */
27972 	case IRE_DB_TYPE: {
27973 		nce_t		*nce;
27974 		ill_t		*ill;
27975 		in6_addr_t	gw_addr_v6;
27976 
27977 
27978 		/*
27979 		 * This is a response back from a resolver.  It
27980 		 * consists of a message chain containing:
27981 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27982 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27983 		 * The LL_HDR_MBLK is the DLPI header to use to get
27984 		 * the attached packet, and subsequent ones for the
27985 		 * same destination, transmitted.
27986 		 */
27987 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27988 			break;
27989 		/*
27990 		 * First, check to make sure the resolution succeeded.
27991 		 * If it failed, the second mblk will be empty.
27992 		 * If it is, free the chain, dropping the packet.
27993 		 * (We must ire_delete the ire; that frees the ire mblk)
27994 		 * We're doing this now to support PVCs for ATM; it's
27995 		 * a partial xresolv implementation. When we fully implement
27996 		 * xresolv interfaces, instead of freeing everything here
27997 		 * we'll initiate neighbor discovery.
27998 		 *
27999 		 * For v4 (ARP and other external resolvers) the resolver
28000 		 * frees the message, so no check is needed. This check
28001 		 * is required, though, for a full xresolve implementation.
28002 		 * Including this code here now both shows how external
28003 		 * resolvers can NACK a resolution request using an
28004 		 * existing design that has no specific provisions for NACKs,
28005 		 * and also takes into account that the current non-ARP
28006 		 * external resolver has been coded to use this method of
28007 		 * NACKing for all IPv6 (xresolv) cases,
28008 		 * whether our xresolv implementation is complete or not.
28009 		 *
28010 		 */
28011 		ire = (ire_t *)mp->b_rptr;
28012 		ill = ire_to_ill(ire);
28013 		mp1 = mp->b_cont;		/* dl_unitdata_req */
28014 		if (mp1->b_rptr == mp1->b_wptr) {
28015 			if (ire->ire_ipversion == IPV6_VERSION) {
28016 				/*
28017 				 * XRESOLV interface.
28018 				 */
28019 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
28020 				mutex_enter(&ire->ire_lock);
28021 				gw_addr_v6 = ire->ire_gateway_addr_v6;
28022 				mutex_exit(&ire->ire_lock);
28023 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
28024 					nce = ndp_lookup_v6(ill,
28025 					    &ire->ire_addr_v6, B_FALSE);
28026 				} else {
28027 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
28028 					    B_FALSE);
28029 				}
28030 				if (nce != NULL) {
28031 					nce_resolv_failed(nce);
28032 					ndp_delete(nce);
28033 					NCE_REFRELE(nce);
28034 				}
28035 			}
28036 			mp->b_cont = NULL;
28037 			freemsg(mp1);		/* frees the pkt as well */
28038 			ASSERT(ire->ire_nce == NULL);
28039 			ire_delete((ire_t *)mp->b_rptr);
28040 			return;
28041 		}
28042 
28043 		/*
28044 		 * Split them into IRE_MBLK and pkt and feed it into
28045 		 * ire_add_then_send. Then in ire_add_then_send
28046 		 * the IRE will be added, and then the packet will be
28047 		 * run back through ip_wput. This time it will make
28048 		 * it to the wire.
28049 		 */
28050 		mp->b_cont = NULL;
28051 		mp = mp1->b_cont;		/* now, mp points to pkt */
28052 		mp1->b_cont = NULL;
28053 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
28054 		if (ire->ire_ipversion == IPV6_VERSION) {
28055 			/*
28056 			 * XRESOLV interface. Find the nce and put a copy
28057 			 * of the dl_unitdata_req in nce_res_mp
28058 			 */
28059 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
28060 			mutex_enter(&ire->ire_lock);
28061 			gw_addr_v6 = ire->ire_gateway_addr_v6;
28062 			mutex_exit(&ire->ire_lock);
28063 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
28064 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
28065 				    B_FALSE);
28066 			} else {
28067 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
28068 			}
28069 			if (nce != NULL) {
28070 				/*
28071 				 * We have to protect nce_res_mp here
28072 				 * from being accessed by other threads
28073 				 * while we change the mblk pointer.
28074 				 * Other functions will also lock the nce when
28075 				 * accessing nce_res_mp.
28076 				 *
28077 				 * The reason we change the mblk pointer
28078 				 * here rather than copying the resolved address
28079 				 * into the template is that, unlike with
28080 				 * ethernet, we have no guarantee that the
28081 				 * resolved address length will be
28082 				 * smaller than or equal to the lla length
28083 				 * with which the template was allocated,
28084 				 * (for ethernet, they're equal)
28085 				 * so we have to use the actual resolved
28086 				 * address mblk - which holds the real
28087 				 * dl_unitdata_req with the resolved address.
28088 				 *
28089 				 * Doing this is the same behavior as was
28090 				 * previously used in the v4 ARP case.
28091 				 */
28092 				mutex_enter(&nce->nce_lock);
28093 				if (nce->nce_res_mp != NULL)
28094 					freemsg(nce->nce_res_mp);
28095 				nce->nce_res_mp = mp1;
28096 				mutex_exit(&nce->nce_lock);
28097 				/*
28098 				 * We do a fastpath probe here because
28099 				 * we have resolved the address without
28100 				 * using Neighbor Discovery.
28101 				 * In the non-XRESOLV v6 case, the fastpath
28102 				 * probe is done right after neighbor
28103 				 * discovery completes.
28104 				 */
28105 				if (nce->nce_res_mp != NULL) {
28106 					int res;
28107 					nce_fastpath_list_add(nce);
28108 					res = ill_fastpath_probe(ill,
28109 					    nce->nce_res_mp);
28110 					if (res != 0 && res != EAGAIN)
28111 						nce_fastpath_list_delete(nce);
28112 				}
28113 
28114 				ire_add_then_send(q, ire, mp);
28115 				/*
28116 				 * Now we have to clean out any packets
28117 				 * that may have been queued on the nce
28118 				 * while it was waiting for address resolution
28119 				 * to complete.
28120 				 */
28121 				mutex_enter(&nce->nce_lock);
28122 				mp1 = nce->nce_qd_mp;
28123 				nce->nce_qd_mp = NULL;
28124 				mutex_exit(&nce->nce_lock);
28125 				while (mp1 != NULL) {
28126 					mblk_t *nxt_mp;
28127 					queue_t *fwdq = NULL;
28128 					ill_t   *inbound_ill;
28129 					uint_t ifindex;
28130 
28131 					nxt_mp = mp1->b_next;
28132 					mp1->b_next = NULL;
28133 					/*
28134 					 * Retrieve ifindex stored in
28135 					 * ip_rput_data_v6()
28136 					 */
28137 					ifindex =
28138 					    (uint_t)(uintptr_t)mp1->b_prev;
28139 					inbound_ill =
28140 					    ill_lookup_on_ifindex(ifindex,
28141 					    B_TRUE, NULL, NULL, NULL,
28142 					    NULL, ipst);
28143 					mp1->b_prev = NULL;
28144 					if (inbound_ill != NULL)
28145 						fwdq = inbound_ill->ill_rq;
28146 
28147 					if (fwdq != NULL) {
28148 						put(fwdq, mp1);
28149 						ill_refrele(inbound_ill);
28150 					} else
28151 						put(WR(ill->ill_rq), mp1);
28152 					mp1 = nxt_mp;
28153 				}
28154 				NCE_REFRELE(nce);
28155 			} else {	/* nce is NULL; clean up */
28156 				ire_delete(ire);
28157 				freemsg(mp);
28158 				freemsg(mp1);
28159 				return;
28160 			}
28161 		} else {
28162 			nce_t *arpce;
28163 			/*
28164 			 * Link layer resolution succeeded. Recompute the
28165 			 * ire_nce.
28166 			 */
28167 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
28168 			if ((arpce = ndp_lookup_v4(ill,
28169 			    (ire->ire_gateway_addr != INADDR_ANY ?
28170 			    &ire->ire_gateway_addr : &ire->ire_addr),
28171 			    B_FALSE)) == NULL) {
28172 				freeb(ire->ire_mp);
28173 				freeb(mp1);
28174 				freemsg(mp);
28175 				return;
28176 			}
28177 			mutex_enter(&arpce->nce_lock);
28178 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
28179 			if (arpce->nce_state == ND_REACHABLE) {
28180 				/*
28181 				 * Someone resolved this before us;
28182 				 * cleanup the res_mp. Since ire has
28183 				 * not been added yet, the call to ire_add_v4
28184 				 * from ire_add_then_send (when a dup is
28185 				 * detected) will clean up the ire.
28186 				 */
28187 				freeb(mp1);
28188 			} else {
28189 				ASSERT(arpce->nce_res_mp == NULL);
28190 				arpce->nce_res_mp = mp1;
28191 				arpce->nce_state = ND_REACHABLE;
28192 			}
28193 			mutex_exit(&arpce->nce_lock);
28194 			if (ire->ire_marks & IRE_MARK_NOADD) {
28195 				/*
28196 				 * this ire will not be added to the ire
28197 				 * cache table, so we can set the ire_nce
28198 				 * here, as there are no atomicity constraints.
28199 				 */
28200 				ire->ire_nce = arpce;
28201 				/*
28202 				 * We are associating this nce with the ire
28203 				 * so change the nce ref taken in
28204 				 * ndp_lookup_v4() from
28205 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
28206 				 */
28207 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
28208 			} else {
28209 				NCE_REFRELE(arpce);
28210 			}
28211 			ire_add_then_send(q, ire, mp);
28212 		}
28213 		return;	/* All is well, the packet has been sent. */
28214 	}
28215 	case IRE_ARPRESOLVE_TYPE: {
28216 
28217 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
28218 			break;
28219 		mp1 = mp->b_cont;		/* dl_unitdata_req */
28220 		mp->b_cont = NULL;
28221 		/*
28222 		 * First, check to make sure the resolution succeeded.
28223 		 * If it failed, the second mblk will be empty.
28224 		 */
28225 		if (mp1->b_rptr == mp1->b_wptr) {
28226 			/* cleanup  the incomplete ire, free queued packets */
28227 			freemsg(mp); /* fake ire */
28228 			freeb(mp1);  /* dl_unitdata response */
28229 			return;
28230 		}
28231 
28232 		/*
28233 		 * Update any incomplete nce_t found. We search the ctable
28234 		 * and find the nce from the ire->ire_nce because we need
28235 		 * to pass the ire to ip_xmit_v4 later, and can find both
28236 		 * ire and nce in one lookup.
28237 		 */
28238 		fake_ire = (ire_t *)mp->b_rptr;
28239 
28240 		/*
28241 		 * By the time we come back here from ARP the incomplete ire
28242 		 * created in ire_forward() could have been removed. We use
28243 		 * the parameters stored in the fake_ire to specify the real
28244 		 * ire as explicitly as possible. This avoids problems when
28245 		 * IPMP groups are configured as an ipif can 'float'
28246 		 * across several ill queues. We can be confident that the
28247 		 * the inability to find an ire is because it no longer exists.
28248 		 */
28249 		ill = ill_lookup_on_ifindex(fake_ire->ire_ipif_ifindex, B_FALSE,
28250 		    NULL, NULL, NULL, NULL, ipst);
28251 		if (ill == NULL) {
28252 			ip1dbg(("ill for incomplete ire vanished\n"));
28253 			freemsg(mp); /* fake ire */
28254 			freeb(mp1);  /* dl_unitdata response */
28255 			return;
28256 		}
28257 
28258 		/* Get the outgoing ipif */
28259 		mutex_enter(&ill->ill_lock);
28260 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
28261 		if (ipif == NULL) {
28262 			mutex_exit(&ill->ill_lock);
28263 			ill_refrele(ill);
28264 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
28265 			freemsg(mp); /* fake_ire */
28266 			freeb(mp1);  /* dl_unitdata response */
28267 			return;
28268 		}
28269 
28270 		ipif_refhold_locked(ipif);
28271 		mutex_exit(&ill->ill_lock);
28272 		ill_refrele(ill);
28273 		ire = ire_arpresolve_lookup(fake_ire->ire_addr,
28274 		    fake_ire->ire_gateway_addr, ipif, fake_ire->ire_zoneid,
28275 		    ipst, ((ill_t *)q->q_ptr)->ill_wq);
28276 		ipif_refrele(ipif);
28277 		if (ire == NULL) {
28278 			/*
28279 			 * no ire was found; check if there is an nce
28280 			 * for this lookup; if it has no ire's pointing at it
28281 			 * cleanup.
28282 			 */
28283 			if ((nce = ndp_lookup_v4(q->q_ptr,
28284 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
28285 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
28286 			    B_FALSE)) != NULL) {
28287 				/*
28288 				 * cleanup:
28289 				 * We check for refcnt 2 (one for the nce
28290 				 * hash list + 1 for the ref taken by
28291 				 * ndp_lookup_v4) to check that there are
28292 				 * no ire's pointing at the nce.
28293 				 */
28294 				if (nce->nce_refcnt == 2)
28295 					ndp_delete(nce);
28296 				NCE_REFRELE(nce);
28297 			}
28298 			freeb(mp1);  /* dl_unitdata response */
28299 			freemsg(mp); /* fake ire */
28300 			return;
28301 		}
28302 		nce = ire->ire_nce;
28303 		DTRACE_PROBE2(ire__arpresolve__type,
28304 		    ire_t *, ire, nce_t *, nce);
28305 		ASSERT(nce->nce_state != ND_INITIAL);
28306 		mutex_enter(&nce->nce_lock);
28307 		nce->nce_last = TICK_TO_MSEC(lbolt64);
28308 		if (nce->nce_state == ND_REACHABLE) {
28309 			/*
28310 			 * Someone resolved this before us;
28311 			 * our response is not needed any more.
28312 			 */
28313 			mutex_exit(&nce->nce_lock);
28314 			freeb(mp1);  /* dl_unitdata response */
28315 		} else {
28316 			ASSERT(nce->nce_res_mp == NULL);
28317 			nce->nce_res_mp = mp1;
28318 			nce->nce_state = ND_REACHABLE;
28319 			mutex_exit(&nce->nce_lock);
28320 			nce_fastpath(nce);
28321 		}
28322 		/*
28323 		 * The cached nce_t has been updated to be reachable;
28324 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
28325 		 */
28326 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
28327 		freemsg(mp);
28328 		/*
28329 		 * send out queued packets.
28330 		 */
28331 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
28332 
28333 		IRE_REFRELE(ire);
28334 		return;
28335 	}
28336 	default:
28337 		break;
28338 	}
28339 	if (q->q_next) {
28340 		putnext(q, mp);
28341 	} else
28342 		freemsg(mp);
28343 	return;
28344 
28345 protonak:
28346 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
28347 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
28348 		qreply(q, mp);
28349 }
28350 
28351 /*
28352  * Process IP options in an outbound packet.  Modify the destination if there
28353  * is a source route option.
28354  * Returns non-zero if something fails in which case an ICMP error has been
28355  * sent and mp freed.
28356  */
28357 static int
28358 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
28359     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
28360 {
28361 	ipoptp_t	opts;
28362 	uchar_t		*opt;
28363 	uint8_t		optval;
28364 	uint8_t		optlen;
28365 	ipaddr_t	dst;
28366 	intptr_t	code = 0;
28367 	mblk_t		*mp;
28368 	ire_t		*ire = NULL;
28369 
28370 	ip2dbg(("ip_wput_options\n"));
28371 	mp = ipsec_mp;
28372 	if (mctl_present) {
28373 		mp = ipsec_mp->b_cont;
28374 	}
28375 
28376 	dst = ipha->ipha_dst;
28377 	for (optval = ipoptp_first(&opts, ipha);
28378 	    optval != IPOPT_EOL;
28379 	    optval = ipoptp_next(&opts)) {
28380 		opt = opts.ipoptp_cur;
28381 		optlen = opts.ipoptp_len;
28382 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
28383 		    optval, optlen));
28384 		switch (optval) {
28385 			uint32_t off;
28386 		case IPOPT_SSRR:
28387 		case IPOPT_LSRR:
28388 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28389 				ip1dbg((
28390 				    "ip_wput_options: bad option offset\n"));
28391 				code = (char *)&opt[IPOPT_OLEN] -
28392 				    (char *)ipha;
28393 				goto param_prob;
28394 			}
28395 			off = opt[IPOPT_OFFSET];
28396 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
28397 			    ntohl(dst)));
28398 			/*
28399 			 * For strict: verify that dst is directly
28400 			 * reachable.
28401 			 */
28402 			if (optval == IPOPT_SSRR) {
28403 				ire = ire_ftable_lookup(dst, 0, 0,
28404 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
28405 				    MBLK_GETLABEL(mp),
28406 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
28407 				if (ire == NULL) {
28408 					ip1dbg(("ip_wput_options: SSRR not"
28409 					    " directly reachable: 0x%x\n",
28410 					    ntohl(dst)));
28411 					goto bad_src_route;
28412 				}
28413 				ire_refrele(ire);
28414 			}
28415 			break;
28416 		case IPOPT_RR:
28417 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28418 				ip1dbg((
28419 				    "ip_wput_options: bad option offset\n"));
28420 				code = (char *)&opt[IPOPT_OLEN] -
28421 				    (char *)ipha;
28422 				goto param_prob;
28423 			}
28424 			break;
28425 		case IPOPT_TS:
28426 			/*
28427 			 * Verify that length >=5 and that there is either
28428 			 * room for another timestamp or that the overflow
28429 			 * counter is not maxed out.
28430 			 */
28431 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
28432 			if (optlen < IPOPT_MINLEN_IT) {
28433 				goto param_prob;
28434 			}
28435 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28436 				ip1dbg((
28437 				    "ip_wput_options: bad option offset\n"));
28438 				code = (char *)&opt[IPOPT_OFFSET] -
28439 				    (char *)ipha;
28440 				goto param_prob;
28441 			}
28442 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
28443 			case IPOPT_TS_TSONLY:
28444 				off = IPOPT_TS_TIMELEN;
28445 				break;
28446 			case IPOPT_TS_TSANDADDR:
28447 			case IPOPT_TS_PRESPEC:
28448 			case IPOPT_TS_PRESPEC_RFC791:
28449 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28450 				break;
28451 			default:
28452 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28453 				    (char *)ipha;
28454 				goto param_prob;
28455 			}
28456 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28457 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28458 				/*
28459 				 * No room and the overflow counter is 15
28460 				 * already.
28461 				 */
28462 				goto param_prob;
28463 			}
28464 			break;
28465 		}
28466 	}
28467 
28468 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28469 		return (0);
28470 
28471 	ip1dbg(("ip_wput_options: error processing IP options."));
28472 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28473 
28474 param_prob:
28475 	/*
28476 	 * Since ip_wput() isn't close to finished, we fill
28477 	 * in enough of the header for credible error reporting.
28478 	 */
28479 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28480 		/* Failed */
28481 		freemsg(ipsec_mp);
28482 		return (-1);
28483 	}
28484 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28485 	return (-1);
28486 
28487 bad_src_route:
28488 	/*
28489 	 * Since ip_wput() isn't close to finished, we fill
28490 	 * in enough of the header for credible error reporting.
28491 	 */
28492 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28493 		/* Failed */
28494 		freemsg(ipsec_mp);
28495 		return (-1);
28496 	}
28497 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28498 	return (-1);
28499 }
28500 
28501 /*
28502  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28503  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28504  * thru /etc/system.
28505  */
28506 #define	CONN_MAXDRAINCNT	64
28507 
28508 static void
28509 conn_drain_init(ip_stack_t *ipst)
28510 {
28511 	int i;
28512 
28513 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28514 
28515 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28516 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28517 		/*
28518 		 * Default value of the number of drainers is the
28519 		 * number of cpus, subject to maximum of 8 drainers.
28520 		 */
28521 		if (boot_max_ncpus != -1)
28522 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28523 		else
28524 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28525 	}
28526 
28527 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28528 	    sizeof (idl_t), KM_SLEEP);
28529 
28530 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28531 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28532 		    MUTEX_DEFAULT, NULL);
28533 	}
28534 }
28535 
28536 static void
28537 conn_drain_fini(ip_stack_t *ipst)
28538 {
28539 	int i;
28540 
28541 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28542 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28543 	kmem_free(ipst->ips_conn_drain_list,
28544 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28545 	ipst->ips_conn_drain_list = NULL;
28546 }
28547 
28548 /*
28549  * Note: For an overview of how flowcontrol is handled in IP please see the
28550  * IP Flowcontrol notes at the top of this file.
28551  *
28552  * Flow control has blocked us from proceeding. Insert the given conn in one
28553  * of the conn drain lists. These conn wq's will be qenabled later on when
28554  * STREAMS flow control does a backenable. conn_walk_drain will enable
28555  * the first conn in each of these drain lists. Each of these qenabled conns
28556  * in turn enables the next in the list, after it runs, or when it closes,
28557  * thus sustaining the drain process.
28558  *
28559  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28560  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28561  * running at any time, on a given conn, since there can be only 1 service proc
28562  * running on a queue at any time.
28563  */
28564 void
28565 conn_drain_insert(conn_t *connp)
28566 {
28567 	idl_t	*idl;
28568 	uint_t	index;
28569 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28570 
28571 	mutex_enter(&connp->conn_lock);
28572 	if (connp->conn_state_flags & CONN_CLOSING) {
28573 		/*
28574 		 * The conn is closing as a result of which CONN_CLOSING
28575 		 * is set. Return.
28576 		 */
28577 		mutex_exit(&connp->conn_lock);
28578 		return;
28579 	} else if (connp->conn_idl == NULL) {
28580 		/*
28581 		 * Assign the next drain list round robin. We dont' use
28582 		 * a lock, and thus it may not be strictly round robin.
28583 		 * Atomicity of load/stores is enough to make sure that
28584 		 * conn_drain_list_index is always within bounds.
28585 		 */
28586 		index = ipst->ips_conn_drain_list_index;
28587 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28588 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28589 		index++;
28590 		if (index == ipst->ips_conn_drain_list_cnt)
28591 			index = 0;
28592 		ipst->ips_conn_drain_list_index = index;
28593 	}
28594 	mutex_exit(&connp->conn_lock);
28595 
28596 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28597 	if ((connp->conn_drain_prev != NULL) ||
28598 	    (connp->conn_state_flags & CONN_CLOSING)) {
28599 		/*
28600 		 * The conn is already in the drain list, OR
28601 		 * the conn is closing. We need to check again for
28602 		 * the closing case again since close can happen
28603 		 * after we drop the conn_lock, and before we
28604 		 * acquire the CONN_DRAIN_LIST_LOCK.
28605 		 */
28606 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28607 		return;
28608 	} else {
28609 		idl = connp->conn_idl;
28610 	}
28611 
28612 	/*
28613 	 * The conn is not in the drain list. Insert it at the
28614 	 * tail of the drain list. The drain list is circular
28615 	 * and doubly linked. idl_conn points to the 1st element
28616 	 * in the list.
28617 	 */
28618 	if (idl->idl_conn == NULL) {
28619 		idl->idl_conn = connp;
28620 		connp->conn_drain_next = connp;
28621 		connp->conn_drain_prev = connp;
28622 	} else {
28623 		conn_t *head = idl->idl_conn;
28624 
28625 		connp->conn_drain_next = head;
28626 		connp->conn_drain_prev = head->conn_drain_prev;
28627 		head->conn_drain_prev->conn_drain_next = connp;
28628 		head->conn_drain_prev = connp;
28629 	}
28630 	/*
28631 	 * For non streams based sockets assert flow control.
28632 	 */
28633 	(*connp->conn_upcalls->su_txq_full)
28634 	    (connp->conn_upper_handle, B_TRUE);
28635 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28636 }
28637 
28638 /*
28639  * This conn is closing, and we are called from ip_close. OR
28640  * This conn has been serviced by ip_wsrv, and we need to do the tail
28641  * processing.
28642  * If this conn is part of the drain list, we may need to sustain the drain
28643  * process by qenabling the next conn in the drain list. We may also need to
28644  * remove this conn from the list, if it is done.
28645  */
28646 static void
28647 conn_drain_tail(conn_t *connp, boolean_t closing)
28648 {
28649 	idl_t *idl;
28650 
28651 	/*
28652 	 * connp->conn_idl is stable at this point, and no lock is needed
28653 	 * to check it. If we are called from ip_close, close has already
28654 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28655 	 * called us only because conn_idl is non-null. If we are called thru
28656 	 * service, conn_idl could be null, but it cannot change because
28657 	 * service is single-threaded per queue, and there cannot be another
28658 	 * instance of service trying to call conn_drain_insert on this conn
28659 	 * now.
28660 	 */
28661 	ASSERT(!closing || (connp->conn_idl != NULL));
28662 
28663 	/*
28664 	 * If connp->conn_idl is null, the conn has not been inserted into any
28665 	 * drain list even once since creation of the conn. Just return.
28666 	 */
28667 	if (connp->conn_idl == NULL)
28668 		return;
28669 
28670 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28671 
28672 	if (connp->conn_drain_prev == NULL) {
28673 		/* This conn is currently not in the drain list.  */
28674 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28675 		return;
28676 	}
28677 	idl = connp->conn_idl;
28678 	if (idl->idl_conn_draining == connp) {
28679 		/*
28680 		 * This conn is the current drainer. If this is the last conn
28681 		 * in the drain list, we need to do more checks, in the 'if'
28682 		 * below. Otherwwise we need to just qenable the next conn,
28683 		 * to sustain the draining, and is handled in the 'else'
28684 		 * below.
28685 		 */
28686 		if (connp->conn_drain_next == idl->idl_conn) {
28687 			/*
28688 			 * This conn is the last in this list. This round
28689 			 * of draining is complete. If idl_repeat is set,
28690 			 * it means another flow enabling has happened from
28691 			 * the driver/streams and we need to another round
28692 			 * of draining.
28693 			 * If there are more than 2 conns in the drain list,
28694 			 * do a left rotate by 1, so that all conns except the
28695 			 * conn at the head move towards the head by 1, and the
28696 			 * the conn at the head goes to the tail. This attempts
28697 			 * a more even share for all queues that are being
28698 			 * drained.
28699 			 */
28700 			if ((connp->conn_drain_next != connp) &&
28701 			    (idl->idl_conn->conn_drain_next != connp)) {
28702 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28703 			}
28704 			if (idl->idl_repeat) {
28705 				qenable(idl->idl_conn->conn_wq);
28706 				idl->idl_conn_draining = idl->idl_conn;
28707 				idl->idl_repeat = 0;
28708 			} else {
28709 				idl->idl_conn_draining = NULL;
28710 			}
28711 		} else {
28712 			/*
28713 			 * If the next queue that we are now qenable'ing,
28714 			 * is closing, it will remove itself from this list
28715 			 * and qenable the subsequent queue in ip_close().
28716 			 * Serialization is acheived thru idl_lock.
28717 			 */
28718 			qenable(connp->conn_drain_next->conn_wq);
28719 			idl->idl_conn_draining = connp->conn_drain_next;
28720 		}
28721 	}
28722 	if (!connp->conn_did_putbq || closing) {
28723 		/*
28724 		 * Remove ourself from the drain list, if we did not do
28725 		 * a putbq, or if the conn is closing.
28726 		 * Note: It is possible that q->q_first is non-null. It means
28727 		 * that these messages landed after we did a enableok() in
28728 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28729 		 * service them.
28730 		 */
28731 		if (connp->conn_drain_next == connp) {
28732 			/* Singleton in the list */
28733 			ASSERT(connp->conn_drain_prev == connp);
28734 			idl->idl_conn = NULL;
28735 			idl->idl_conn_draining = NULL;
28736 		} else {
28737 			connp->conn_drain_prev->conn_drain_next =
28738 			    connp->conn_drain_next;
28739 			connp->conn_drain_next->conn_drain_prev =
28740 			    connp->conn_drain_prev;
28741 			if (idl->idl_conn == connp)
28742 				idl->idl_conn = connp->conn_drain_next;
28743 			ASSERT(idl->idl_conn_draining != connp);
28744 
28745 		}
28746 		connp->conn_drain_next = NULL;
28747 		connp->conn_drain_prev = NULL;
28748 
28749 		/*
28750 		 * For non streams based sockets open up flow control.
28751 		 */
28752 		if (IPCL_IS_NONSTR(connp)) {
28753 			(*connp->conn_upcalls->su_txq_full)
28754 			    (connp->conn_upper_handle, B_FALSE);
28755 		}
28756 	}
28757 
28758 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28759 }
28760 
28761 /*
28762  * Write service routine. Shared perimeter entry point.
28763  * ip_wsrv can be called in any of the following ways.
28764  * 1. The device queue's messages has fallen below the low water mark
28765  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28766  *    the drain lists and backenable the first conn in each list.
28767  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28768  *    qenabled non-tcp upper layers. We start dequeing messages and call
28769  *    ip_wput for each message.
28770  */
28771 
28772 void
28773 ip_wsrv(queue_t *q)
28774 {
28775 	conn_t	*connp;
28776 	ill_t	*ill;
28777 	mblk_t	*mp;
28778 
28779 	if (q->q_next) {
28780 		ill = (ill_t *)q->q_ptr;
28781 		if (ill->ill_state_flags == 0) {
28782 			/*
28783 			 * The device flow control has opened up.
28784 			 * Walk through conn drain lists and qenable the
28785 			 * first conn in each list. This makes sense only
28786 			 * if the stream is fully plumbed and setup.
28787 			 * Hence the if check above.
28788 			 */
28789 			ip1dbg(("ip_wsrv: walking\n"));
28790 			conn_walk_drain(ill->ill_ipst);
28791 		}
28792 		return;
28793 	}
28794 
28795 	connp = Q_TO_CONN(q);
28796 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28797 
28798 	/*
28799 	 * 1. Set conn_draining flag to signal that service is active.
28800 	 *
28801 	 * 2. ip_output determines whether it has been called from service,
28802 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28803 	 *    has been called from service.
28804 	 *
28805 	 * 3. Message ordering is preserved by the following logic.
28806 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28807 	 *    the message at the tail, if conn_draining is set (i.e. service
28808 	 *    is running) or if q->q_first is non-null.
28809 	 *
28810 	 *    ii. If ip_output is called from service, and if ip_output cannot
28811 	 *    putnext due to flow control, it does a putbq.
28812 	 *
28813 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28814 	 *    (causing an infinite loop).
28815 	 */
28816 	ASSERT(!connp->conn_did_putbq);
28817 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28818 		connp->conn_draining = 1;
28819 		noenable(q);
28820 		while ((mp = getq(q)) != NULL) {
28821 			ASSERT(CONN_Q(q));
28822 
28823 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28824 			if (connp->conn_did_putbq) {
28825 				/* ip_wput did a putbq */
28826 				break;
28827 			}
28828 		}
28829 		/*
28830 		 * At this point, a thread coming down from top, calling
28831 		 * ip_wput, may end up queueing the message. We have not yet
28832 		 * enabled the queue, so ip_wsrv won't be called again.
28833 		 * To avoid this race, check q->q_first again (in the loop)
28834 		 * If the other thread queued the message before we call
28835 		 * enableok(), we will catch it in the q->q_first check.
28836 		 * If the other thread queues the message after we call
28837 		 * enableok(), ip_wsrv will be called again by STREAMS.
28838 		 */
28839 		connp->conn_draining = 0;
28840 		enableok(q);
28841 
28842 	}
28843 
28844 	/* Enable the next conn for draining */
28845 	conn_drain_tail(connp, B_FALSE);
28846 
28847 	connp->conn_did_putbq = 0;
28848 }
28849 
28850 /*
28851  * Callback to disable flow control in IP.
28852  *
28853  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
28854  * is enabled.
28855  *
28856  * When MAC_TX() is not able to send any more packets, dld sets its queue
28857  * to QFULL and enable the STREAMS flow control. Later, when the underlying
28858  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
28859  * function and wakes up corresponding mac worker threads, which in turn
28860  * calls this callback function, and disables flow control.
28861  */
28862 /* ARGSUSED */
28863 void
28864 ill_flow_enable(void *ill, ip_mac_tx_cookie_t cookie)
28865 {
28866 	qenable(((ill_t *)ill)->ill_wq);
28867 }
28868 
28869 /*
28870  * Walk the list of all conn's calling the function provided with the
28871  * specified argument for each.	 Note that this only walks conn's that
28872  * have been bound.
28873  * Applies to both IPv4 and IPv6.
28874  */
28875 static void
28876 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28877 {
28878 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28879 	    ipst->ips_ipcl_udp_fanout_size,
28880 	    func, arg, zoneid);
28881 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28882 	    ipst->ips_ipcl_conn_fanout_size,
28883 	    func, arg, zoneid);
28884 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28885 	    ipst->ips_ipcl_bind_fanout_size,
28886 	    func, arg, zoneid);
28887 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28888 	    IPPROTO_MAX, func, arg, zoneid);
28889 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28890 	    IPPROTO_MAX, func, arg, zoneid);
28891 }
28892 
28893 /*
28894  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28895  * of conns that need to be drained, check if drain is already in progress.
28896  * If so set the idl_repeat bit, indicating that the last conn in the list
28897  * needs to reinitiate the drain once again, for the list. If drain is not
28898  * in progress for the list, initiate the draining, by qenabling the 1st
28899  * conn in the list. The drain is self-sustaining, each qenabled conn will
28900  * in turn qenable the next conn, when it is done/blocked/closing.
28901  */
28902 static void
28903 conn_walk_drain(ip_stack_t *ipst)
28904 {
28905 	int i;
28906 	idl_t *idl;
28907 
28908 	IP_STAT(ipst, ip_conn_walk_drain);
28909 
28910 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28911 		idl = &ipst->ips_conn_drain_list[i];
28912 		mutex_enter(&idl->idl_lock);
28913 		if (idl->idl_conn == NULL) {
28914 			mutex_exit(&idl->idl_lock);
28915 			continue;
28916 		}
28917 		/*
28918 		 * If this list is not being drained currently by
28919 		 * an ip_wsrv thread, start the process.
28920 		 */
28921 		if (idl->idl_conn_draining == NULL) {
28922 			ASSERT(idl->idl_repeat == 0);
28923 			qenable(idl->idl_conn->conn_wq);
28924 			idl->idl_conn_draining = idl->idl_conn;
28925 		} else {
28926 			idl->idl_repeat = 1;
28927 		}
28928 		mutex_exit(&idl->idl_lock);
28929 	}
28930 }
28931 
28932 /*
28933  * Walk an conn hash table of `count' buckets, calling func for each entry.
28934  */
28935 static void
28936 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28937     zoneid_t zoneid)
28938 {
28939 	conn_t	*connp;
28940 
28941 	while (count-- > 0) {
28942 		mutex_enter(&connfp->connf_lock);
28943 		for (connp = connfp->connf_head; connp != NULL;
28944 		    connp = connp->conn_next) {
28945 			if (zoneid == GLOBAL_ZONEID ||
28946 			    zoneid == connp->conn_zoneid) {
28947 				CONN_INC_REF(connp);
28948 				mutex_exit(&connfp->connf_lock);
28949 				(*func)(connp, arg);
28950 				mutex_enter(&connfp->connf_lock);
28951 				CONN_DEC_REF(connp);
28952 			}
28953 		}
28954 		mutex_exit(&connfp->connf_lock);
28955 		connfp++;
28956 	}
28957 }
28958 
28959 /* conn_walk_fanout routine invoked for ip_conn_report for each conn. */
28960 static void
28961 conn_report1(conn_t *connp, void *mp)
28962 {
28963 	char	buf1[INET6_ADDRSTRLEN];
28964 	char	buf2[INET6_ADDRSTRLEN];
28965 	uint_t	print_len, buf_len;
28966 
28967 	ASSERT(connp != NULL);
28968 
28969 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28970 	if (buf_len <= 0)
28971 		return;
28972 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28973 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28974 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28975 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28976 	    "%5d %s/%05d %s/%05d\n",
28977 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28978 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28979 	    buf1, connp->conn_lport,
28980 	    buf2, connp->conn_fport);
28981 	if (print_len < buf_len) {
28982 		((mblk_t *)mp)->b_wptr += print_len;
28983 	} else {
28984 		((mblk_t *)mp)->b_wptr += buf_len;
28985 	}
28986 }
28987 
28988 /*
28989  * Named Dispatch routine to produce a formatted report on all conns
28990  * that are listed in one of the fanout tables.
28991  * This report is accessed by using the ndd utility to "get" ND variable
28992  * "ip_conn_status".
28993  */
28994 /* ARGSUSED */
28995 static int
28996 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28997 {
28998 	conn_t *connp = Q_TO_CONN(q);
28999 
29000 	(void) mi_mpprintf(mp,
29001 	    "CONN      " MI_COL_HDRPAD_STR
29002 	    "rfq      " MI_COL_HDRPAD_STR
29003 	    "stq      " MI_COL_HDRPAD_STR
29004 	    " zone local		 remote");
29005 
29006 	/*
29007 	 * Because of the ndd constraint, at most we can have 64K buffer
29008 	 * to put in all conn info.  So to be more efficient, just
29009 	 * allocate a 64K buffer here, assuming we need that large buffer.
29010 	 * This should be OK as only privileged processes can do ndd /dev/ip.
29011 	 */
29012 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
29013 		/* The following may work even if we cannot get a large buf. */
29014 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
29015 		return (0);
29016 	}
29017 
29018 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
29019 	    connp->conn_netstack->netstack_ip);
29020 	return (0);
29021 }
29022 
29023 /*
29024  * Determine if the ill and multicast aspects of that packets
29025  * "matches" the conn.
29026  */
29027 boolean_t
29028 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
29029     zoneid_t zoneid)
29030 {
29031 	ill_t *in_ill;
29032 	boolean_t found;
29033 	ipif_t *ipif;
29034 	ire_t *ire;
29035 	ipaddr_t dst, src;
29036 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
29037 
29038 	dst = ipha->ipha_dst;
29039 	src = ipha->ipha_src;
29040 
29041 	/*
29042 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
29043 	 * unicast, broadcast and multicast reception to
29044 	 * conn_incoming_ill. conn_wantpacket itself is called
29045 	 * only for BROADCAST and multicast.
29046 	 *
29047 	 * 1) ip_rput supresses duplicate broadcasts if the ill
29048 	 *    is part of a group. Hence, we should be receiving
29049 	 *    just one copy of broadcast for the whole group.
29050 	 *    Thus, if it is part of the group the packet could
29051 	 *    come on any ill of the group and hence we need a
29052 	 *    match on the group. Otherwise, match on ill should
29053 	 *    be sufficient.
29054 	 *
29055 	 * 2) ip_rput does not suppress duplicate multicast packets.
29056 	 *    If there are two interfaces in a ill group and we have
29057 	 *    2 applications (conns) joined a multicast group G on
29058 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
29059 	 *    will give us two packets because we join G on both the
29060 	 *    interfaces rather than nominating just one interface
29061 	 *    for receiving multicast like broadcast above. So,
29062 	 *    we have to call ilg_lookup_ill to filter out duplicate
29063 	 *    copies, if ill is part of a group.
29064 	 */
29065 	in_ill = connp->conn_incoming_ill;
29066 	if (in_ill != NULL) {
29067 		if (in_ill->ill_group == NULL) {
29068 			if (in_ill != ill)
29069 				return (B_FALSE);
29070 		} else if (in_ill->ill_group != ill->ill_group) {
29071 			return (B_FALSE);
29072 		}
29073 	}
29074 
29075 	if (!CLASSD(dst)) {
29076 		if (IPCL_ZONE_MATCH(connp, zoneid))
29077 			return (B_TRUE);
29078 		/*
29079 		 * The conn is in a different zone; we need to check that this
29080 		 * broadcast address is configured in the application's zone and
29081 		 * on one ill in the group.
29082 		 */
29083 		ipif = ipif_get_next_ipif(NULL, ill);
29084 		if (ipif == NULL)
29085 			return (B_FALSE);
29086 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
29087 		    connp->conn_zoneid, NULL,
29088 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
29089 		ipif_refrele(ipif);
29090 		if (ire != NULL) {
29091 			ire_refrele(ire);
29092 			return (B_TRUE);
29093 		} else {
29094 			return (B_FALSE);
29095 		}
29096 	}
29097 
29098 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
29099 	    connp->conn_zoneid == zoneid) {
29100 		/*
29101 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
29102 		 * disabled, therefore we don't dispatch the multicast packet to
29103 		 * the sending zone.
29104 		 */
29105 		return (B_FALSE);
29106 	}
29107 
29108 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
29109 		/*
29110 		 * Multicast packet on the loopback interface: we only match
29111 		 * conns who joined the group in the specified zone.
29112 		 */
29113 		return (B_FALSE);
29114 	}
29115 
29116 	if (connp->conn_multi_router) {
29117 		/* multicast packet and multicast router socket: send up */
29118 		return (B_TRUE);
29119 	}
29120 
29121 	mutex_enter(&connp->conn_lock);
29122 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
29123 	mutex_exit(&connp->conn_lock);
29124 	return (found);
29125 }
29126 
29127 /*
29128  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
29129  */
29130 /* ARGSUSED */
29131 static void
29132 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
29133 {
29134 	ill_t *ill = (ill_t *)q->q_ptr;
29135 	mblk_t	*mp1, *mp2;
29136 	ipif_t  *ipif;
29137 	int err = 0;
29138 	conn_t *connp = NULL;
29139 	ipsq_t	*ipsq;
29140 	arc_t	*arc;
29141 
29142 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
29143 
29144 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
29145 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
29146 
29147 	ASSERT(IAM_WRITER_ILL(ill));
29148 	mp2 = mp->b_cont;
29149 	mp->b_cont = NULL;
29150 
29151 	/*
29152 	 * We have now received the arp bringup completion message
29153 	 * from ARP. Mark the arp bringup as done. Also if the arp
29154 	 * stream has already started closing, send up the AR_ARP_CLOSING
29155 	 * ack now since ARP is waiting in close for this ack.
29156 	 */
29157 	mutex_enter(&ill->ill_lock);
29158 	ill->ill_arp_bringup_pending = 0;
29159 	if (ill->ill_arp_closing) {
29160 		mutex_exit(&ill->ill_lock);
29161 		/* Let's reuse the mp for sending the ack */
29162 		arc = (arc_t *)mp->b_rptr;
29163 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
29164 		arc->arc_cmd = AR_ARP_CLOSING;
29165 		qreply(q, mp);
29166 	} else {
29167 		mutex_exit(&ill->ill_lock);
29168 		freeb(mp);
29169 	}
29170 
29171 	ipsq = ill->ill_phyint->phyint_ipsq;
29172 	ipif = ipsq->ipsq_pending_ipif;
29173 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
29174 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
29175 	if (mp1 == NULL) {
29176 		/* bringup was aborted by the user */
29177 		freemsg(mp2);
29178 		return;
29179 	}
29180 
29181 	/*
29182 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
29183 	 * must have an associated conn_t.  Otherwise, we're bringing this
29184 	 * interface back up as part of handling an asynchronous event (e.g.,
29185 	 * physical address change).
29186 	 */
29187 	if (ipsq->ipsq_current_ioctl != 0) {
29188 		ASSERT(connp != NULL);
29189 		q = CONNP_TO_WQ(connp);
29190 	} else {
29191 		ASSERT(connp == NULL);
29192 		q = ill->ill_rq;
29193 	}
29194 
29195 	/*
29196 	 * If the DL_BIND_REQ fails, it is noted
29197 	 * in arc_name_offset.
29198 	 */
29199 	err = *((int *)mp2->b_rptr);
29200 	if (err == 0) {
29201 		if (ipif->ipif_isv6) {
29202 			if ((err = ipif_up_done_v6(ipif)) != 0)
29203 				ip0dbg(("ip_arp_done: init failed\n"));
29204 		} else {
29205 			if ((err = ipif_up_done(ipif)) != 0)
29206 				ip0dbg(("ip_arp_done: init failed\n"));
29207 		}
29208 	} else {
29209 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
29210 	}
29211 
29212 	freemsg(mp2);
29213 
29214 	if ((err == 0) && (ill->ill_up_ipifs)) {
29215 		err = ill_up_ipifs(ill, q, mp1);
29216 		if (err == EINPROGRESS)
29217 			return;
29218 	}
29219 
29220 	if (ill->ill_up_ipifs)
29221 		ill_group_cleanup(ill);
29222 
29223 	/*
29224 	 * The operation must complete without EINPROGRESS since
29225 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
29226 	 * Otherwise, the operation will be stuck forever in the ipsq.
29227 	 */
29228 	ASSERT(err != EINPROGRESS);
29229 	if (ipsq->ipsq_current_ioctl != 0)
29230 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
29231 	else
29232 		ipsq_current_finish(ipsq);
29233 }
29234 
29235 /* Allocate the private structure */
29236 static int
29237 ip_priv_alloc(void **bufp)
29238 {
29239 	void	*buf;
29240 
29241 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
29242 		return (ENOMEM);
29243 
29244 	*bufp = buf;
29245 	return (0);
29246 }
29247 
29248 /* Function to delete the private structure */
29249 void
29250 ip_priv_free(void *buf)
29251 {
29252 	ASSERT(buf != NULL);
29253 	kmem_free(buf, sizeof (ip_priv_t));
29254 }
29255 
29256 /*
29257  * The entry point for IPPF processing.
29258  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
29259  * routine just returns.
29260  *
29261  * When called, ip_process generates an ipp_packet_t structure
29262  * which holds the state information for this packet and invokes the
29263  * the classifier (via ipp_packet_process). The classification, depending on
29264  * configured filters, results in a list of actions for this packet. Invoking
29265  * an action may cause the packet to be dropped, in which case the resulting
29266  * mblk (*mpp) is NULL. proc indicates the callout position for
29267  * this packet and ill_index is the interface this packet on or will leave
29268  * on (inbound and outbound resp.).
29269  */
29270 void
29271 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
29272 {
29273 	mblk_t		*mp;
29274 	ip_priv_t	*priv;
29275 	ipp_action_id_t	aid;
29276 	int		rc = 0;
29277 	ipp_packet_t	*pp;
29278 #define	IP_CLASS	"ip"
29279 
29280 	/* If the classifier is not loaded, return  */
29281 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
29282 		return;
29283 	}
29284 
29285 	mp = *mpp;
29286 	ASSERT(mp != NULL);
29287 
29288 	/* Allocate the packet structure */
29289 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
29290 	if (rc != 0) {
29291 		*mpp = NULL;
29292 		freemsg(mp);
29293 		return;
29294 	}
29295 
29296 	/* Allocate the private structure */
29297 	rc = ip_priv_alloc((void **)&priv);
29298 	if (rc != 0) {
29299 		*mpp = NULL;
29300 		freemsg(mp);
29301 		ipp_packet_free(pp);
29302 		return;
29303 	}
29304 	priv->proc = proc;
29305 	priv->ill_index = ill_index;
29306 	ipp_packet_set_private(pp, priv, ip_priv_free);
29307 	ipp_packet_set_data(pp, mp);
29308 
29309 	/* Invoke the classifier */
29310 	rc = ipp_packet_process(&pp);
29311 	if (pp != NULL) {
29312 		mp = ipp_packet_get_data(pp);
29313 		ipp_packet_free(pp);
29314 		if (rc != 0) {
29315 			freemsg(mp);
29316 			*mpp = NULL;
29317 		}
29318 	} else {
29319 		*mpp = NULL;
29320 	}
29321 #undef	IP_CLASS
29322 }
29323 
29324 /*
29325  * Propagate a multicast group membership operation (add/drop) on
29326  * all the interfaces crossed by the related multirt routes.
29327  * The call is considered successful if the operation succeeds
29328  * on at least one interface.
29329  */
29330 static int
29331 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
29332     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
29333     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
29334     mblk_t *first_mp)
29335 {
29336 	ire_t		*ire_gw;
29337 	irb_t		*irb;
29338 	int		error = 0;
29339 	opt_restart_t	*or;
29340 	ip_stack_t	*ipst = ire->ire_ipst;
29341 
29342 	irb = ire->ire_bucket;
29343 	ASSERT(irb != NULL);
29344 
29345 	ASSERT(DB_TYPE(first_mp) == M_CTL);
29346 
29347 	or = (opt_restart_t *)first_mp->b_rptr;
29348 	IRB_REFHOLD(irb);
29349 	for (; ire != NULL; ire = ire->ire_next) {
29350 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
29351 			continue;
29352 		if (ire->ire_addr != group)
29353 			continue;
29354 
29355 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
29356 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
29357 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
29358 		/* No resolver exists for the gateway; skip this ire. */
29359 		if (ire_gw == NULL)
29360 			continue;
29361 
29362 		/*
29363 		 * This function can return EINPROGRESS. If so the operation
29364 		 * will be restarted from ip_restart_optmgmt which will
29365 		 * call ip_opt_set and option processing will restart for
29366 		 * this option. So we may end up calling 'fn' more than once.
29367 		 * This requires that 'fn' is idempotent except for the
29368 		 * return value. The operation is considered a success if
29369 		 * it succeeds at least once on any one interface.
29370 		 */
29371 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
29372 		    NULL, fmode, src, first_mp);
29373 		if (error == 0)
29374 			or->or_private = CGTP_MCAST_SUCCESS;
29375 
29376 		if (ip_debug > 0) {
29377 			ulong_t	off;
29378 			char	*ksym;
29379 			ksym = kobj_getsymname((uintptr_t)fn, &off);
29380 			ip2dbg(("ip_multirt_apply_membership: "
29381 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
29382 			    "error %d [success %u]\n",
29383 			    ksym ? ksym : "?",
29384 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
29385 			    error, or->or_private));
29386 		}
29387 
29388 		ire_refrele(ire_gw);
29389 		if (error == EINPROGRESS) {
29390 			IRB_REFRELE(irb);
29391 			return (error);
29392 		}
29393 	}
29394 	IRB_REFRELE(irb);
29395 	/*
29396 	 * Consider the call as successful if we succeeded on at least
29397 	 * one interface. Otherwise, return the last encountered error.
29398 	 */
29399 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
29400 }
29401 
29402 /*
29403  * Issue a warning regarding a route crossing an interface with an
29404  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
29405  * amount of time is logged.
29406  */
29407 static void
29408 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
29409 {
29410 	hrtime_t	current = gethrtime();
29411 	char		buf[INET_ADDRSTRLEN];
29412 	ip_stack_t	*ipst = ire->ire_ipst;
29413 
29414 	/* Convert interval in ms to hrtime in ns */
29415 	if (ipst->ips_multirt_bad_mtu_last_time +
29416 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
29417 	    current) {
29418 		cmn_err(CE_WARN, "ip: ignoring multiroute "
29419 		    "to %s, incorrect MTU %u (expected %u)\n",
29420 		    ip_dot_addr(ire->ire_addr, buf),
29421 		    ire->ire_max_frag, max_frag);
29422 
29423 		ipst->ips_multirt_bad_mtu_last_time = current;
29424 	}
29425 }
29426 
29427 
29428 /*
29429  * Get the CGTP (multirouting) filtering status.
29430  * If 0, the CGTP hooks are transparent.
29431  */
29432 /* ARGSUSED */
29433 static int
29434 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
29435 {
29436 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29437 
29438 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
29439 	return (0);
29440 }
29441 
29442 
29443 /*
29444  * Set the CGTP (multirouting) filtering status.
29445  * If the status is changed from active to transparent
29446  * or from transparent to active, forward the new status
29447  * to the filtering module (if loaded).
29448  */
29449 /* ARGSUSED */
29450 static int
29451 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
29452     cred_t *ioc_cr)
29453 {
29454 	long		new_value;
29455 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29456 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29457 
29458 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
29459 		return (EPERM);
29460 
29461 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
29462 	    new_value < 0 || new_value > 1) {
29463 		return (EINVAL);
29464 	}
29465 
29466 	if ((!*ip_cgtp_filter_value) && new_value) {
29467 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
29468 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29469 		    " (module not loaded)" : "");
29470 	}
29471 	if (*ip_cgtp_filter_value && (!new_value)) {
29472 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
29473 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29474 		    " (module not loaded)" : "");
29475 	}
29476 
29477 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29478 		int	res;
29479 		netstackid_t stackid;
29480 
29481 		stackid = ipst->ips_netstack->netstack_stackid;
29482 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
29483 		    new_value);
29484 		if (res)
29485 			return (res);
29486 	}
29487 
29488 	*ip_cgtp_filter_value = (boolean_t)new_value;
29489 
29490 	return (0);
29491 }
29492 
29493 
29494 /*
29495  * Return the expected CGTP hooks version number.
29496  */
29497 int
29498 ip_cgtp_filter_supported(void)
29499 {
29500 	return (ip_cgtp_filter_rev);
29501 }
29502 
29503 
29504 /*
29505  * CGTP hooks can be registered by invoking this function.
29506  * Checks that the version number matches.
29507  */
29508 int
29509 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
29510 {
29511 	netstack_t *ns;
29512 	ip_stack_t *ipst;
29513 
29514 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29515 		return (ENOTSUP);
29516 
29517 	ns = netstack_find_by_stackid(stackid);
29518 	if (ns == NULL)
29519 		return (EINVAL);
29520 	ipst = ns->netstack_ip;
29521 	ASSERT(ipst != NULL);
29522 
29523 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29524 		netstack_rele(ns);
29525 		return (EALREADY);
29526 	}
29527 
29528 	ipst->ips_ip_cgtp_filter_ops = ops;
29529 	netstack_rele(ns);
29530 	return (0);
29531 }
29532 
29533 /*
29534  * CGTP hooks can be unregistered by invoking this function.
29535  * Returns ENXIO if there was no registration.
29536  * Returns EBUSY if the ndd variable has not been turned off.
29537  */
29538 int
29539 ip_cgtp_filter_unregister(netstackid_t stackid)
29540 {
29541 	netstack_t *ns;
29542 	ip_stack_t *ipst;
29543 
29544 	ns = netstack_find_by_stackid(stackid);
29545 	if (ns == NULL)
29546 		return (EINVAL);
29547 	ipst = ns->netstack_ip;
29548 	ASSERT(ipst != NULL);
29549 
29550 	if (ipst->ips_ip_cgtp_filter) {
29551 		netstack_rele(ns);
29552 		return (EBUSY);
29553 	}
29554 
29555 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29556 		netstack_rele(ns);
29557 		return (ENXIO);
29558 	}
29559 	ipst->ips_ip_cgtp_filter_ops = NULL;
29560 	netstack_rele(ns);
29561 	return (0);
29562 }
29563 
29564 /*
29565  * Check whether there is a CGTP filter registration.
29566  * Returns non-zero if there is a registration, otherwise returns zero.
29567  * Note: returns zero if bad stackid.
29568  */
29569 int
29570 ip_cgtp_filter_is_registered(netstackid_t stackid)
29571 {
29572 	netstack_t *ns;
29573 	ip_stack_t *ipst;
29574 	int ret;
29575 
29576 	ns = netstack_find_by_stackid(stackid);
29577 	if (ns == NULL)
29578 		return (0);
29579 	ipst = ns->netstack_ip;
29580 	ASSERT(ipst != NULL);
29581 
29582 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29583 		ret = 1;
29584 	else
29585 		ret = 0;
29586 
29587 	netstack_rele(ns);
29588 	return (ret);
29589 }
29590 
29591 static int
29592 ip_squeue_switch(int val)
29593 {
29594 	int rval = SQ_FILL;
29595 
29596 	switch (val) {
29597 	case IP_SQUEUE_ENTER_NODRAIN:
29598 		rval = SQ_NODRAIN;
29599 		break;
29600 	case IP_SQUEUE_ENTER:
29601 		rval = SQ_PROCESS;
29602 		break;
29603 	default:
29604 		break;
29605 	}
29606 	return (rval);
29607 }
29608 
29609 /* ARGSUSED */
29610 static int
29611 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29612     caddr_t addr, cred_t *cr)
29613 {
29614 	int *v = (int *)addr;
29615 	long new_value;
29616 
29617 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29618 		return (EPERM);
29619 
29620 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29621 		return (EINVAL);
29622 
29623 	ip_squeue_flag = ip_squeue_switch(new_value);
29624 	*v = new_value;
29625 	return (0);
29626 }
29627 
29628 /*
29629  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29630  * ip_debug.
29631  */
29632 /* ARGSUSED */
29633 static int
29634 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29635     caddr_t addr, cred_t *cr)
29636 {
29637 	int *v = (int *)addr;
29638 	long new_value;
29639 
29640 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29641 		return (EPERM);
29642 
29643 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29644 		return (EINVAL);
29645 
29646 	*v = new_value;
29647 	return (0);
29648 }
29649 
29650 /*
29651  * Handle changes to ipmp_hook_emulation ndd variable.
29652  * Need to update phyint_hook_ifindex.
29653  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29654  */
29655 static void
29656 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29657 {
29658 	phyint_t *phyi;
29659 	phyint_t *phyi_tmp;
29660 	char *groupname;
29661 	int namelen;
29662 	ill_t	*ill;
29663 	boolean_t new_group;
29664 
29665 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29666 	/*
29667 	 * Group indicies are stored in the phyint - a common structure
29668 	 * to both IPv4 and IPv6.
29669 	 */
29670 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29671 	for (; phyi != NULL;
29672 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29673 	    phyi, AVL_AFTER)) {
29674 		/* Ignore the ones that do not have a group */
29675 		if (phyi->phyint_groupname_len == 0)
29676 			continue;
29677 
29678 		/*
29679 		 * Look for other phyint in group.
29680 		 * Clear name/namelen so the lookup doesn't find ourselves.
29681 		 */
29682 		namelen = phyi->phyint_groupname_len;
29683 		groupname = phyi->phyint_groupname;
29684 		phyi->phyint_groupname_len = 0;
29685 		phyi->phyint_groupname = NULL;
29686 
29687 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29688 		/* Restore */
29689 		phyi->phyint_groupname_len = namelen;
29690 		phyi->phyint_groupname = groupname;
29691 
29692 		new_group = B_FALSE;
29693 		if (ipst->ips_ipmp_hook_emulation) {
29694 			/*
29695 			 * If the group already exists and has already
29696 			 * been assigned a group ifindex, we use the existing
29697 			 * group_ifindex, otherwise we pick a new group_ifindex
29698 			 * here.
29699 			 */
29700 			if (phyi_tmp != NULL &&
29701 			    phyi_tmp->phyint_group_ifindex != 0) {
29702 				phyi->phyint_group_ifindex =
29703 				    phyi_tmp->phyint_group_ifindex;
29704 			} else {
29705 				/* XXX We need a recovery strategy here. */
29706 				if (!ip_assign_ifindex(
29707 				    &phyi->phyint_group_ifindex, ipst))
29708 					cmn_err(CE_PANIC,
29709 					    "ip_assign_ifindex() failed");
29710 				new_group = B_TRUE;
29711 			}
29712 		} else {
29713 			phyi->phyint_group_ifindex = 0;
29714 		}
29715 		if (ipst->ips_ipmp_hook_emulation)
29716 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29717 		else
29718 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29719 
29720 		/*
29721 		 * For IP Filter to find out the relationship between
29722 		 * names and interface indicies, we need to generate
29723 		 * a NE_PLUMB event when a new group can appear.
29724 		 * We always generate events when a new interface appears
29725 		 * (even when ipmp_hook_emulation is set) so there
29726 		 * is no need to generate NE_PLUMB events when
29727 		 * ipmp_hook_emulation is turned off.
29728 		 * And since it isn't critical for IP Filter to get
29729 		 * the NE_UNPLUMB events we skip those here.
29730 		 */
29731 		if (new_group) {
29732 			/*
29733 			 * First phyint in group - generate group PLUMB event.
29734 			 * Since we are not running inside the ipsq we do
29735 			 * the dispatch immediately.
29736 			 */
29737 			if (phyi->phyint_illv4 != NULL)
29738 				ill = phyi->phyint_illv4;
29739 			else
29740 				ill = phyi->phyint_illv6;
29741 
29742 			if (ill != NULL)
29743 				ill_nic_event_plumb(ill, B_TRUE);
29744 		}
29745 	}
29746 	rw_exit(&ipst->ips_ill_g_lock);
29747 }
29748 
29749 /* ARGSUSED */
29750 static int
29751 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29752     caddr_t addr, cred_t *cr)
29753 {
29754 	int *v = (int *)addr;
29755 	long new_value;
29756 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29757 
29758 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29759 		return (EINVAL);
29760 
29761 	if (*v != new_value) {
29762 		*v = new_value;
29763 		ipmp_hook_emulation_changed(ipst);
29764 	}
29765 	return (0);
29766 }
29767 
29768 static void *
29769 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29770 {
29771 	kstat_t *ksp;
29772 
29773 	ip_stat_t template = {
29774 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29775 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29776 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29777 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29778 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29779 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29780 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29781 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29782 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29783 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29784 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29785 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29786 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29787 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29788 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29789 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29790 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29791 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29792 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29793 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29794 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29795 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29796 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29797 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29798 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29799 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29800 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29801 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29802 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29803 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29804 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29805 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29806 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29807 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29808 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29809 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29810 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29811 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29812 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29813 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29814 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29815 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29816 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29817 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29818 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29819 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29820 	};
29821 
29822 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29823 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29824 	    KSTAT_FLAG_VIRTUAL, stackid);
29825 
29826 	if (ksp == NULL)
29827 		return (NULL);
29828 
29829 	bcopy(&template, ip_statisticsp, sizeof (template));
29830 	ksp->ks_data = (void *)ip_statisticsp;
29831 	ksp->ks_private = (void *)(uintptr_t)stackid;
29832 
29833 	kstat_install(ksp);
29834 	return (ksp);
29835 }
29836 
29837 static void
29838 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29839 {
29840 	if (ksp != NULL) {
29841 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29842 		kstat_delete_netstack(ksp, stackid);
29843 	}
29844 }
29845 
29846 static void *
29847 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29848 {
29849 	kstat_t	*ksp;
29850 
29851 	ip_named_kstat_t template = {
29852 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29853 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29854 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29855 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29856 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29857 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29858 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29859 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29860 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29861 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29862 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29863 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29864 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29865 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29866 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29867 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29868 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29869 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29870 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29871 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29872 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29873 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29874 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29875 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29876 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29877 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29878 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29879 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29880 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29881 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29882 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29883 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29884 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29885 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29886 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29887 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29888 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29889 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29890 	};
29891 
29892 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29893 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29894 	if (ksp == NULL || ksp->ks_data == NULL)
29895 		return (NULL);
29896 
29897 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29898 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29899 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29900 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29901 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29902 
29903 	template.netToMediaEntrySize.value.i32 =
29904 	    sizeof (mib2_ipNetToMediaEntry_t);
29905 
29906 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29907 
29908 	bcopy(&template, ksp->ks_data, sizeof (template));
29909 	ksp->ks_update = ip_kstat_update;
29910 	ksp->ks_private = (void *)(uintptr_t)stackid;
29911 
29912 	kstat_install(ksp);
29913 	return (ksp);
29914 }
29915 
29916 static void
29917 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29918 {
29919 	if (ksp != NULL) {
29920 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29921 		kstat_delete_netstack(ksp, stackid);
29922 	}
29923 }
29924 
29925 static int
29926 ip_kstat_update(kstat_t *kp, int rw)
29927 {
29928 	ip_named_kstat_t *ipkp;
29929 	mib2_ipIfStatsEntry_t ipmib;
29930 	ill_walk_context_t ctx;
29931 	ill_t *ill;
29932 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29933 	netstack_t	*ns;
29934 	ip_stack_t	*ipst;
29935 
29936 	if (kp == NULL || kp->ks_data == NULL)
29937 		return (EIO);
29938 
29939 	if (rw == KSTAT_WRITE)
29940 		return (EACCES);
29941 
29942 	ns = netstack_find_by_stackid(stackid);
29943 	if (ns == NULL)
29944 		return (-1);
29945 	ipst = ns->netstack_ip;
29946 	if (ipst == NULL) {
29947 		netstack_rele(ns);
29948 		return (-1);
29949 	}
29950 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29951 
29952 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29953 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29954 	ill = ILL_START_WALK_V4(&ctx, ipst);
29955 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29956 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29957 	rw_exit(&ipst->ips_ill_g_lock);
29958 
29959 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29960 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29961 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29962 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29963 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29964 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29965 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29966 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29967 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29968 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29969 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29970 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29971 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29972 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29973 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29974 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29975 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29976 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29977 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29978 
29979 	ipkp->routingDiscards.value.ui32 =	0;
29980 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29981 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29982 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29983 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29984 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29985 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29986 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29987 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29988 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29989 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29990 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29991 
29992 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29993 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29994 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29995 
29996 	netstack_rele(ns);
29997 
29998 	return (0);
29999 }
30000 
30001 static void *
30002 icmp_kstat_init(netstackid_t stackid)
30003 {
30004 	kstat_t	*ksp;
30005 
30006 	icmp_named_kstat_t template = {
30007 		{ "inMsgs",		KSTAT_DATA_UINT32 },
30008 		{ "inErrors",		KSTAT_DATA_UINT32 },
30009 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
30010 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
30011 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
30012 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
30013 		{ "inRedirects",	KSTAT_DATA_UINT32 },
30014 		{ "inEchos",		KSTAT_DATA_UINT32 },
30015 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
30016 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
30017 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
30018 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
30019 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
30020 		{ "outMsgs",		KSTAT_DATA_UINT32 },
30021 		{ "outErrors",		KSTAT_DATA_UINT32 },
30022 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
30023 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
30024 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
30025 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
30026 		{ "outRedirects",	KSTAT_DATA_UINT32 },
30027 		{ "outEchos",		KSTAT_DATA_UINT32 },
30028 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
30029 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
30030 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
30031 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
30032 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
30033 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
30034 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
30035 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
30036 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
30037 		{ "outDrops",		KSTAT_DATA_UINT32 },
30038 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
30039 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
30040 	};
30041 
30042 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
30043 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
30044 	if (ksp == NULL || ksp->ks_data == NULL)
30045 		return (NULL);
30046 
30047 	bcopy(&template, ksp->ks_data, sizeof (template));
30048 
30049 	ksp->ks_update = icmp_kstat_update;
30050 	ksp->ks_private = (void *)(uintptr_t)stackid;
30051 
30052 	kstat_install(ksp);
30053 	return (ksp);
30054 }
30055 
30056 static void
30057 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
30058 {
30059 	if (ksp != NULL) {
30060 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
30061 		kstat_delete_netstack(ksp, stackid);
30062 	}
30063 }
30064 
30065 static int
30066 icmp_kstat_update(kstat_t *kp, int rw)
30067 {
30068 	icmp_named_kstat_t *icmpkp;
30069 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
30070 	netstack_t	*ns;
30071 	ip_stack_t	*ipst;
30072 
30073 	if ((kp == NULL) || (kp->ks_data == NULL))
30074 		return (EIO);
30075 
30076 	if (rw == KSTAT_WRITE)
30077 		return (EACCES);
30078 
30079 	ns = netstack_find_by_stackid(stackid);
30080 	if (ns == NULL)
30081 		return (-1);
30082 	ipst = ns->netstack_ip;
30083 	if (ipst == NULL) {
30084 		netstack_rele(ns);
30085 		return (-1);
30086 	}
30087 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
30088 
30089 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
30090 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
30091 	icmpkp->inDestUnreachs.value.ui32 =
30092 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
30093 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
30094 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
30095 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
30096 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
30097 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
30098 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
30099 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
30100 	icmpkp->inTimestampReps.value.ui32 =
30101 	    ipst->ips_icmp_mib.icmpInTimestampReps;
30102 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
30103 	icmpkp->inAddrMaskReps.value.ui32 =
30104 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
30105 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
30106 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
30107 	icmpkp->outDestUnreachs.value.ui32 =
30108 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
30109 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
30110 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
30111 	icmpkp->outSrcQuenchs.value.ui32 =
30112 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
30113 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
30114 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
30115 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
30116 	icmpkp->outTimestamps.value.ui32 =
30117 	    ipst->ips_icmp_mib.icmpOutTimestamps;
30118 	icmpkp->outTimestampReps.value.ui32 =
30119 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
30120 	icmpkp->outAddrMasks.value.ui32 =
30121 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
30122 	icmpkp->outAddrMaskReps.value.ui32 =
30123 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
30124 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
30125 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
30126 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
30127 	icmpkp->outFragNeeded.value.ui32 =
30128 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
30129 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
30130 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
30131 	icmpkp->inBadRedirects.value.ui32 =
30132 	    ipst->ips_icmp_mib.icmpInBadRedirects;
30133 
30134 	netstack_rele(ns);
30135 	return (0);
30136 }
30137 
30138 /*
30139  * This is the fanout function for raw socket opened for SCTP.  Note
30140  * that it is called after SCTP checks that there is no socket which
30141  * wants a packet.  Then before SCTP handles this out of the blue packet,
30142  * this function is called to see if there is any raw socket for SCTP.
30143  * If there is and it is bound to the correct address, the packet will
30144  * be sent to that socket.  Note that only one raw socket can be bound to
30145  * a port.  This is assured in ipcl_sctp_hash_insert();
30146  */
30147 void
30148 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
30149     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
30150     zoneid_t zoneid)
30151 {
30152 	conn_t		*connp;
30153 	queue_t		*rq;
30154 	mblk_t		*first_mp;
30155 	boolean_t	secure;
30156 	ip6_t		*ip6h;
30157 	ip_stack_t	*ipst = recv_ill->ill_ipst;
30158 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
30159 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
30160 	boolean_t	sctp_csum_err = B_FALSE;
30161 
30162 	if (flags & IP_FF_SCTP_CSUM_ERR) {
30163 		sctp_csum_err = B_TRUE;
30164 		flags &= ~IP_FF_SCTP_CSUM_ERR;
30165 	}
30166 
30167 	first_mp = mp;
30168 	if (mctl_present) {
30169 		mp = first_mp->b_cont;
30170 		secure = ipsec_in_is_secure(first_mp);
30171 		ASSERT(mp != NULL);
30172 	} else {
30173 		secure = B_FALSE;
30174 	}
30175 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
30176 
30177 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
30178 	if (connp == NULL) {
30179 		/*
30180 		 * Although raw sctp is not summed, OOB chunks must be.
30181 		 * Drop the packet here if the sctp checksum failed.
30182 		 */
30183 		if (sctp_csum_err) {
30184 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
30185 			freemsg(first_mp);
30186 			return;
30187 		}
30188 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
30189 		return;
30190 	}
30191 	rq = connp->conn_rq;
30192 	if (!canputnext(rq)) {
30193 		CONN_DEC_REF(connp);
30194 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
30195 		freemsg(first_mp);
30196 		return;
30197 	}
30198 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
30199 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
30200 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
30201 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
30202 		if (first_mp == NULL) {
30203 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
30204 			CONN_DEC_REF(connp);
30205 			return;
30206 		}
30207 	}
30208 	/*
30209 	 * We probably should not send M_CTL message up to
30210 	 * raw socket.
30211 	 */
30212 	if (mctl_present)
30213 		freeb(first_mp);
30214 
30215 	/* Initiate IPPF processing here if needed. */
30216 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
30217 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
30218 		ip_process(IPP_LOCAL_IN, &mp,
30219 		    recv_ill->ill_phyint->phyint_ifindex);
30220 		if (mp == NULL) {
30221 			CONN_DEC_REF(connp);
30222 			return;
30223 		}
30224 	}
30225 
30226 	if (connp->conn_recvif || connp->conn_recvslla ||
30227 	    ((connp->conn_ip_recvpktinfo ||
30228 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
30229 	    (flags & IP_FF_IPINFO))) {
30230 		int in_flags = 0;
30231 
30232 		/*
30233 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
30234 		 * IPF_RECVIF.
30235 		 */
30236 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
30237 			in_flags = IPF_RECVIF;
30238 		}
30239 		if (connp->conn_recvslla) {
30240 			in_flags |= IPF_RECVSLLA;
30241 		}
30242 		if (isv4) {
30243 			mp = ip_add_info(mp, recv_ill, in_flags,
30244 			    IPCL_ZONEID(connp), ipst);
30245 		} else {
30246 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
30247 			if (mp == NULL) {
30248 				BUMP_MIB(recv_ill->ill_ip_mib,
30249 				    ipIfStatsInDiscards);
30250 				CONN_DEC_REF(connp);
30251 				return;
30252 			}
30253 		}
30254 	}
30255 
30256 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
30257 	/*
30258 	 * We are sending the IPSEC_IN message also up. Refer
30259 	 * to comments above this function.
30260 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
30261 	 */
30262 	(connp->conn_recv)(connp, mp, NULL);
30263 	CONN_DEC_REF(connp);
30264 }
30265 
30266 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
30267 {									\
30268 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
30269 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
30270 }
30271 /*
30272  * This function should be called only if all packet processing
30273  * including fragmentation is complete. Callers of this function
30274  * must set mp->b_prev to one of these values:
30275  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
30276  * prior to handing over the mp as first argument to this function.
30277  *
30278  * If the ire passed by caller is incomplete, this function
30279  * queues the packet and if necessary, sends ARP request and bails.
30280  * If the ire passed is fully resolved, we simply prepend
30281  * the link-layer header to the packet, do ipsec hw acceleration
30282  * work if necessary, and send the packet out on the wire.
30283  *
30284  * NOTE: IPsec will only call this function with fully resolved
30285  * ires if hw acceleration is involved.
30286  * TODO list :
30287  * 	a Handle M_MULTIDATA so that
30288  *	  tcp_multisend->tcp_multisend_data can
30289  *	  call ip_xmit_v4 directly
30290  *	b Handle post-ARP work for fragments so that
30291  *	  ip_wput_frag can call this function.
30292  */
30293 ipxmit_state_t
30294 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io,
30295     boolean_t flow_ctl_enabled, conn_t *connp)
30296 {
30297 	nce_t		*arpce;
30298 	ipha_t		*ipha;
30299 	queue_t		*q;
30300 	int		ill_index;
30301 	mblk_t		*nxt_mp, *first_mp;
30302 	boolean_t	xmit_drop = B_FALSE;
30303 	ip_proc_t	proc;
30304 	ill_t		*out_ill;
30305 	int		pkt_len;
30306 
30307 	arpce = ire->ire_nce;
30308 	ASSERT(arpce != NULL);
30309 
30310 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
30311 
30312 	mutex_enter(&arpce->nce_lock);
30313 	switch (arpce->nce_state) {
30314 	case ND_REACHABLE:
30315 		/* If there are other queued packets, queue this packet */
30316 		if (arpce->nce_qd_mp != NULL) {
30317 			if (mp != NULL)
30318 				nce_queue_mp_common(arpce, mp, B_FALSE);
30319 			mp = arpce->nce_qd_mp;
30320 		}
30321 		arpce->nce_qd_mp = NULL;
30322 		mutex_exit(&arpce->nce_lock);
30323 
30324 		/*
30325 		 * Flush the queue.  In the common case, where the
30326 		 * ARP is already resolved,  it will go through the
30327 		 * while loop only once.
30328 		 */
30329 		while (mp != NULL) {
30330 
30331 			nxt_mp = mp->b_next;
30332 			mp->b_next = NULL;
30333 			ASSERT(mp->b_datap->db_type != M_CTL);
30334 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
30335 			/*
30336 			 * This info is needed for IPQOS to do COS marking
30337 			 * in ip_wput_attach_llhdr->ip_process.
30338 			 */
30339 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
30340 			mp->b_prev = NULL;
30341 
30342 			/* set up ill index for outbound qos processing */
30343 			out_ill = ire_to_ill(ire);
30344 			ill_index = out_ill->ill_phyint->phyint_ifindex;
30345 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
30346 			    ill_index, &ipha);
30347 			if (first_mp == NULL) {
30348 				xmit_drop = B_TRUE;
30349 				BUMP_MIB(out_ill->ill_ip_mib,
30350 				    ipIfStatsOutDiscards);
30351 				goto next_mp;
30352 			}
30353 
30354 			/* non-ipsec hw accel case */
30355 			if (io == NULL || !io->ipsec_out_accelerated) {
30356 				/* send it */
30357 				q = ire->ire_stq;
30358 				if (proc == IPP_FWD_OUT) {
30359 					UPDATE_IB_PKT_COUNT(ire);
30360 				} else {
30361 					UPDATE_OB_PKT_COUNT(ire);
30362 				}
30363 				ire->ire_last_used_time = lbolt;
30364 
30365 				if (flow_ctl_enabled || canputnext(q)) {
30366 					if (proc == IPP_FWD_OUT) {
30367 
30368 					BUMP_MIB(out_ill->ill_ip_mib,
30369 					    ipIfStatsHCOutForwDatagrams);
30370 
30371 					}
30372 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
30373 					    pkt_len);
30374 
30375 					DTRACE_IP7(send, mblk_t *, first_mp,
30376 					    conn_t *, NULL, void_ip_t *, ipha,
30377 					    __dtrace_ipsr_ill_t *, out_ill,
30378 					    ipha_t *, ipha, ip6_t *, NULL, int,
30379 					    0);
30380 
30381 					ILL_SEND_TX(out_ill,
30382 					    ire, connp, first_mp, 0);
30383 				} else {
30384 					BUMP_MIB(out_ill->ill_ip_mib,
30385 					    ipIfStatsOutDiscards);
30386 					xmit_drop = B_TRUE;
30387 					freemsg(first_mp);
30388 				}
30389 			} else {
30390 				/*
30391 				 * Safety Pup says: make sure this
30392 				 *  is going to the right interface!
30393 				 */
30394 				ill_t *ill1 =
30395 				    (ill_t *)ire->ire_stq->q_ptr;
30396 				int ifindex =
30397 				    ill1->ill_phyint->phyint_ifindex;
30398 				if (ifindex !=
30399 				    io->ipsec_out_capab_ill_index) {
30400 					xmit_drop = B_TRUE;
30401 					freemsg(mp);
30402 				} else {
30403 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
30404 					    pkt_len);
30405 
30406 					DTRACE_IP7(send, mblk_t *, first_mp,
30407 					    conn_t *, NULL, void_ip_t *, ipha,
30408 					    __dtrace_ipsr_ill_t *, ill1,
30409 					    ipha_t *, ipha, ip6_t *, NULL,
30410 					    int, 0);
30411 
30412 					ipsec_hw_putnext(ire->ire_stq, mp);
30413 				}
30414 			}
30415 next_mp:
30416 			mp = nxt_mp;
30417 		} /* while (mp != NULL) */
30418 		if (xmit_drop)
30419 			return (SEND_FAILED);
30420 		else
30421 			return (SEND_PASSED);
30422 
30423 	case ND_INITIAL:
30424 	case ND_INCOMPLETE:
30425 
30426 		/*
30427 		 * While we do send off packets to dests that
30428 		 * use fully-resolved CGTP routes, we do not
30429 		 * handle unresolved CGTP routes.
30430 		 */
30431 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
30432 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
30433 
30434 		if (mp != NULL) {
30435 			/* queue the packet */
30436 			nce_queue_mp_common(arpce, mp, B_FALSE);
30437 		}
30438 
30439 		if (arpce->nce_state == ND_INCOMPLETE) {
30440 			mutex_exit(&arpce->nce_lock);
30441 			DTRACE_PROBE3(ip__xmit__incomplete,
30442 			    (ire_t *), ire, (mblk_t *), mp,
30443 			    (ipsec_out_t *), io);
30444 			return (LOOKUP_IN_PROGRESS);
30445 		}
30446 
30447 		arpce->nce_state = ND_INCOMPLETE;
30448 		mutex_exit(&arpce->nce_lock);
30449 		/*
30450 		 * Note that ire_add() (called from ire_forward())
30451 		 * holds a ref on the ire until ARP is completed.
30452 		 */
30453 
30454 		ire_arpresolve(ire, ire_to_ill(ire));
30455 		return (LOOKUP_IN_PROGRESS);
30456 	default:
30457 		ASSERT(0);
30458 		mutex_exit(&arpce->nce_lock);
30459 		return (LLHDR_RESLV_FAILED);
30460 	}
30461 }
30462 
30463 #undef	UPDATE_IP_MIB_OB_COUNTERS
30464 
30465 /*
30466  * Return B_TRUE if the buffers differ in length or content.
30467  * This is used for comparing extension header buffers.
30468  * Note that an extension header would be declared different
30469  * even if all that changed was the next header value in that header i.e.
30470  * what really changed is the next extension header.
30471  */
30472 boolean_t
30473 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
30474     uint_t blen)
30475 {
30476 	if (!b_valid)
30477 		blen = 0;
30478 
30479 	if (alen != blen)
30480 		return (B_TRUE);
30481 	if (alen == 0)
30482 		return (B_FALSE);	/* Both zero length */
30483 	return (bcmp(abuf, bbuf, alen));
30484 }
30485 
30486 /*
30487  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
30488  * Return B_FALSE if memory allocation fails - don't change any state!
30489  */
30490 boolean_t
30491 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30492     const void *src, uint_t srclen)
30493 {
30494 	void *dst;
30495 
30496 	if (!src_valid)
30497 		srclen = 0;
30498 
30499 	ASSERT(*dstlenp == 0);
30500 	if (src != NULL && srclen != 0) {
30501 		dst = mi_alloc(srclen, BPRI_MED);
30502 		if (dst == NULL)
30503 			return (B_FALSE);
30504 	} else {
30505 		dst = NULL;
30506 	}
30507 	if (*dstp != NULL)
30508 		mi_free(*dstp);
30509 	*dstp = dst;
30510 	*dstlenp = dst == NULL ? 0 : srclen;
30511 	return (B_TRUE);
30512 }
30513 
30514 /*
30515  * Replace what is in *dst, *dstlen with the source.
30516  * Assumes ip_allocbuf has already been called.
30517  */
30518 void
30519 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30520     const void *src, uint_t srclen)
30521 {
30522 	if (!src_valid)
30523 		srclen = 0;
30524 
30525 	ASSERT(*dstlenp == srclen);
30526 	if (src != NULL && srclen != 0)
30527 		bcopy(src, *dstp, srclen);
30528 }
30529 
30530 /*
30531  * Free the storage pointed to by the members of an ip6_pkt_t.
30532  */
30533 void
30534 ip6_pkt_free(ip6_pkt_t *ipp)
30535 {
30536 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30537 
30538 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30539 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30540 		ipp->ipp_hopopts = NULL;
30541 		ipp->ipp_hopoptslen = 0;
30542 	}
30543 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30544 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30545 		ipp->ipp_rtdstopts = NULL;
30546 		ipp->ipp_rtdstoptslen = 0;
30547 	}
30548 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30549 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30550 		ipp->ipp_dstopts = NULL;
30551 		ipp->ipp_dstoptslen = 0;
30552 	}
30553 	if (ipp->ipp_fields & IPPF_RTHDR) {
30554 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30555 		ipp->ipp_rthdr = NULL;
30556 		ipp->ipp_rthdrlen = 0;
30557 	}
30558 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30559 	    IPPF_RTHDR);
30560 }
30561 
30562 zoneid_t
30563 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_stack_t *ipst,
30564     zoneid_t lookup_zoneid)
30565 {
30566 	ire_t		*ire;
30567 	int		ire_flags = MATCH_IRE_TYPE;
30568 	zoneid_t	zoneid = ALL_ZONES;
30569 
30570 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
30571 		return (ALL_ZONES);
30572 
30573 	if (lookup_zoneid != ALL_ZONES)
30574 		ire_flags |= MATCH_IRE_ZONEONLY;
30575 	ire = ire_ctable_lookup(addr, NULL, IRE_LOCAL | IRE_LOOPBACK, NULL,
30576 	    lookup_zoneid, NULL, ire_flags, ipst);
30577 	if (ire != NULL) {
30578 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
30579 		ire_refrele(ire);
30580 	}
30581 	return (zoneid);
30582 }
30583 
30584 zoneid_t
30585 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
30586     ip_stack_t *ipst, zoneid_t lookup_zoneid)
30587 {
30588 	ire_t		*ire;
30589 	int		ire_flags = MATCH_IRE_TYPE;
30590 	zoneid_t	zoneid = ALL_ZONES;
30591 	ipif_t		*ipif_arg = NULL;
30592 
30593 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
30594 		return (ALL_ZONES);
30595 
30596 	if (IN6_IS_ADDR_LINKLOCAL(addr)) {
30597 		ire_flags |= MATCH_IRE_ILL_GROUP;
30598 		ipif_arg = ill->ill_ipif;
30599 	}
30600 	if (lookup_zoneid != ALL_ZONES)
30601 		ire_flags |= MATCH_IRE_ZONEONLY;
30602 	ire = ire_ctable_lookup_v6(addr, NULL, IRE_LOCAL | IRE_LOOPBACK,
30603 	    ipif_arg, lookup_zoneid, NULL, ire_flags, ipst);
30604 	if (ire != NULL) {
30605 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
30606 		ire_refrele(ire);
30607 	}
30608 	return (zoneid);
30609 }
30610 
30611 /*
30612  * IP obserability hook support functions.
30613  */
30614 
30615 static void
30616 ipobs_init(ip_stack_t *ipst)
30617 {
30618 	ipst->ips_ipobs_enabled = B_FALSE;
30619 	list_create(&ipst->ips_ipobs_cb_list, sizeof (ipobs_cb_t),
30620 	    offsetof(ipobs_cb_t, ipobs_cbnext));
30621 	mutex_init(&ipst->ips_ipobs_cb_lock, NULL, MUTEX_DEFAULT, NULL);
30622 	ipst->ips_ipobs_cb_nwalkers = 0;
30623 	cv_init(&ipst->ips_ipobs_cb_cv, NULL, CV_DRIVER, NULL);
30624 }
30625 
30626 static void
30627 ipobs_fini(ip_stack_t *ipst)
30628 {
30629 	ipobs_cb_t *cb;
30630 
30631 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30632 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30633 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30634 
30635 	while ((cb = list_head(&ipst->ips_ipobs_cb_list)) != NULL) {
30636 		list_remove(&ipst->ips_ipobs_cb_list, cb);
30637 		kmem_free(cb, sizeof (*cb));
30638 	}
30639 	list_destroy(&ipst->ips_ipobs_cb_list);
30640 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30641 	mutex_destroy(&ipst->ips_ipobs_cb_lock);
30642 	cv_destroy(&ipst->ips_ipobs_cb_cv);
30643 }
30644 
30645 void
30646 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
30647     const ill_t *ill, int ipver, uint32_t hlen, ip_stack_t *ipst)
30648 {
30649 	ipobs_cb_t *ipobs_cb;
30650 
30651 	ASSERT(DB_TYPE(mp) == M_DATA);
30652 
30653 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30654 	ipst->ips_ipobs_cb_nwalkers++;
30655 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30656 	for (ipobs_cb = list_head(&ipst->ips_ipobs_cb_list); ipobs_cb != NULL;
30657 	    ipobs_cb = list_next(&ipst->ips_ipobs_cb_list, ipobs_cb)) {
30658 		mblk_t  *mp2 = allocb(sizeof (ipobs_hook_data_t),
30659 		    BPRI_HI);
30660 		if (mp2 != NULL) {
30661 			ipobs_hook_data_t *ihd =
30662 			    (ipobs_hook_data_t *)mp2->b_rptr;
30663 			if (((ihd->ihd_mp = dupmsg(mp)) == NULL) &&
30664 			    ((ihd->ihd_mp = copymsg(mp)) == NULL)) {
30665 				freemsg(mp2);
30666 				continue;
30667 			}
30668 			ihd->ihd_mp->b_rptr += hlen;
30669 			ihd->ihd_htype = htype;
30670 			ihd->ihd_ipver = ipver;
30671 			ihd->ihd_zsrc = zsrc;
30672 			ihd->ihd_zdst = zdst;
30673 			ihd->ihd_ifindex = ill->ill_phyint->phyint_ifindex;
30674 			ihd->ihd_stack = ipst->ips_netstack;
30675 			mp2->b_wptr += sizeof (*ihd);
30676 			ipobs_cb->ipobs_cbfunc(mp2);
30677 		}
30678 	}
30679 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30680 	ipst->ips_ipobs_cb_nwalkers--;
30681 	if (ipst->ips_ipobs_cb_nwalkers == 0)
30682 		cv_broadcast(&ipst->ips_ipobs_cb_cv);
30683 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30684 }
30685 
30686 void
30687 ipobs_register_hook(netstack_t *ns, pfv_t func)
30688 {
30689 	ipobs_cb_t   *cb;
30690 	ip_stack_t *ipst = ns->netstack_ip;
30691 
30692 	cb = kmem_alloc(sizeof (*cb), KM_SLEEP);
30693 
30694 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30695 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30696 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30697 	ASSERT(ipst->ips_ipobs_cb_nwalkers == 0);
30698 
30699 	cb->ipobs_cbfunc = func;
30700 	list_insert_head(&ipst->ips_ipobs_cb_list, cb);
30701 	ipst->ips_ipobs_enabled = B_TRUE;
30702 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30703 }
30704 
30705 void
30706 ipobs_unregister_hook(netstack_t *ns, pfv_t func)
30707 {
30708 	ipobs_cb_t	*curcb;
30709 	ip_stack_t	*ipst = ns->netstack_ip;
30710 
30711 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30712 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30713 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30714 
30715 	for (curcb = list_head(&ipst->ips_ipobs_cb_list); curcb != NULL;
30716 	    curcb = list_next(&ipst->ips_ipobs_cb_list, curcb)) {
30717 		if (func == curcb->ipobs_cbfunc) {
30718 			list_remove(&ipst->ips_ipobs_cb_list, curcb);
30719 			kmem_free(curcb, sizeof (*curcb));
30720 			break;
30721 		}
30722 	}
30723 	if (list_is_empty(&ipst->ips_ipobs_cb_list))
30724 		ipst->ips_ipobs_enabled = B_FALSE;
30725 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30726 }
30727